Web-Development-Using-PHP-MySQL-notes
Web-Development-Using-PHP-MySQL-notes
Com (Hons), BBA & BAJMC II Year Subject: Web Development Using PHP & MySQL
UNIT -1
Introduction to PHP & Features
PHP is a server scripting language, and a powerful tool for making dynamic and interactiveWeb
pages.
PHP is a widely-used, free, and efficient alternative to competitors such as Microsoft's ASP.
What is PHP?
• PHP is an acronym for "PHP: Hypertext Preprocessor"
• PHP is a widely-used, open source scripting language
• PHP scripts are executed on the server
• PHP is free to download and use
What is a PHP File?
• PHP files can contain text, HTML, CSS, JavaScript, and PHP code
• PHP code are executed on the server, and the result is returned to the browseras
plain HTML
• PHP files have extension ".php"
What Can PHP Do?
• PHP can generate dynamic page content
• PHP can create, open, read, write, delete, and close files on the server
• PHP can collect form data
• PHP can send and receive cookies
• PHP can add, delete, modify data in your database
• PHP can be used to control user-access
• PHP can encrypt data
With PHP you are not limited to output HTML. You can output images, PDF files, and
even Flash movies. You can also output any text, such as XHTML and XML.
Why PHP?
• PHP runs on various platforms (Windows, Linux, Unix, Mac OS X, etc.)
• PHP is compatible with almost all servers used today (Apache, IIS, etc.)
• PHP supports a wide range of databases
• PHP is free. Download it from the official PHP resource: www.php.net
• PHP is easy to learn and runs efficiently on the server side
To start using PHP, you can:
• Find a web host with PHP and MySQL support
• Install a web server on your own PC, and then install PHP and MySQL
Use a Web Host with PHP Support
• If your server has activated support for PHP you do not need to do anything.
• Just create some .php files, place them in your web directory, and the server will
Class: - B.Com, B.Com (Hons), BBA & BAJMC II Year Subject: Web Development Using PHP & MySQL
Example
<?php
</html>
Comments in PHP
A comment in PHP code is a line that is not read/executed as part of the program. Its
only purpose is to be read by someone who is looking at the code.
Comments can be used to:
• Let others understand what you are doing
• Remind yourself of what you did - Most programmers have experienced coming
back to their own work a year or two later and having to re-figure out what they did.
Comments can remind you of what you were thinking when you wrote the code
Example
<html>
<body>
<?php
// This is a single-line comment
# This is also a single-line
comment /*
This is a multiple-lines comment
block that spans over multiple
Class: - B.Com, B.Com (Hons), BBA & BAJMC II Year Subject: Web Development Using PHP & MySQL
lines
*/
// You can also use comments to leave out parts of a code line
$x = 5 /* + 15 */ + 5;
echo
$x; ?>
</body>
</html>
Variables
A variable can have a short name (like x and y) or a more descriptive name (age,
carname, total_volume).
• A variable starts with the $ sign, followed by the name of the variable
• A variable name must start with a letter or the underscore character
• A variable name cannot start with a number
• A variable name can only contain alpha-numeric characters and underscores (A-z,
0-9, and _ )
• Variable names are case-sensitive ($age and $AGE are two different variables)
Output Variables
• The PHP echo statement is often used to output data to the screen.
PHP Variables Scope
• In PHP, variables can be declared anywhere in the script.
• The scope of a variable is the part of the script where the variable can be
referenced/used.
PHP has three different variable scopes:
• local
• global
• static
Global and Local Scope
A variable declared outside a function has a GLOBAL SCOPE and can only be accessed
outside a function:
A variable declared within a function has a LOCAL SCOPE and can only be accessedwithin
that function:
The global Keyword
• The global keyword is used to access a global variable from within a function.
• To do this, use the global keyword before the variables (inside the function):
The static Keyword
Normally, when a function is completed/executed, all of its variables are deleted. However,
Class: - B.Com, B.Com (Hons), BBA & BAJMC II Year Subject: Web Development Using PHP & MySQL
sometimes we want a local variable NOT to be deleted. We need it for a further job.
echo and print Statements
• In PHP there are two basic ways to get output: echo and print.
• In this tutorial we use echo (and print) in almost every example. So, this chapter
contains a little more info about those two output statements.
• echo and print are more or less the same. They are both used to output data tothe
screen.
• The differences are small: echo has no return value while print has a return value
of 1 so it can be used in expressions. echo can take multiple parameters (although
such usage is rare) while print can take one argument. echo is marginally faster than
print.
Echo Statement
The echo statement can be used with or without parentheses: echo or echo().
Data Types
• Variables can store data of different types, and different data types can do
different things.
PHP supports the following data types:
• String
• Integer
• Float (floating point numbers - also called double)
• Boolean
• Array
• Object
• NULL
• Resource
PHP String
• A string is a sequence of characters, like "Hello world!".
• A string can be any text inside quotes. You can use single or double quotes:
PHP Integer
An integer data type is a non-decimal number between -2,147,483,648 and
2,147,483,647.
Rules for integers:
• An integer must have at least one digit
• An integer must not have a decimal point
• An integer can be either positive or negative
• Integers can be specified in three formats: decimal (10-based), hexadecimal (16-
based - prefixed with 0x) or octal (8-based - prefixed with 0)
• In the following example $x is an integer. The PHP var_dump() function
returns the data type and value:
PHP Float
• A float (floating point number) is a number with a decimal point or a number in
exponential form.
• In the following example $x is a float. The PHP var_dump() function returns the
Class: - B.Com, B.Com (Hons), BBA & BAJMC II Year Subject: Web Development Using PHP & MySQL
array();
x=y
x=y The left operand gets set to the value of the expression
on the right
x += y
x=x+y Addition
x -= y
x=x-y Subtraction
x *= y
x=x*y Multiplication
x /= y
x=x/y Division
x %= y
x=x%y Modulus
=== Identical $x === $y Returns true if $x is equal to $y, and they are of
the same type
!== Not identical $x !== $y Returns true if $x is not equal to $y, or they are
not of the same type
<= Less than or equal $x <= $y Returns true if $x is less than or equal to $y
to
• PHP has two operators that are specially designed for strings.
=== Identity $x === Returns true if $x and $y have the same key/valuepairs
$y in the same order and of the same types
Syntax
if (condition) {
code to be executed if condition is true;
} else {
code to be executed if condition is false;
}
The if.... elseif... else statement executes different codes for more than two conditions.
Syntax
if (condition) {
code to be executed if this condition is true;
} elseif (condition) {
code to be executed if this condition is true;
} else {
code to be executed if all conditions are false;
}
Use the switch statement to select one of many blocks of code to be executed.
Syntax
switch (n)
{ case
label1:
code to be executed if n=label1;
break
; case
label2:
code to be executed if n=label2;
break
; case
label3:
code to be executed if n=label3;
break;
...
default:
code to be executed if n is different from all labels;
Class: - B.Com, B.Com (Hons), BBA & BAJMC II Year Subject: Web Development Using PHP & MySQL
This is how it works: First we have a single expression n (most often a variable), that
is evaluated once. The value of the expression is then compared with the values for
each case in the structure. If there is a match, the block of code associated with that
case is executed. Use break to prevent the code from running into the next case
automatically.The default statement is used if no match is found.
PHP Loops
Often when you write code, you want the same block of code to run over and over again
in a row. Instead of adding several almost equal code-lines in a script, we can use loops
to perform a task like this.
• The while loop executes a block of code as long as the specified condition is
true.
Syntax
while (condition is true) {
code to be executed;
}
The PHP do...while Loop
The do...while loop will always execute the block of code once, it will then check the
condition, and repeat the loop while the specified condition is true.
Syntax
do {
code to be
executed; }while
(condition is true);
for Loops
• The for loop is used when you know in advance how many times the
scriptshould run.
Syntax
for (init counter; test counter; increment counter) {
code to be executed;
}
Parameters:
• The foreach loop works only on arrays, and is used to loop through
eachkey/value pair in an array.
Syntax
• For every loop iteration, the value of the current array element is assigned to
$value and the array pointer is moved by one, until it reaches the last array
element.
Class: - B.Com, B.Com (Hons), BBA & BAJMC II Year Subject: Web Development Using PHP & MySQL
Unit-2
Functions
The real power of PHP comes from its functions; it has more than 1000 built-in
functions. Functions are blocks of codes that perform specific task in php. It makes the codes
reusable and shorthand. it can be categorized into two groups.
• Predefined functions
• User defined functions
Predefined Functions
Predefined function (plural predefined functions) (computing) Any of a set of subroutines that perform
standard mathematical functions included in a programming language; either included in a program at
compilation time, or called when a program is executed. Predefined functions are the inbuilt functions of php.
These functions can be subdivided into multiple categories as stated below.
• string functions
• numeric functions
• date and time functions
• array functions
• directory functions
String Function
strtolower(); -> converts all characters of the string to lower case
strtoupper(); -> converts all characters of the string to upper case
ucfirst(); -> converts first letter to upper case
ucwords(); -> converts first letter of each word to upper case
strlen(); -> counts number of characters in a string and returns integer value
trim(); -> trims unnecessary spaces
ltrim(); -> trims unnecessary spaces from left
rtrim(); -> trims unnecessary spaces from right
sprintf("%s,%s,%s",$a,$b,$c); -> placeholder to keep the value
str_word_count() -> count the number of words
$count = str_word_count($x,1) -> returns array
strstr(); echo strstr($str,U,true);
stristr(); case insensitive strstr
str_replace() -> search and replace characters from the string
str_repeat() -> repeats the string
substr(int,int) -> prints a string from defined initial character number to defined last number
strpos() -> finds position of the string
Numeric Function
abs() -> returns positive value of a number
sqrt() -> returns square root of a number
round() -> rounds a floating number
floor() -> rounds a number down to a nearest integer
ceil() -> rounds a number up to a nearest integer
rand() -> generates a random integer
mt_rand() -> generates random number between defined inital and end number
pow() -> returns x raised to the power of y
pi() -> returns the value of pi
min() -> returns the lowest value from an array
max() -> returns the highest value from an array
fmod() -> returns the remainder from x/y {%}
bindec() -> converts a binary number to a decimal number
decbin() -> converts a decimal number to a binary number
deg2rad() -> converts a degree value to a radian value
Class: - B.Com, B.Com (Hons), BBA & BAJMC II Year Subject: Web Development Using PHP & MySQL
Array Functions
array() -> creates an array
sizeof() -> counts the number of values in an array
sort() -> sorts an indexed array in ascending order
in_array() -> checks if a specified value is in array
list() -> keep array values in variable
compact() -> keeps variable values in associative array
arsort() -> sorts an associative array in descending order according to the value
array_unique() -> removes duplicate values from an array
explode() -> converts string to array
implode() -> converts array to string
extract() -> converts array to variable
array_sum() -> returns the sum of values in an array
array_shift() -> removes the first element of an array and returns the first value from the array
array_pop() -> deletes the last element from an array
array_merge() -> merges multiple arrays
array_search() -> searches for a defined value in an array and returns the key for that value
array_reverse() -> returns an array in reverse order
array_keys() -> returns all the keys from an array
PHP Date/Time Functions
PHP date() Function: The PHP date() function converts timestamp to a more readable date and
time format.
Syntax:
date(format, timestamp)
• The format parameter in the date() function specifies the format of returned date and time.
• The timestamp is an optional parameter, if it is not included then the current date and time will
be used.
Formatting options available in date() function: The format parameter of the date() function is a
string that can contain multiple characters allowing to generate the dates in various formats. Date-
related formatting characters that are commonly used in the format string:
• d: Represents day of the month; two digits with leading zeros (01 or 31).
• D: Represents day of the week in the text as an abbreviation (Mon to Sun).
• m: Represents month in numbers with leading zeros (01 or 12).
• M: Represents month in text, abbreviated (Jan to Dec).
• y: Represents year in two digits (08 or 14).
• Y: Represents year in four digits (2008 or 2014).
The parts of the date can be separated by inserting other characters, like hyphens (-), dots (.),
slashes (/), or spaces to add additional visual formatting.
PHP time() Function: The time() function is used to get the current time as a Unix timestamp (the
number of seconds since the beginning of the Unix epoch: January 1, 1970, 00:00:00 GMT).
The following characters can be used to format the time string:
• h: Represents hour in 12-hour format with leading zeros (01 to 12).
• H: Represents hour in 24-hour format with leading zeros (00 to 23).
• i: Represents minutes with leading zeros (00 to 59).
• s: Represents seconds with leading zeros (00 to 59).
• a: Represents lowercase antemeridian and post meridian (am or pm).
Class: - B.Com, B.Com (Hons), BBA & BAJMC II Year Subject: Web Development Using PHP & MySQL
• Besides the built-in PHP functions, we can create our own functions.
• A function is a block of statements that can be used repeatedly in a program.
• A function will not execute immediately when a page loads.
• A function will be executed by a call to the function.
Defining a Function in PHP
Syn
tax
function
functionName() {
code to be executed;
}
• Function names are NOT case-sensitive.
In the example below, we create a function named "writeMsg()". The opening curly
brace ( { ) indicates the beginning of the function code and the closing curly brace ( } )
indicates the end of the function. The function outputs "Hello world!". To call the
function, just write its name:
Example
<html>
<body>
<?php
function
writeMsg()echo
"Hello world!";
}
writeMsg();
?>
</body>
Class: - B.Com, B.Com (Hons), BBA & BAJMC II Year Subject: Web Development Using PHP & MySQL
</html>
The following example shows how to use a default parameter. If we call the
function setHeight() without arguments it takes the default value as
argument:
Example
<html>
<body>
<?php
function setHeight($minheight = 50) {
echo "The height is : $minheight
<br>";
}
setHeight(3
50);
setHeight();
setHeight(1
35);
setHeight(8
0);
?>
</body>
</html>
PHP Functions - Returning values
Unit -4
Introduction
Sure the idea of dynamic web pages is cool, but you can only go far with what’s built into PHP,
like changing the page based on the day of the week. What you’d really like to do is make a web
page unique for each visitor, and that’s where databases come in.
We will begin this chapter assuming that the reader has absolutely no knowledge of MySQL or
databases. First, we’ll explain databases, then we’ll create one the easy way
— using phpMyAdmin. Then we’ll cover how to create databases and tables using SQL,
and in the next chapter we’ll show how all this can be done using PHP.
Databases help to organize and track things. Databases allow you to use creativity to
group things together in meaningful ways, and to present the same set of information
in different ways to different audiences.
Database is simply an organized collection of data stored in a computer.
Databases are composed of one or more “tables”. Tables are composed of parts called
“rows” and “columns” similar to what you would see in a spreadsheet. The columns
section of each table declares the characteristics of each table while each row contains
unique data for each element in the table.
It may sound complicated but actually it is quite simple. Take the example below
Table: Cars
Class: - B.Com, B.Com (Hons), BBA & BAJMC II Year Subject: Web Development Using PHP & MySQL
We can clearly see that the elements in this table has seven columns defined as ID, VIN,
Make, Model, Style, Year, and Price. The table has four rows that describe four different
cars—a Ford Explorer, Dodge RAM, Mazda 6, and a Subaru Outback.
Tables are just a collection of things that you want to keep track of.
Columns hold the different attributes of each element in that table. Rows in a
table hold different instances uniquely defined by the table’s columns. Databases
are a collection of tables.
just enter this address into your browser or click on this link:
http://localhost/phpmyadmin/ Clicking that link should take you to a page that is
similar to this:
Class: - B.Com, B.Com (Hons), BBA & BAJMC II Year Subject: Web Development Using PHP &
MySQL
What is phpMyAdmin?
phpMyAdmin is a free software tool—that just happens to be written in PHP itself— that
is intended to handle many common administration tasks of MySQL using a browser.
phpMyAdmin supports a wide range of operations with MySQL. The most frequently
used operations are supported by the user interface (managing databases, tables, fields,
relations, indexes, users, permissions, etc), and you still have the ability to directly
execute a SQL statement if you prefer.
First navigate such that you have phpMyAdmin on the screen. Click on the link that
says Databases:
In the box that says Create new database, type the word ‘Cars’, then click on the
Create button. If it worked properly, you should see a yellow confirmation box appear
on the screen briefly, as below:
Class: - B.Com, B.Com (Hons), BBA & BAJMC II Year Subject: Web Development Using PHP &
MySQL
Introduction to SQL
and, in fact, phpMyAdmin actually executed that exact SQL command in the
background for you when you clicked on the button. In other words, you can think
of phpMyAdmin as a tool that builds SQL commands for you.
Now that the database is created, we would like to use it. Find the cars database in
the list of databases, then click on the database name.
Class: - B.Com, B.Com (Hons), BBA & BAJMC II Year Subject: Web Development Using PHP & MySQL
This tells the MySQL database that you are going to work in the database *cars*
until you say otherwise.
You have just created the database for our fictional used car lot. We will develop
this database more as we go along.
So far, you have created your database, and figured out the general structure of
PHPMyAdmin. Now you will need to put a table inside of the database you have
created. In the case of our cars database, we will need to define the table to describe
the cars and trucks that Sam has for sale on his used car lot.
Class: - B.Com, B.Com (Hons), BBA & BAJMC II Year Subject: Web Development Using PHP &
MySQL
Before creating your table, think about what you are going to put into the table and what
are the various attributes that might distinguish one row (car) from another.
I can think of a number of properties or attributes that distinguish one car from
another on a used car lot.
Year
Make
Model
Trim
Exterior color
Interior color
Asking Price
Purchase Price
Mileage
Transmission
Purchase Date
Sale Date
Sale Price
Class: - B.Com, B.Com (Hons), BBA & BAJMC II Year Subject: Web Development Using PHP &
MySQL
That should be enough to at least let us get started. Now we have to figure out
what kind of data we are going to put in these categories.
Datatypes
For learning purposes, there are really only three types of data you will need to use.
They are:
1. Numbers
2. Characters
3. Dates
Numbers
Numbers, as the name probably gives away, are any kind of numeric information. Will you
need to use any kind of decimals for the data that you are going to store? In that case,
you will need to use the datatype decimal or float. If not, you can use the datatype int
(short for integer) or bigint (a big integer—which takes up more space, but can
handle bigger numbers).
Characters
The character type in MySQL is the data type you use to store Strings. Characters are used
to store the representation of a letter, word, or series of words. For example the letter A and
the phrase ‘Hello World’ would both be of a character type. MySQL calls this a
VARCHAR, short for variable characters It is variable because you only set the maximum
number of characters that the field can hold, and if you put in a value with fewer
characters, the shorter value will be stored. Other databases, such as Microsoft SQL Server,
offer the CHAR datatype, which will fill in any unused characters with spaces. Why
anyone would want that I can’t imagine, so for simplicity we’ll stick to VARCHAR for
now.
Use the datatype varchar(n) to define a column that you would like to represent with
a character. Substitute the n in varchar(n) with the maximum amount of letters a
Class: - B.Com, B.Com (Hons), BBA & BAJMC II Year Subject: Web Development Using PHP &
MySQL
column in your table can have (up to 255). Spaces, tabs, and newlines in a paragraph
all count as characters.
Dates
Dates are a way to store dates in the database. Do you just want to store the date and not the
time? Use the datatype date. Do you want to store the time and not the date? Use the datatype
time. Want to store the date and the time? Use the datatype datetime.
Let’s look back at our characteristics of cars to decide what kind of datatype they
should be.
That about sums up the table that we need to create to track our cars. Since the VIN is the
only truly unique element in the list, we will make this the “Primary Key”.
Defining a column as a primary key means that the column will only be able to have unique
values (i.e. nothing can repeat itself). In the case of this specific table, it means that you can’t
enter two cars with the same VIN into the database, because we have just told mySQL that this
isn’t allowed. Some examples of this in everyday life are license plate numbers, credit card
numbers, and social security numbers. All of these numbers are supposed to unique for each
person. The same concept applies to tables in databases. Whenever possible, it is good practice to
make sure that the table you are creating contains some form of primary key to give something to
uniquely identify a row.
How do I make a table with this information? Great question. Although we created the
database using the phpMyAdmin wizard, from now on we’re just going to use SQL.
Class: - B.Com, B.Com (Hons), BBA & BAJMC II Year Subject: Web Development Using PHP &
MySQL
In your window with phpMyAdmin, make sure that the cars table is selected (see it
circled in red below), then click on the SQL tab to bring up the command box. Make sure
that you see localhost -> cars above the box. If you do not, just click on the cars link on
the right side and then the SQL tab to get yourself there.
Type the following command into the box and click go.
Here’s an incredibly useful tip: Click the link “Create PHP Code” located on the
right side of the screen and what you’ll get back is:
$sql = "CREATE TABLE INVENTORY (VIN varchar(17) PRIMARY KEY,
YEAR INT, Make varchar(50), Model varchar(100), TRIM varchar(50),
EXT_COLOR varchar (50), INT_COLOR varchar (50), ASKING PRICE
DECIMAL (10,2), SALE PRICE DECIMAL (10,2), PURCHASE_PRICE
Class: - B.Com, B.Com (Hons), BBA & BAJMC II Year Subject: Web Development Using PHP &
MySQL
The reason there is such a link is because anything you can do in mySQL using a SQL
command, you can tell PHP to do for you in code. This represents a valid line of PHP
code in which the variable $sql is assigned a string value to hold the SQL statement. Of
course, there is more that would need to be done beyond this single line of code, but
don’t worry—we will cover this shortly.
Create a table using a SQL statement, then delete the table and create it again
using phpmyAdmin. Which is easier?
INSERT Statements
Now that you have a table created, the next logical step is to put some data into our
table. In the world of SQL, this is accomplished with the INSERT command.
Class: - B.Com, B.Com (Hons), BBA & BAJMC II Year Subject: Web Development Using PHP &
MySQL
Click on the SQL tab again, type the following command (if you can), and press enter.
The only difference is the number of fields. The syntax is the same, but the challenge
becomes making sure that there is a one-to-one relationship for each column name
and value, and that they are in the right order—the column names and their respective
values, that is.
As you can see, writing an INSERT statement is easy to goof up. We all do it. Luckily,
phpMyAdmin makes it easy to generate perfect SQL statements. Simply click on the table,
then click the Insert button and enter values into the boxes, as shown:
Class: - B.Com, B.Com (Hons), BBA & BAJMC II Year Subject: Web Development Using PHP &
MySQL
Once you click the Go button, phpMyAdmin will create a SQL statement for you and
insert the record, and even offer to convert it into a line of PHP code for you.
Here’s a trick used by the professionals: once you have one line of SQL that works,
it’s pretty easy to copy and paste it and tweak the values for the next car. Go ahead
and enter some more values until you get 5 or 6 cars entered into your table. Here’s
another one:
Don’t worry if you mess up. MySQL will warn you, and prevent you from running incorrect
commands. You don’t need to enter 10 or 20 cars; the sample code includes a script that does
that for you. Just do it enough times that you get it.
SELECT Statements
The syntax of SQL is pretty straight forward, at least syntactically. We have used it thus far to
create a database, create a table within that database, and insert data into the table.
Class: - B.Com, B.Com (Hons), BBA & BAJMC II Year Subject: Web Development Using PHP &
MySQL
There are just a few basic transactions left for us to master: reading data, updating
data, and deleting data. Some people refer to this with the cheery acronym CRUD, for
Create, Read, Update, and Delete.
Reading data is accomplished using the SELECT statement. The SELECT statement
selects a value or group of values from a table and returns those value(s) to the user.
Here’s an easy way to remember it: The SELECT statement allows you to be
selective. Clever, eh?
Let’s start out with a simple SELECT statement. In phpMyAdmin, click on the cars
icon on the left side and then click on the SQL tab at the top of the page. Type in the
following command and press Go.
If you typed out this statement correctly, you should see the entire contents of your
table ‘inventory’. To select only certain columns of a table, type out all of the
columns you want to see in that table separated by a comma. Type in the following
command and press Go.
Note that I added the red circle and line to show you where to look. The mySQL
database only returned the columns you specified using the SELECT statement.
WHERE Statements
So far, you have learned how to get all the rows and columns from a table, and how to
get selected columns from a table, but what about selected rows?
This is where the WHERE statement comes into play. The WHERE statement gives a
specific set of criteria to the MySQL database so that the results are much more
controlled and relevant to what you want. For example, say that you want to select all
the Ford Explorers that are in the inventory, or all the Toyotas under $15,000. The
WHERE clause makes this possible.
Class: - B.Com, B.Com (Hons), BBA & BAJMC II Year Subject: Web Development Using PHP &
MySQL
The results should be every automobile made by Ford in the database. If you
wanted just Ford Explorers, you would need to have WHERE Make=‘Ford’ AND
Model = ‘Explorer.
Of course, if you were looking to buy a car, you would only be interested in those cars that
haven’t already been sold, so the following query might be better suited:
NULL is a special word meaning that the field does not contain a value, and for some
reason you can’t say = NULL, you have to say IS NULL. I’m sure there is a reason
for this, but it doesn’t really matter. It is what it is.
Comparison Operators
Remember to surround a string with quotations or parentheses every time you wish
to use them in SQL statements. They will not work otherwise. Also, the WHERE
command always goes after the SELECT statement in MySQL.
To find all of the automobiles with a year that is a 2010 or newer, it is fairly obvious
that we need to use the Greater Than Or Equal To operator defined above. Type the
following command into your compiler and press Go.
ORDER BY
The ORDER BY statement is probably one of the easiest and handiest commands
in SQL. You can attach it at the end of any SELECT statement to put the results
in the order of the column that you specify.
The above statement should display the automobiles in order of the column ‘Year’
with the newest cars at the top. This is because the modifier DESC, or descending, is
placed at the end of the command.
The above statement should display the automobiles in order of the column ‘Year’
with the oldest cars at the top. This is because the modifier ASC, or ascending, is
placed at the end of the command.
The ORDER BY modifier can also be used with a WHERE statement such as:
Class: - B.Com, B.Com (Hons), BBA & BAJMC II Year Subject: Web Development Using PHP &
MySQL
Just remember that the WHERE command always goes before the ORDER
BY command. If you mix them up, you will get an error.
To limit how many results you receive in an ORDER BY statement, use the limit
clause after you write ‘asc’ or ‘desc’, such as
The number after limit determines how many results are returned.
UPDATE Statements
To update existing records in a database, you use the UPDATE statement. This
would be useful, for example, when a car in the inventory goes on sale with a
lower asking price.
To change the asking price for a car in our database, you can use a statement such as:
Class: - B.Com, B.Com (Hons), BBA & BAJMC II Year Subject: Web Development Using PHP &
MySQL
DELETE Statements
To delete records from a database you use the DELETE statement, specifying the
table name and a WHERE clause that specifies which records to delete.
For example, to delete the Caravan cars from the inventory you could use a
command similar to
If you wanted to delete everything from a database table, you could skip the
WHERE clause and use our friend the wildcard with a statement like
Delete * from inventory
Class: - B.Com, B.Com (Hons), BBA & BAJMC II Year Subject: Web Development Using PHP &
MySQL
Unit -5
Using mySQL and PHP Together
In the previous chapter, we learned all the basics of using a database, in our case
mySQL. All the SQL statements that we learned so far would likely work with other
database systems, in this chapter, we’re going to use PHP and mySQL together.
This is where it really starts to get good.
1. <?php
2. /**
5. */
6.
8.
9. if (!$mysqli) {
11. }
13.
14.
18. }
19. else
20. {
22. }
24. $mysqli->select_db(“Cars”);
26.
28. ( VIN varchar(17) PRIMARY KEY, YEAR INT, Make varchar(50), Model varchar(100),
29. TRIM varchar(50), EXT_COLOR varchar (50), INT_COLOR varchar (50), ASKING_PRICE
DECIMAL (10,2),
35. {
37. }
38. else
39. {
41. }
45. VALUES
46. (‘5FNYF4H91CB054036’, ‘2012’, ‘Honda’, ‘Pilot’, ‘Touring’, ‘White Diamond Pearl’, ‘Leather’,
‘37807’, NULL, ‘34250’, ‘7076’, ‘Automatic’, ‘2012-11-08’, NULL);”;
47.
48.
51. }
52. else
53. {
58. }
59.
61.
62. $query = “INSERT INTO `cars`.`inventory` (`VIN`, `YEAR`, `Make`, `Model`, `TRIM`,
`EXT_COLOR`, `INT_COLOR`, `ASKING_PRICE`, `SALE_PRICE`, `PURCHASE_PRICE`,
`MILEAGE`, `TRANSMISSION`, `PURCHASE_DATE`, `SALE_DATE`)
Class: - B.Com, B.Com (Hons), BBA & BAJMC II Year Subject: Web Development Using PHP &
MySQL
63. VALUES
64. (‘LAKSDFJ234LASKRF2’, ‘2009’, ‘Dodge’, ‘Durango’, ‘SLT’, ‘Silver’, ‘Black’, ‘2700’, NULL,
‘2000’, ‘144000’, ‘4WD Automatic’, ‘2012-12-05’, NULL);”;
65.
68. }
69. else
70. {
75. }
76. $mysqli->close();
77. ?>
Next I’ll walk you through the code, line by line. Please take the time to follow along
with me, as this is the only way to really get it. Yes, every line does matter.
1. <?php
line 1 is the start tag for PHP, and it tells the PHP interpreter that what follows is
code, not HTML.
Class: - B.Com, B.Com (Hons), BBA & BAJMC II Year Subject: Web Development Using PHP &
MySQL
2. /**
5. */
6.
lines 2 - 5 are comments. Comments are good, so put lots of comments in your code.
line 7 creates a variable called $con (for connection) and sets it equal to a built-in
function for connecting to mySQL. You need to supply the hostname, username,
and password for your mySQL server. If you do not have the correct username and
password, you will see this:
9. if (!$mysqli) {
line 9 is the start of an if statement, saying basically “if you are not connected”. The
exclamation point is the not operator. The point of this line is to test to see if line 7
succeeded.
line 10 is what to do if the connection failed. ‘die‘ is a command that stops further code
execution and prints out the text that follows. If I had been the one who invented PHP, I might
have named that command ‘stop’ rather than ‘die’, but it does make the point.
11. }
line 12 prints out “Connected successfully to mySQL”. This is the first line you see
in the browser.
18. }
19. else
20. {
22. }
Line 17 prints to the browser if the SQL statement in line 15 ran without error.
Line 21 prints error information to the browser if the SQL statement in line 15 did
not run successfully.
24. $mysqli->select_db(“Cars”);
Class: - B.Com, B.Com (Hons), BBA & BAJMC II Year Subject: Web Development Using PHP &
MySQL
line 24 creates a variable called $selected which uses a built-in function for selecting
a mySQL database, using the connection created in line 7.
28. ( VIN varchar(17) PRIMARY KEY, YEAR INT, Make varchar(50), Model varchar(100),
29. TRIM varchar(50), EXT_COLOR varchar (50), INT_COLOR varchar (50), ASKING_PRICE
DECIMAL (10,2),
lines 27 - 30 creates a variable called $query which holds an SQL statement. Recall
that phpMyAdmin created this line of code for us. Good thing too, as it is an easy one
to goof up.
lines 31 - 33 are comments now, but previously they were part of the script that printed out
the value of the variable $query. I had this in there to help me figure out why it didn’t work
at first, and I leave it in there as an example of what to do when as script doesn’t do quite
what you thought it would. I then copied the output of line 32 to the clipboard and pasted it
into phpMyAdmin for syntax advice.
34. if ($mysqli->query($query) === TRUE)
line 34 executes a SQL statement “query($query)” then tests for the result of the
SQL statement held in the variable $mysqli.
35. {
Class: - B.Com, B.Com (Hons), BBA & BAJMC II Year Subject: Web Development Using PHP &
MySQL
37. }
Class: - B.Com, B.Com (Hons), BBA & BAJMC II Year Subject: Web Development Using PHP &
MySQL
39. {
41. }
line 40 prints the message “Error:” and the mySQL error if line 34 fails. Hopefully
the value returned by mysql_error() will tell you something helpful about why it
failed. Sometimes it actually does.
42. // Dates are stored in MySQL as ‘YYYY-MM-DD’ format
line 42 is a comment to remind me (and you) to format dates the way mySQL
expects them
43. $query = “INSERT INTO `cars`.`inventory`
45. VALUES
46. (‘5FNYF4H91CB054036’, ‘2012’, ‘Honda’, ‘Pilot’, ‘Touring’, ‘White Diamond Pearl’, ‘Leather’,
‘37807’, NULL, ‘34250’, ‘7076’, ‘Automatic’, ‘2012-11-08’, NULL);”;
lines 43 - 46 changes the value of $query to a new SQL statement, this time an INSERT.
line 49 tests for the execution of the SQL statement held in the variable $query
51. }
52. else
53. {
58. }
61.
62. $query = “INSERT INTO `cars`.`inventory` (`VIN`, `YEAR`, `Make`, `Model`, `TRIM`,
`EXT_COLOR`, `INT_COLOR`, `ASKING_PRICE`, `SALE_PRICE`, `PURCHASE_PRICE`,
`MILEAGE`, `TRANSMISSION`, `PURCHASE_DATE`, `SALE_DATE`)
63. VALUES
64. (‘LAKSDFJ234LASKRF2’, ‘2009’, ‘Dodge’, ‘Durango’, ‘SLT’, ‘Silver’, ‘Black’, ‘2700’, NULL,
‘2000’, ‘144000’, ‘4WD Automatic’, ‘2012-12-05’, NULL);”;
65.
68. }
69. else
70. {
75. }
76.
lines 60 -76 does the same thing as 43 - 58, except for a different car.
78. $mysqli->close();
79. ?>
line 79 is the end tag for PHP, and any text that followed would be treated as
HTML, rather than code.
The astute reader might have noticed that this script didn’t appear inside the usual pattern of
<HTML><Body> <html code here> <php code here> </Body></HTML>.
Yet it worked. How come? I discovered this quite by accident, actually. It’s not a
function of PHP but apparently some browsers will fill in the HTML framework for
you if you “forget” to do so, which I did one time. Try it yourself. It works. Is this a
best practice? No, I can’t imagine that it is. But while you are learning it does let you
focus on the PHP code.
Introduction
Class: - B.Com, B.Com (Hons), BBA & BAJMC II Year Subject: Web Development Using PHP &
MySQL
So far we’ve learned how to use SQL to create databases, add records, edit
records, delete records, and select records. Then we learned how to use PHP to
perform those same operations.
Next we’ll get even more awesome. We’ll learn how to use HTML forms along
with PHP to create the SQL statements that perform the operation.
A Basic Form
Let’s start with a simple example that is easy to follow. Here’s a simple, four-field form:
Obviously, it doesn’t have all the attributes of a car that we have previously identified,
and it’s not very pretty to look at, but it is simple, and it will illustrate the point without
any extra junk to get in the way of your understanding of the concept.
HTML Code
<HTML>
Class: - B.Com, B.Com (Hons), BBA & BAJMC II Year Subject: Web Development Using PHP &
MySQL
<head>
<title>Joy of PHP</title>
</head>
<body>
</h1>
<form>
<br />
<br />
<br />
</body>
</html>
Class: - B.Com, B.Com (Hons), BBA & BAJMC II Year Subject: Web Development Using PHP &
MySQL
So far what we have is just HTML, and in fact the form won’t actually do anything
if you press the submit button…yet.
Form Action
To make the form actually do something, we need to modify the <form> tag.
Change the line of code above so that instead of saying <form> it says <form
action=“SubmitCar.php” method=”post”>
This tells the browser that when the form is submitted by pressing the submit button,
it should pass this form to the PHP script entitled ‘SubmitCar.php’ and use the ‘Post’
method to do so.
We’ll use get later in the book for a different purpose, though.
PHP Code
Here’s what we are going to accomplish. We want the script referenced by the form to
get the values from the form, produce a SQL INSERT statement using those values,
write the SQL statement to the browser so we can see it, execute the SQL statement that
we just created, and finally, let us know if it worked.
If all goes well, the script should output something similar to this:
Here’s the code for the SubmitCar.php file, which is also available in the sample code.
Again, you don’t have to study it here because I will walk you through it next. For
now, just give it a quick look over.
Class: - B.Com, B.Com (Hons), BBA & BAJMC II Year Subject: Web Development Using PHP &
MySQL
Class: - B.Com, B.Com (Hons), BBA & BAJMC II Year Subject: Web Development Using PHP &
MySQL
Lines 2 – 4 constitute the Head tag, while line 3 sets the page title.
Line 5 opens the body tag (which is closed on line 52). Note that we used the optional
parameter to set the background and text colors.
Line 7 is the opening <php> tag, to signify that the text that follows is code rather
than HTML.
Line 8 is a comment. You can never have too many comments in your code. Get in the
habit early of over-commenting your code. I have never heard anyone complain that
the code they were trying to figure out had “too many” comments distracting from the
elegance of the logic.
Class: - B.Com, B.Com (Hons), BBA & BAJMC II Year Subject: Web Development Using PHP &
MySQL
Lines 10 – 13 get the values that were on the form and assign them to variables in
PHP. $_REQUEST is a special variable that is used to collect data after submitting
HTML forms. You follow it with the name of the field on the HTML form that you
want to retrieve.
A number of readers of the first edition of this book have commented that you should
never trust the information that users give you, even in a corporate application like this
one,where the users are generally trusted. So a safer way to acheive what we did above
would be to use the PHP function called mysql_real_escape_string to strip out anything
dangerous that users might try to enter. For instance, $Make =
mysql_real_escape_string($_POST[‘Make’]);
Lines 17 – 24 build a SQL INSERT command. It could have been all on one line, but it
is easier to read this way. Notice that the variables $VIN, $Make, $Model, and $Price are
put into the formula as they are. Later, when the code is actually executed, PHP will
substitute the variable names with their actual values.
Line 27 writes the SQL statement out to the browser, on its own line. The .”<br>” after
the $query adds a <br> to the end of the line. That’s what puts it on its own line. Line
27 was not required for the function to work. It is there so you can see how PHP
translated the variables into their values when producing the SQL statement, which in
turn is stored in the variable $query.
Class: - B.Com, B.Com (Hons), BBA & BAJMC II Year Subject: Web Development Using PHP &
MySQL
Line 29 makes a connection to the mySQL database by passing the name of the
server (‘localhost’), username (‘root’), password (‘password’), and initial database
(‘cars’). Note your password will likely be different.
Lines 31 – 34 test to see if the connection made with line 29 worked or not. If not, it
prints an error message then stops further code execution (line 33 – exit). exit() is an
alternative to the command die.
Line 36 prints to the browser the message ‘Connected successfully to mySQL’. This
line would not execute if line 33 was called. Since we made it this far, we can conclude
that we did in fact connect.
Line 39 selects the ‘cars’ database, and line 40 prints this fact.
Line 42 is a comment. You see a theme here, right? The more comments you add, the easier it
will be to figure out your code when you come back later to look at it.
Class: - B.Com, B.Com (Hons), BBA & BAJMC II Year Subject: Web Development Using PHP &
MySQL
Line 43 is the grand finale. Here we actually execute the SQL statement against the
cars database. Line 43 is the start of an if statement and line 44 prints a success
message while line 48 prints a failure message.
Note: Line 48 really should read use ‘mysqli_error($mysql)’ not mysql_error(). This is corrected in
the sample code. As an astute reader of the first edition pointed out, you can’t mix mysql and myslqi
in the same script– they are not the same. In any case, the mysql extension has been deprecated
in favor of the mysqli extension.
Line 50 closes the connection to the mySQL database. This is not strictly required, as the
page will still work if you don’t do it, but apparently it’s a good idea because if you don’t do
it, eventually the server will develop problems and ultimately require a reboot.
Line 51 closes the PHP tag that was opened on line 7, signaling that the lines
that follow are html not PHP code.
Lines 52 and 53 close the body tag and the HTML tags, respectively.
Wow, we made it through the whole script. If you are still with me, you have a
good future in PHP development! Stay with it!
Include Files
Class: - B.Com, B.Com (Hons), BBA & BAJMC II Year Subject: Web Development Using PHP &
MySQL
You may recall from the earlier section on Includes the notion of reusing code by
including the contents of one file in another. This is a good time to revisit this
important topic.
So far we’ve made two different PHP files—the first one to create a database and table, and
the second one in the section above to insert data into the database using a web form. As you
can guess from the section headings coming up later in this chapter, we’re about to make even
more scripts that will allow us to edit and delete data as well.
Each of these scripts will have a something in common—code that connects to the
mySQL database, and in each case that code will be exactly the same. So far, we’ve
been developing on our own computer, so the host name has been ‘LocalHost’.
Imagine yourself, sometime in the near future, having written a dozen or more
scripts into the future, and suddenly you decide to move your application to another
computer—one accessible from the Internet. The host name will not be the same.
Nor, most likely, will the username and password be the same. What if your
password got out and you needed to change it?
Without my helpful intervention right here, you would be facing the prospect of
changing dozens of .php files—searching for the line that reads something like…
…and changing it to reflect the new host name, username, or password. Uck—
there would be no joy in that task at all. From now on, we’re going move the part of
the code that connects to the database to a separate file, and all our new scripts from this
point forward will simply refer to that code using an include statement. If any of the
values change, we will only have to change it in one place… the file that all the others
point to.
Just imagine the joy of changing one line of code and seeing that change propagate across
dozens of pages. That’s what I’m talking about. The include feature is one of the most
helpful and important features of PHP, in my humble opinion.
… to tell PHP to insert the contents of the db.php file into the current script. Be sure to use
include files whenever you can, as the extra few minutes it takes to move some code out to a
separate file is more than paid back when that code has to change.
SQL Injection
In general, it is not a good idea to take whatever the user enters into a form and pass
that directly to a SQL script as we did in the above example. If the user were
malicious (and skilled) they might enter SQL code into one of your forms and this
could have a big impact on what the script actually does. For example, imagine a
basic username/password form and the user entering ‘or 1=1– into the Password field,
as shown:
SELECT * FROM Users WHERE Username= ‘Brian’ and Password= ”or 1 = 1—’
Because 1=1 is always true, this query will return all users. (Note that the last
quotation is commented out.) So, in the script above, sqlsrv_has_rows is true, and all
the username password rows will be returned.
SQL injection is possible here because user input is concatenated with the executed SQL
code. One way to prevent against this is to strip out any slashes or quote marks from the the
user’ input. The following code snippet demostrates this:
$make = stripslashes($myusername);
$model = stripslashes($mypassword);
$make = mysql_real_escape_string($myusername);
Class: - B.Com, B.Com (Hons), BBA & BAJMC II Year Subject: Web Development Using PHP &
MySQL
$model = mysql_real_escape_string($mypassword);
Class: - B.Com, B.Com (Hons), BBA & BAJMC II Year Subject: Web Development Using PHP &
MySQL
At the risk of stating the obvious, the stripslashes command removes any slashes the users
and mysql_real_escape command removes the quote characters.
An even better way to reduce the chance for SQL injection is to use prepared
statements, but this is a topic that is beyond the scope of this beginner’s book. If you
want to learn more, here’s a good place to start —>
http://www.dreamincode.net/forums/topic/54239-introduction-to-mysqli-and-
prepared-statements/
One of the first things we’ll want to do for Sam’s Used Cars is to display a list of all
the cars that meet the selected criteria. At first, our criteria will be to select all the
cars, but later on you can modify the query to return only certain cars simply by
modifying the SELECT statement in the code.
The way this will work is that we will execute a SQL Select statement to retrieve
the cars that match the criteria, then loop through all the rows. We’ll put each row
of data into a nicely formatted table.
Class: - B.Com, B.Com (Hons), BBA & BAJMC II Year Subject: Web Development Using PHP &
MySQL
The source code can be found as viewcars.php. If all goes well the page should look
like this:
Of course, the output of a simple script is not particularly attractive to look at, but
with the addition of a bit of CSS we can make it look like this:
But let’s not get too far ahead of ourselves. First, here is the code that produces the
basic version of the table. The output of this script is more interesting if you have a lot
of cars in your database, so if you haven’t done so already, use the script
“createdb.php” included with the sample code to populate your inventory table with a
lot of cars.
Class: - B.Com, B.Com (Hons), BBA & BAJMC II Year Subject: Web Development Using PHP &
MySQL
Code
Class: - B.Com, B.Com (Hons), BBA & BAJMC II Year Subject: Web Development Using PHP &
MySQL
Code Explained
I won’t walk you through every line anymore, as I no longer think you need it.
From now on, I’ll just explain the important ones.
Line 11 is our first use of the include option which refers to an external file named db.php
which will be included in this script just as if it were part of the same file. I highlighted line 11
above in blue and the code below in blue, in hopes that you would better understand how it
works. The content of the blue box below is substituted into the code for the blue line (11)
above, so that both files are combined into a single script.
The code in the db.php file is identical to the code explained as line 29 in the previous section,
so I won’t explain it again here. That’s another key benefit of include files. Once the code
inside it works, you don’t really have to think about it much anymore.
Line 12 is the query that produces the list of cars to be displayed. In this simple
case, we are selecting all the cars.
Lines 14 – 20 runs the query and displays an error message if the query fails.
Line 23 is an opening tag to create a table with the ID of ‘grid’. The ID is optional but
makes it easy to apply styles to the table later. style=width:80% prevents the column
from extending to fill the entire screen; instead it takes 80% of the width. <tr> starts
the Table Row with the opening <tr> tag.
Class: - B.Com, B.Com (Hons), BBA & BAJMC II Year Subject: Web Development Using PHP &
MySQL
Lines 24– 27 create the first row of the table, the row that contains the column titles of make,
model, and price. Line 27 is a closing Table Row tag, followed by a new line.
Line 29 sets the value of a variable called $class to ‘odd’ because the first data row in
our table will be odd. As we loop through each row of data, we’ll alternately set the
$class to the value of either ‘odd’ or ‘even’. We do this so we can style the table later to
have alternate rows show different coloring to make it easier on the eyes.
Lines 31 to 37 create a row in the HTML table to correspond with each row in the
Class: - B.Com, B.Com (Hons), BBA & BAJMC II Year Subject: Web Development Using PHP &
MySQL
database table that we extracted using the query. Each table cell contains data from
the mySQL table. For instance, line 34 ( echo “<td>” . $result_ar[‘Make’] . “</td>”;)
should produce something like
<td>Ford</td>
because $result_ar[‘Make’] says get the value of Make (one of the columns in the table, and
in this case ‘Ford’) and put it here between the <td> tags. Take the time to really understand
what that line is doing, because if you can understand this, you can do virtually anything!
Remember the . character means join these two strings.
Go back and modify this code so that it doesn’t select all the cars but rather a subset that pleases
you.
Here’s the CSS that improves the look of the form. This style information is added to the
<head> section of the page, but often people put styles into a separate style sheet too. See the
file viewcarswithstyle.php to see the form in action.
Explaining how CSS works is beyond the scope of this book, and a topic in itself. But
the important thing is to see how easily we were able to change the look of the HTML
table using a little style information. Take a look at the complete style sheet here, and
I’ll explain it next.
Class: - B.Com, B.Com (Hons), BBA & BAJMC II Year Subject: Web Development Using PHP &
MySQL
Class: - B.Com, B.Com (Hons), BBA & BAJMC II Year Subject: Web Development Using PHP &
MySQL
Class: - B.Com, B.Com (Hons), BBA & BAJMC II Year Subject: Web Development Using PHP &
MySQL
CSS Explained
Line 1 opens the <style> tag, telling the browser that what follows is a style sheet.
Line 2 is a comment.
Line 3 says to select an item on the page with the id of Grid. The # symbol is the selector
to select something defined using an id, and what follows is the name of the specific thing
you want to select. See line 23 of the previous PHP script, which set the id of our table to
‘grid’ with the line echo “<table id=‘Grid’ style=‘width: 80%’>; Since we have a table
with an id=‘Grid’, this style will apply.
Everything that follows between the { and the } symbols define the style for that item.
Line 11 specifies that the following lines only apply to <td> and <th> tags, if
they appear within an item with an ID of ‘Grid’.
Each line that follows gets more specific about how an item should be formatted. A
specific selector overwrites a general one. So we started off specifying default
formatting for Grid, but later we modified specific elements of the grid item. The
next bit is how we color alternate rows differently:
Line 27 says to selects a <td> tag, within a table row <tr> if it is a member of the
class odd. Look at the HTML that is output by the script. You’ll see a table row for
the table defined like this: <tr class=‘odd’> or <tr class=‘even’>.
There is another selector for the table headers. It does make sense if you look at it
long enough. The # symbol in CSS is a selector. OK, that’s it for now. Maybe
someday I’ll do a “Joy of CSS” book. Let me know…
The last thing this form needs is way to link to a specific car. When the site visitor
clicks on a specific car in a row, it should take them to more detail about that
specific car. In other words, it should take them to the ‘car detail’ page. We’re going
to have to make that page, of course.
Class: - B.Com, B.Com (Hons), BBA & BAJMC II Year Subject: Web Development Using PHP &
MySQL
Note that for this to work we will need to build the detail page because otherwise
the link will naturally fail. Nothing happens automatically. Assuming that the detail
page exists, we can modify the code on line 34 that reads as:
What this does is create an ‘anchor’ or a link which makes the first column of each
row a clickable link. It should output HTML similar to:
You can see that the URL created will be similar to /viewcar.php?VIN=123234FE221 as
shown above. This tells the browser to open the viewcar.php file and pass it the query
string of VIN= followed by a VIN. It is called a query string because the primary purpose
of passing data to a form this way is so it can use the data in a SQL query—and that’s
exactly what we are going to do.
Remember back when I said to use ‘Post’ rather then ‘Get’ when submitting a form? If
you had used get, clicking the submit button would send to the browser a really long
URL with all the field names and values appended to the end of it as a query string in a
format similar to ?Make=Ford&Model=Explorer, etc. We are going to take advantage of
that technique to create our own query string and pass it to a script.
For now, clicking on the link will only trigger an error, because the viewcar.php
file does not yet exist, but that’s what we’re going to build next.
Once a site visitor has identified a car that they want more information about, the
car shopper will want to click on a particular car to learn more about it. So we’ll
make a PHP page to handle this. We’ll call this the Car Detail page, and its file
name will be viewcar.php.
Again, we’ll keep the example relatively simple for the purpose of following the
logic. If all goes well, clicking on a car from the previous screen will bring up a form
similar to:
Code
Class: - B.Com, B.Com (Hons), BBA & BAJMC II Year Subject: Web Development Using PHP &
MySQL
Class: - B.Com, B.Com (Hons), BBA & BAJMC II Year Subject: Web Development Using PHP &
MySQL
Code Explained
Lines 2 – 4 are the head tags, and in between specifies the document title, ‘Sam’s
Used Cars’.
Line 8 is ordinary HTML; it prints Sam’s Used Cars at the top of the page in a
headline style type.
Line 9 specifies that the current script include the db.php file, which logs into
the mySQL database.
Line 10 creates a variable called $vin and assigns it the value that follows VIN= in the URL
string. Remember, for this form to work, you have to pass it the VIN like this:
/viewcar.php?VIN=123234FE221. We use the command $_GET because when you submit a
form using get the values are appended to the URL in a similar fashion.
Line 11 builds a query using the value passed to the form in the Query String, and assigns it
to the cleverly named variable $query. See why we call it a ‘query string’?
Class: - B.Com, B.Com (Hons), BBA & BAJMC II Year Subject: Web Development Using PHP &
MySQL
Lines 12 – 19 run the query against the mySQL database and create something called
a ‘result set’. A result set is the set of data that results from the running of a query.
This result set is assigned to the variable $result.
Lines 20 – 31 loop through ‘all’ the rows returned as a result of the query. In our case,
since VINs are unique we would only expect to get one row of data back, but we are
using basically the same technique we learned in the prior section – Forms that
Display Summary Data.
Lines 22 to 30 assign a series of variables with the values of the specified data
columns, which match the names of the columns in the database table ‘inventory’.
Class: - B.Com, B.Com (Hons), BBA & BAJMC II Year Subject: Web Development Using PHP & MySQL
If you understand how to make Forms that Add Data to a Database, and you
understand Forms that Display Detail Data, it isn’t much of a stretch
(conceptually anyway) to make a form that Edits data. Simply create a form just
like the one you made to add data, but before displaying it retrieve data from the
database and pre-populate it with values.
Instead of executing a SQL Insert command when the user clicks submit,
instead execute an Update.
To delete a specific record from a database, you need a way for the user to select the data they
want to delete. You already learned how to do this in the section Forms that Display Summary
Data. In the section Modifying the form to link to the detail page we created an <HREF> link
that takes the user to a detail page, and you can use that same technique to take them to a delete
page, such as the one shown below:
Code Explained
Lines 1 – 6 set up the basics of the page. We open an <html>, open and close the <head>
tags, and start the body with a headline proclaiming “Sam’s Used Cars”.
Lines 6 – 7 are also familiar to us by now. We open the php tag and add the insert
line to connect us to our mySQL database.
Line 9 gets the VIN from the query string. Remember, this page will be called with ?
VIN=‘23ABC..’ appended to the end. Line 10 builds a SQL delete statement using the VIN, so
we know which vehicle to delete. Line 11 simply writes the query to screen so we can see the
query we built. It is not strictly required for the function to work.
Class: - B.Com, B.Com (Hons), BBA & BAJMC II Year Subject: Web Development Using PHP &
MySQL
Lines 14 through 20 do the actual work. Line 14 performs the query, and returns
True if the query succeeds. If so, line 15 prints a success message to the screen, and if
not, line 19 prints a failure message to the screen.
The rest of the page close the database connection, closes the php tag, closes the
body tag, and finally closes the html tag.
Exercise
To add edit and delete functionality, simply add two new columns to the table with
the links for edit and delete, and call the appropriate php page. deletecar.php has
been provided, while editcar.php you will have to make yourself. If you absolutely
can’t get editcar.php to work, I did include it in the sample code. Just do yourself a
favor and TRY to make it.
Session Variables
Introduction
Variables in PHP typically have a specific and limited scope—generally, a variable is only
available on the page on which it was declared. The prime exception to this rule is when you
declare a variable inside a function, it only works in that function.
But what if you want access to the same variable across multiple pages in your application? For
instance, I’m a regular shopper on Amazon.com. If you are too, you may have noticed that once
you’re logged in, every page has your name on the top of it.
But how does that value $FirstName pass from page to page as I wander about the site?
And how does the site keep track of hundreds of unique $FirstName variables for all
Class: - B.Com, B.Com (Hons), BBA & BAJMC II Year Subject: Web Development Using PHP & MySQL
the unique customers who happen to be on the site at the same time? The answer is
session variables.
Sessions
A session variable is a special kind of variable that, once set, is available to all the
pages in an application for as long as the user has their browser open, or until the
session is explicitly terminated by the developer (you).
The great thing about session variables is that PHP will magically keep track of which
particular session variable goes with each particular user. So while my Amazon.com
experience will always say “Alan’s Amazon”, yours will say something different
(unless your name also happens to be Alan, of course.) Sessions work by creating a
unique id (UID) for each visitor and storing variables based on this UID. The UID is
typically stored in a cookie.
It doesn’t really matter how they work, the important thing is that they do work. And, they
are very cool. They open up a whole realm of possibilities for customizing your web
application for a specific customer. For example, in the case of Sam’s Used Cars, you could
ask a customer their preferred car color, make/model, features, etc. From that point on, you
can customize the pages to reflect the customers’ preferences. For example, Hey look, this
car has a sunroof! (And it’s red too!) It’s just a sample app, so it’s OK to code annoying
features to learn something valuable.
Once a user closes their browser, the cookie will be erased and the session will end. So sessions
are not a good place to store data you intend to keep for long. The right place to store long-term
data is in a database. Of course, sessions and databases can work together. For instance, you can
store a user’s preferences in a database, and retrieve them from the database when the user “logs
in” or types in their email address or does whatever it is that you coded for them to identify
themselves. Once the data is retrieved, assign the preferences to the session variables and they
will be available from then on.
Class: - B.Com, B.Com (Hons), BBA & BAJMC II Year Subject: Web Development Using PHP & MySQL
The code above will start the user’s session with the server and allow you to start
saving user information into session variables.
The correct way to store and retrieve session variables is to use the PHP
$_SESSION variable:
Store a variable
Class: - B.Com, B.Com (Hons), BBA & BAJMC II Year Subject: Web Development Using PHP &
MySQL
Retrieve a variable
You can check to see if a session variable is available or not by using the
isset() function.
Here’s an example:
Destroying a Session
Class: - B.Com, B.Com (Hons), BBA & BAJMC II Year Subject: Web Development Using PHP &
MySQL
If you wish to delete some session data, you can use the unset() function. If you want
to delete it all, use the session_destroy() function. The unset() function is used to
delete a specific session variable:
Class: - B.Com, B.Com (Hons), BBA & BAJMC II Year Subject: Web Development Using PHP & MySQL
You can also completely destroy all the session by calling the session_destroy()
function:
Note: session_destroy() will reset your session and you will lose all your stored session
data. This is an easy way to implement a logout function.
If you would like to learn more about Session Variables, I have a whole book on this
topic titled “The Joy of PHP: Deep Dive into Sessions”.
Then we would build PHP to retrieve the image name and insert it into an HTML
image tag on the car details page.
Class: - B.Com, B.Com (Hons), BBA & BAJMC II Year Subject: Web Development Using PHP & MySQL
Of course, PHP would be well suited for this. We would read the file name from
the database and use PHP to create the image tag dynamically.
For instance, we could modify our earlier example, which shows the detail for a
specific car by adding the lines highlighted in red as follows:
Class: - B.Com, B.Com (Hons), BBA & BAJMC II Year Subject: Web Development Using PHP & MySQL
This example assumes that we have a column in our database called Primary_Image, which
contains the file name of an image file that is stored on our server. The sample files home page
contains a script that makes this modification, if you are so inclined.
If the images were in a folder called ‘images’, the line would read:
Get the above example to work. Create an images folder underneath the folder that is
running the car lot application and put some images into it. Modify your inventory
table to add a Primary_Image field and enter some values in that field to associate
specific cars with specific images.
Make a copy of the viewcar.php script (call it viewcar-backup.php in case you need it later),
then modify the viewcar.php as shown in red above so that it reads the image location out of
the database and inserts the image into the page using the <img> tag.
Assuming you got the above exercise to work, you must admit that it is pretty slick.
Congratulations, you are officially awesome. But, we can do much more. Just having one image
of a car doesn’t really reflect the reality of a visitor’s expectation of a car site. More likely a
visitor to Sam’s Used Cars web site would want to see many images of a car he or she is
interested in, and our site will have to accommodate this. Some cars might have only one image,
but some might have 10 or more. It will be different for each car. So how would we accomplish
this? Having a single column called Primary_Image is obviously not the permanent solution.
As soon as you show it to Sam, he’ll surely say ‘But what if I have two pictures of the car to
show?’ That’s the nature of web development sometimes. One good idea sparks another. Don’t
get
frustrated when this happens, but rather think to yourself, ‘Wow, I inspired an even
better idea!’
The easiest way to handle a variable number of images would be to create a database
table to store them in.
Let’s add a table called ‘images’ to our cars database. It should have the columns ID,
VIN, and ImageFile.
Class: - B.Com, B.Com (Hons), BBA & BAJMC II Year Subject: Web Development Using PHP &
MySQL
Now you need to populate the table with some sample data. Here’s what I did. Go to
http://www.cars.com and search for some cars. Copy the VIN to the clipboard, and save some
the pictures of the car to your hard drive. Enter a row in the images table for each of the images
you save, and enter the VIN of the car for each one. There should also be a corresponding entry
in the inventory table for that car, with the exact same VIN. It’s easy to do in phpMyAdmin.
Don’t worry about trying to automate that part of it yet.
The assumption of this script is you have the VIN of the car in the variable $vin, and that
you have included ‘db.php’ to establish the database connection.
Class: - B.Com, B.Com (Hons), BBA & BAJMC II Year Subject: Web Development Using PHP & MySQL
Code explained
Line 2 sets up the query whereby we select all the fields in the images table for the
specific car (WHERE VIN=).
Line 4 runs the query and checks to see if any results were returned from the database.
Lines 7 – 10 loops through the result set as many times as there are rows. In other
words, if there were five images for a specific car, there would be five rows of data
returned and the while loop would go around five times.
Line 11 closes the if statement and the line 12 closes the connection to the mySQL
database.
the rest – putting the file in the right place and creating the correct row in the images table
using the VIN of the selected vehicle.
In its most basic incarnation, here is an HTML form you can use to upload a file.
First, notice the form attributes: action=‘upload_file.php’ means that when you click the submit
button, the result of the form post will be passed to the upload_file.php script for further
processing. Next, the enctype=“multipart/form-data” is a new one for us. Here we are specifying
the encoding type to be used by the form. You have to specify that it is multipart/form-data if
you are including a file upload control on a form, so the browser knows to pass the file as a file,
and not as just another big block of text.
We also have a new type of input box. In the past, we’ve been using the input boxes mostly
to allow users to type in text. When you specify that an input type=“file”, the browser
handles it differently. It will put a browse button next to the input field,allowing the user to
select a file from his or her computer.
Class: - B.Com, B.Com (Hons), BBA & BAJMC II Year Subject: Web Development Using PHP & MySQL
The form above specified that the post be processed by ‘upload_file.php’. This script
is used to do something with the file once it’s been uploaded. The script that follows
simply echoes back to the browser some of the attributes of the file that has just been
uploaded. There are, of course, other file attributes that we won’t cover, because you
probably won’t ever need to use them.
It doesn’t really matter how they work, the important thing is that they do work. And, they are
very cool. They open up a whole realm of possibilities for customizing your web application
for a specific customer. For example, in the case of Sam’s Used Cars, you could ask a
customer their preferred car color, make/model, features, etc. From that point on, you can
customize the pages to reflect the customers’ preferences. For example, Hey look, this car has
a sunroof! (And it’s red too!) It’s just a sample app, so it’s OK to code annoying features to
learn something valuable.
I highlighted in yellow the parts that need to match. In other words, if the name of the
input control on the upload form refers to the file as ‘foo’, like <input type=“file”
name=“foo”> you would also have refer to it as foo on the script that follows, such as
$_FILES[“foo”][“name”]. The actual name doesn’t matter, but what does matter is
consistency.
When you upload a file using PHP, the file is stored in a temporary folder. Unless
you specifically do something with the file, it will soon disappear.
Class: - B.Com, B.Com (Hons), BBA & BAJMC II Year Subject: Web Development Using PHP & MySQL
For Sam’s Used Cars, the ideal thing to do would be to upload the file, copy the file into a
specific folder, and then create a record in the images table that inserts the proper vehicle
VIN and the file name of the image we just uploaded. In the sample data, see the script
ViewCarsAddImage.php to see this exact concept in action.
Code: ViewCarsAddImage.php
Class: - B.Com, B.Com (Hons), BBA & BAJMC II Year Subject: Web Development Using
PHP & MySQL
Class: - B.Com, B.Com (Hons), BBA & BAJMC II Year Subject: Web Development Using
PHP & MySQL
Class: - B.Com, B.Com (Hons), BBA & BAJMC II Year Subject: Web Development Using PHP & MySQL
Code Explained
Line 1 opens the php tag, and line 2 adds the necessary include file to connect to
our database.
Line 3 creates a variable called $vin and assigns it the value that was passed to it using when
a form was posted. Again, see this in action with the sample scripts included with this book.
This is not the only way we could have done this. We could also have passed the VIN in a
query string, the technique we used in viewcar.php
Lines 4 – 7 test to see if a file was, in fact, uploaded. If not, an error is printed
using line 6.
Beginning with Line 9, the script begins to process the uploaded file.
Class: - B.Com, B.Com (Hons), BBA & BAJMC II Year Subject: Web Development Using PHP & MySQL
Lines 10 – 12 print information about the file, and line 13 prints the VIN, just to
make sure we got it without any problems.
Line 14 tells us the name that PHP used to temporarily store the uploaded file.
TIP: Notice that on the end of the line I also have it write “\n”, which means to add a new line
at the end of this. This doesn’t affect the script at all, but it does put a new line on the HTML
that is created by the script. Putting \n at the end of the line on scripts makes the HTML code
easier to read when you look at a page and select View Source— something that every PHP
developer has to do from time to time.
Line 14 tells us the name that PHP used to temporarily store the uploaded file.
TIP: Notice that on the end of the line I also have it write “\n”, which means to add a new line
at the end of this. This doesn’t affect the script at all, but it does put a new line on the HTML
that is created by the script. Putting \n at the end of the line on scripts makes the HTML code
easier to read when you look at a page and select View Source— something that every PHP
developer has to do from time to time.
Line 15 uses the command getcwd() to figure out the name of the folder in which the
current script is running. Why did I want that? Because I want to put the uploaded file
into a folder that is under the current folder, and to do that you need to know where you
are. Line 16 outputs what it just learned.
Class: - B.Com, B.Com (Hons), BBA & BAJMC II Year Subject: Web Development Using PHP &
MySQL
In line 17, we create a variable called $target_path and assign it a value by adding two
strings together using the . character. The two strings we added are the current
directory and /uploads/. We are creating the target path to specify where we want the
uploaded file to be put— in the uploads folder.
Line 18 outputs the result of the calculation to set the target path.
In line 20 we tweak the target path yet again, this time appending the original file
name of the uploaded file to it.
Line 21 calculates the name of just the image file without the entire file path. This is because
when you are working with HTML <img> tags, you don’t have to specify the entire path of the
image; you only need to specify where it is relative to where you are.
Class: - B.Com, B.Com (Hons), BBA & BAJMC II Year Subject: Web Development Using PHP &
MySQL
Lines 22 and 24 output the values of these calculations so you can see what was the
result. Of course, if this was a “real” web site for a used car lot, you wouldn’t want
all this extra information going to the browser.
Lines 26 moves the uploaded file from the temporary location assigned by PHP into the
target path that you calculated in line 20. Line 27 informs you of this fact.
Next, we want to create a record in the images table that points to this new image file.
In line 36 we get just the name of the uploaded file, without any path information at all. This is
because we just want to insert the name of the file into the database. When referring to the file
later with an <IMG> tag, we can always specify a path if needed.
Line 37 builds the query to insert the record into the database, and line 38 writes out what
the query is. Line 38 was very helpful while I was originally writing this script, because
of course it didn’t work the first time I tried it. Seeing the actual query is the first step to
figuring out why a particular query did not work.
Lines 39 to 41 create a link that allows us to easily add another image for this car if
we have one.
Lines 42 to 51 execute the query and prints out either a success or failure message.
Line 52 closes the connection to mySQL.
Class: - B.Com, B.Com (Hons), BBA & BAJMC II Year Subject: Web Development Using PHP &
MySQL
Line 52 creates an image tag for the file we just uploaded so you can see what it
looks like. When I first created this the images were so big they took over the whole
screen, so I added the attribute width=‘150’ to keep the images to a reasonable size.
This tells the browser to resize the image.
Introduction
Every language has its quirks. As I encounter those aspects of PHP that are not
immediately intuitive, or if I find a great tip that could make your life easier, it
will go into this section.
When working with strings, it is important to understand the difference in how PHP
treats single quotes (echo ‘Hello $name’;) as compared with double quotes (echo
“Hello $name”;)
Single quoted strings will display things exactly “as is.” Variables will not be
substituted for their values. The first example above (echo ‘Hello $name’; ) will
print out Hello $name.
Double quote strings will display a host of escaped characters and variables in the
strings will be substituted for their values. The second example above (echo “Hello
$name” ) will print out Hello Alan if the $name variable contains ‘Alan’.
The equal sign can also be used to compare to values, if you put two of them together
and include it in an if statement. For instance, $FirstName == ‘Alan’ will return true
for me, as the following code demonstrates
The quirky thing about the double equal test is that PHP will attempt to convert the two variables
being compared into different types to see if it gets a match. For instance, if $a
= 1 and $b = “1” you might think that they are not equal because they are different
types. (One is a number and the other is a string.)
However, comparing $a and $b using the == comparison will return true, because if you
convert $b from the type string to the type number the two variables are equal.
Class: - B.Com, B.Com (Hons), BBA & BAJMC II Year Subject: Web Development Using PHP &
MySQL
If you want to test if two values are the same value and the same type, you compare
them using three equal signs. This way, $a === $b would return false.
Class: - B.Com, B.Com (Hons), BBA & BAJMC II Year Subject: Web Development Using PHP & MySQL
Comparison Operators
If you compare a number with a string or if the comparison involves numerical strings,
then each string is converted to a number and the comparison performed numerically.
These rules also apply to the switch statement. The type conversion does not take place
when the comparison is === or !== as this involves comparing the type as well as the
value.
Class: - B.Com, B.Com (Hons), BBA & BAJMC II Year Subject: Web Development Using PHP & MySQL
Security Considerations
Introduction
As we have seen, PHP is a very easy language to learn, and many people without any
sort of formal background in programming will learn it as a way to add inter-activity
to their web sites.
Sadly, many of the steps taken to increase the security of a web application also decrease its
usability. Passwords, session time-outs, and access control levels and roles all create
Class: - B.Com, B.Com (Hons), BBA & BAJMC II Year Subject: Web Development Using PHP & MySQL
obstacles for legitimate users. While these steps will increase the security of the
application, you can’t have it so secure that nobody can use it.
In short, they required passwords that no human could actually remember, and the system was
not very usable. If your computer was idle for 15 minutes or more, you’d be prompted to type in
the password in again. Everyone I worked with on that project had their password written down
on a piece of paper right next to their computer. Clearly the “powers that be” in the security
department had picked security over usability to such an extreme that the very security they were
seeking was utterly compromised.
SQL Injection
One of PHP’s greatest strengths is the ease with which it can communicate with
databases, such as MySQL. The Sam’s Used Car Lot example from this book
and thousands of other high profile web sites, such as http://Facebook.com, rely
on databases to function.
With that strength also comes risks. The most common security hazard faced when
interacting with a database is something called SQL Injection - when a user
deliberately uses part of your application to run unauthorized and unintended SQL
queries on your database.
Let’s use a common example. Although we didn’t cover it in this book, many systems that ask
a user to login feature a line of PHP code that looks a lot like this one:
The script takes the username and password that was entered on the form and builds
a query using the text entered by the user.
Does it look familiar? You’ll see many variations of this as your journey into the Joy
of PHP continues. So what’s the problem? It does not look like such code could do
much damage. But let’s say for a moment that I enter the following into the
“username” input box in the form and submit it:
Class: - B.Com, B.Com (Hons), BBA & BAJMC II Year Subject: Web Development Using PHP & MySQL
‘OR1=1#
The hash symbol (#) tells MySQL that everything following it is a comment and to ignore
it. The query that is going to be executed by mySQL will now look like this:
The # symbol tells mySQL to ignore any text that follows, leaving a WHERE statement of
‘WHERE Username = ” OR 1=1’. Since 1 always equals 1, the WHERE clause of the SQL will
match for every row—and here’s the bad part. The query will return all of the usernames and
passwords from the database. What may happen next is that if the first username and password
combination is the admin user, then the person who simply entered a few symbols into a
username box is now logged in as your website administrator, as if they actually knew the
admin’s username and password, which they
With a little creativity which is beyond the scope of this book, SQL Injection can be
used to accomplish some nasty tricks you probably never thought of when designing
your application.
Fortunately, it is pretty easy to put up roadblocks that help prevent this type of
vulnerability. By checking for apostrophes in the items we enter into the database, and
removing or substituting them, we can prevent anyone from running their own SQL
code on our database.
Next we would need to modify our query. Instead of directly using the _POST
variables, we would pass all user-provided data through the make_safe function, such
as:
Class: - B.Com, B.Com (Hons), BBA & BAJMC II Year Subject: Web Development Using PHP & MySQL
Now, if a user entered the malicious data above, the query will look like the following,
which is perfectly harmless. The following query will select from a database where the
username is equal to “' OR 1=1 #”.
Now, unless you happen to have a user with a very unusual username and a blank
password, your attacker will not be able to do any damage.
It is important to check all the data passed to your database like this, however secure
you may think it is.
**************