Chapter 3 PHP
Chapter 3 PHP
DATABASE DRIVEN
WEBSITES
3.1 Working with Forms
We use one of two methods to submit form information.
The methods pass the form data differently and have
different advantages and disadvantages
GET method:
The form data is passed by adding it to the URL that calls
the form-processing script.
For example, the URL may look like this:
processform.php?lname=Smith&fname=Goliath
The advantages of this method are simplicity and speed.
The disadvantages are that
less data can be passed and
the information is displayed in the browser, which can be a
security problem in some situations.
3.1 Working with
Forms…
POST method:
The form data is passed as a package in a separate
communication with the processing script.
The advantages of this method are unlimited information
passing and security of the data.
The disadvantages are the additional overhead and slower
speed.
The form data is available in the processing script in the PHP
built-in arrays.
Information from forms that use the POST method is available in
the built-in array called $_POST.
If your form uses the GET method, the information is available in
the array $_GET.
Both types of form information are also stored in an array called
$_REQUEST.
You get information from the array by using the form field name
3.1 Working with
Forms…
The syntax is:
$_POST[“form element name”]
$_GET[“form element name”]
For example, suppose that you echo the following field in
your form that uses the POST method:
<input type=’text’ name=’firstName’>;
The value entered in this textbox can be accessed by
$_POST[‘firstName’]
This contains the text the user typed into the field.
If the form uses GET method, the above textbox can be
accessed as
$_GET[“firstName”]
3.1 Database Programming
PHP is particularly strong in its ability to interact with databases.
PHP supports pretty much every database out there
The most commonly used database with PHP is MySQL
MySQL is a free and open source database that has a lot of users
especially for web applications.
It can be downloaded from internet freely.
database.
You use a PHP function to connect to the database.
To make the connection, you need to supply the function with three
things:
Location:
The database may not be on the same computer where PHP is installed.
Therefore, you need to tell the PHP connect function the name of the
computer where the database is located.
You can supply either a domain name (such as mycompany.com) or an
IP address (such as 172.17.204.2).
If the database is on the same computer as PHP, you can use localhost
for the hostname.
Account name: You must provide a valid account name that can be used
to access the database.
Password: You have to have a valid password to access the database.
3.1 Database
Programming…
The syntax for creating connection to MySQL
database:
$connect = mysql_connect($host, $account,
ID $password);
FirstName LastName Sex Telephone Status
sam232 John Walter M 4325456342 1
sam543 Samuel David M 5424256345 1
sam534 George Graham M 2634345643 0
sam979 Ana Bush F 3462737485 0
…
Example:
<?php
$con = mysql_connect("localhost",“root",“vertrigo");
mysql_select_db(“books”);
//other statements
?>
3.1 Database
Programming…
Querying the Database
To actually perform the query, we can use the
mysql_query() function.
Before doing this, however, it’s a good idea to set up
It’s very similar but allows you to specify which database you
would like to run the query on.
It is like a combination of the mysql_select_db() and
mysql_query() functions.
Both of these functions return a result identifier that allows
you to retrieve the query results or false on failure.
3.1 Database
Programming…
Example: executing query
$sql = “SELECT * FROM Product”;
$result = mysql_query($sql, $connect);
Putting all together:
<?php
$account = “david”;
$password = “gotago”;
$host= “localhost”;
$connect = mysql_connect($host, $account, $password);
$db = mysql_select_db(“Catalog”, $connect);
$sql = “SELECT * FROM Product”;
$result = mysql_query($sql, $connect);
//other code
?>
3.1 Database
Programming…
Customers table
Select *
from Customers
3.1 Database
Programming…
3.1 Database
Programming…
Select AVG(income)
From customers
Select count(*)
From customers
SELECT column_name(s)
FROM table1LEFT JOIN|RIGHT JOIN|INNER JOIN|JOIN table2
ON table1.columnname=table2.columnname
SELECT *
FROM customer inner join security
on customer.CustomerID=security.userID
3.1 Database
Programming…
SELECT name, city, username
FROM customer left join security
on customer.CustomerID=security.userID
Update tablename
Set column1=value1, column2=value2,…
[where condition]
Update customers
Set address=‘250 Olsens Road’, city=‘New York’
Where customerid=‘4’
3.1 Database
Programming…
Delete from tablename
[Where condition]
make a connection,
send a query, and
check the results.
In this case, the query you send will be an
INSERT rather than a SELECT.
3.1 Database
Programming…
3.1 Database
Programming…
<HTML>
<HEAD>
<TITLE>Processing HTML forms with PHP</TITLE>
</HEAD>
<BODY>
<H1>Newsletter sign-up form</H1>
<P> Please, fill the form to be our registered customer</P>
<FORM METHOD=”post” ACTION=”customer.php”>
ID: <INPUT TYPE=”text” NAME=”ID”> <BR>
First name: <INPUT TYPE=”text” NAME=”FirstName”> <BR>
Last name: <INPUT TYPE=”text” NAME=”LastName”> <BR>
Sex: <INPUT TYPE=”text” NAME=”Sex”> <BR>
Telephone: <INPUT TYPE=”text” NAME=”Telephone”> <BR><BR>
<INPUT TYPE=”submit” NAME=”submit” VALUE=”Submit”>
</FORM>
</BODY>
The customer.php file that process the data collected by the above form is the
following:
<?php
// Open connection to the database
$con = mysql_connect(“localhost”, “phpuser”, “sesame”) or
die(“Failure to connect to database”);
mysql_select_db(“customers”);
$ID = $_POST[“ID”]);
$fn = $_POST[“FirstName”];
$ln = $_POST[“LastName”];
$sx = $_POST[“Sex”];
$tl = $_POST[“Telephone”];
$st = “1”;
$query = “INSERT INTO users VALUES($ID, $fn, $ln, $sx, $tl, $st)”;
$result = mysql_query($query);
if (mysql_affected_rows($result) >= 1)
echo ‘<P>Your information has been saved.</P>’;
else
echo ‘<P>Something went wrong with your signup attempt.</P>’;
?>
3.1 Database
Programming…
In addition to insertion, you can do many other operations on database
using SQL
SELECT item_list FROM table_list WHERE search_condition;
select lname, fname, balance from account where balance > 10000
CREATE TABLE table-name (column-name data-type, .... )
Create table customer(lname varchar(20), fname varchar(20), branch
varchar(30), balance number);
INSERT INTO table_name(column_names) VALUES (value_list)
INSERT INTO account (lname, fname, branch, balance) VALUES ('john',
'smith', 101, 10000)
DELETE FROM table_name WHERE search_condition
DELETE FROM account where fname = 'john' and lname = 'smith'
UPDATE table_name SET column_names expression WHERE condition
UPDATE account SET balance = balance * 1.06 where balance > 1000
3.1 Database
Programming…
Closing the connection
Any open database connections are closed when
the script ends.
However, it is good programming practice to
close the connections in the script to avoid any
possible problems.
You close database connections with a PHP
function
For example, for MySQL, use the following
function to close a database connection:
mysql_close($connect);
Other PHP-Database Functions
ODBC functions.
You can have multiple connections open at once.
while(($row = odbc_fetch_array($rs,
ODBC_ASSOC_ARRAY)) != NULL)
{
print(" ". $row['fullname']. "<BR>");
print(" ". $row['birth_date']. "<BR>");
print(" ". $row['email']. "<BR>");
}
odbc_close($con);
Classes in PHP
The basic elements of object-oriented programs are objects.
It’s easiest to understand objects as physical objects.
For example, a car is an object.
A car has properties, such as color, model, engine, and
tires, also called attributes.
A car has things it can do, too, such as move forward, move
backward, park, roll over, and play dead (well, mine does
anyway).
class classname
{
//code
}
In order to be useful, our classes need attributes and
operations.
We create attributes by declaring variables within a class
definition.
The following code will create a class named car with two
operations.
Classes in PHP…
class car
{
var $name;
var $speed;
function moveforward()
{
//code here
}
function reverse($param1, $param2)
{
//code here
}
}
Classes in PHP…
Constructors
Most classes will have a special type of operation called a
constructor.
A constructor is called when an object is created, and
performs useful initialization tasks such as setting attributes
to sensible starting values or
creating other objects needed by this object.
Example:
class Car {
private $gas = 0;
function addGas($amount)
{
$this->gas = $this->gas + $amount;
echo “$amount gallons added to gas tank”;
}
Classes in PHP…
In the following code, line 2 and 3 generates
error because $gas is private:
$mycar = new Car();
$gas_amount = $mycar->gas;
$mycar->gas = 20;
Classes in PHP…
Implementing Inheritance in PHP
If our class is to be a subclass of another, you can use the extends keyword to
specify this.
class A
{
var $attribute1;
function operation1()
{
//code here
}
}
class B extends A
{
var $attribute2;
function operation2()
{
//code here
}
Classes in PHP…
All the following accesses to operations and attributes of an
object of type B would be valid:
$b = new B();
$b->operation1();
$b->attribute1 = 10;
$b->operation2();
$b->attribute2 = 10;
your job-search Web site or pictures to your photo album Web site.
You can display a form that allows a user to upload a file by using
an HTML form designed for that purpose.
The general format of the form is as follows:
In this array, name is the name of the file that was uploaded,
type is the type of file, tmp_name is the path/filename of the
temporary file, and size is the size of the file.
Notice that name contains only the filename, while tmp_name
includes the path to the file as well as the filename.
3.2 Working with Files…
If the file is too large to upload, the
tmp_name in the array is set to none, and the
size is set to 0.
By default, PHP stores the temporary
uploaded file in your temp directory on
Windows or /tmp on Unix/Linux.
You can change the location of temporary
files by setting php.ini.
Look in your php.ini file for the following line:
upload_tmp_dir =
3.2 Working with Files…
Moving Uploaded Files To Their Destination
Since the temporary file created during upload is
deleted when the script finishes, it has to be moved to
another location if you want to store it permanently.
The general format of the statement that moves the
file is as follows:
move_uploaded_file(path/tempfilename,
path/permfilename);
Using a database for data storage requires you to install and learn
to use database software, such as MySQL or Oracle.
The data is stored in the database and can only be accessed by
the database software.
Databases can store very complex information that you can
retrieve easily.
File Input/Output…
You don’t need to know how the data is stored, just how to interact
with the database software.
The database software handles the storage and delivers the data,
without the script needing to know exactly where or how the
customer name is stored.
The first step, before you can write information into or read
information from a file, is to open the file.
The following is the general format for the statement that opens a
file:
$fh = fopen(“filename”,”mode”)
Mode what it means what happens when file does not exist
The final way we can read from a file is using the fread() function
to read an arbitrary number of bytes from the file.
This function has the following prototype:
string fread(int fp, int length);
It reads up to length bytes or to the end of file, whichever comes
first.
File Input/Output…
Writing to a File
Writing to a file in PHP is relatively simple.
You can use either of the functions fwrite() or fputs()
fputs() is an alias to fwrite().
We call fwrite() in the following:
fwrite($fp, $outputstring);
PHP has functions that allow you to find out file information about
You can find out whether a file exists with the file_exists
statement, as follows:
$result = file_exists(filename);
After this statement, $result contains either TRUE or FALSE.
The function is often used in a conditional statement, such as the
following:
if(!file_exists(“stuff.txt”))
{
echo “File not found!\n”;
}
File Input/Output…
Function What It Does Output
is_file(“stuff.txt”) Tests whether the file is a regular file, rather than TRUE or FALSE
a directory or other special type of file
is_dir(“stuff.txt”) Tests whether the file is a directory TRUE or FALSE
is_executable(“do.txt”) Tests whether the file is executable TRUE or FALSE
is_writable(“stuff.txt”) Tests whether you can write to the file TRUE or FALSE
is_readable(“stuff.txt”) Tests whether you can read the file TRUE or FALSE
filesize(“stuff.txt”) Returns the file size in bytes Integer or FALSE
basename(“/t1/do.txt”) Returns the filename from the path do.txt
dirname(“/t1/do.txt”) Returns the directory name from the path /t1
copy(oldfile, newfile) Copy an existing file into a new file TRUE or FALSE
rename(oldname,newname) renames a file oldname to newname TRUE or FALSE
unlink(“badfile.txt”) deletes an unwanted file TRUE or FALSE
File Input/Output…
Example:
if(!file_exists(“library.txt”))
copy(“book.txt”, ”library.txt”);
else
echo “File already exists!\n”;
readfile(“library.txt”);
Working with Date and Time
echo time();
output:
1060751270
This represents August 12th, 2003 at 10:07PM
Working with Date and
Time…
The integer returned by time() represents the number
of seconds elapsed since midnight GMT on January 1,
1970.
This moment is known as the Unix epoch, and the
number of seconds that have elapsed since then is
referred to as a timestamp.
PHP offers excellent tools to convert a timestamp into
a form that humans are comfortable with.
Output:
11/29/11 11.26:53
Working with Date and
Time…
You can get information about the current time, but you
cannot yet work with arbitrary dates.
mktime() returns a timestamp that you can then use
with date() or getdate().
mktime() accepts up to six integer arguments in the
following order: Hour, Minute, Seconds, Month, Day of
month, Year.
The format is:
$dt = mktime(hour, minute, seconds, month, date, year);
For example, you would store the date January 15, 2003,
by using the following statement:
$birthdate = mktime(0, 0, 0, 1, 15, 2003);
Working with Date and
Time…
<?php
// make a timestamp for Aug 23 2003 at 4.15 am
$ts = mktime(4, 15, 0, 8, 23, 2003);
echo date("m/d/y G.i:s", $ts);
echo "<br>";
echo "The date is ";
echo date("j of F Y, \a\\t g.i a", $ts );
?>
Output:
08/23/03 4.15:00
The date is 23 of August 2003, at 4.15 am
Working with Date and
Time…
You might need to accept date information from user input.
Before you work with a user-entered date or store it in a
database, you should check that the date is valid.
This can be done using checkdate() that accepts three
integers: month, day, and year.
checkdate() returns true if the month is between 1 and 12,
the day is acceptable for the given month and year, and
the year is between 0 and 32767.
exp() Takes a single argument and raises e to that power. The value of exp($x) is e x.
log() The “natural log” function. Takes a single argument and returns its base e logarithm.
If ey = x, then the value of log($x) is y.
log10() Takes a single argument and returns its base-10 logarithm. If 10 y = x, then the value
of log10($x) is y.
sin() Takes a numerical argument in radians and returns the sine of the argument as a
double.
cos() Takes a numerical argument in radians and returns the cosine of the argument as a
double.
tan() Takes a numerical argument in radians and returns the tangent of the argument as a
double.
asin() Takes a numerical argument and returns the arcsine of the argument in radians.
Inputs must be between –1.0 and 1.0, otherwise, it will return a result of NAN.
Results are in the range –pi / 2 to pi / 2.
acos() Takes a numerical argument and returns the arccosine of the argument in
radians. Inputs must be between –1.0 and 1.0, otherwise, it will return a result
of NAN. Results are in the range 0 to pi.
atan() Takes a numerical argument and returns the arctangent of the argument in
radians. Results are in the range –pi / 2 to pi / 2.
atan2() A variant of atan() that takes two arguments. Atan($y, $x) is identical to
atan($y/$x) when $x is positive, but the quadrant of atan2’s result depends on
the signs of both $y and $x. Range of the result is from –pi to pi.
Output:
150 in base 10 is 10010110 in base 2
150 in base 10 is 12120 in base 3
150 in base 10 is 2112 in base 4
150 in base 10 is 1100 in base 5
150 in base 10 is 410 in base 6
150 in base 10 is 303 in base 7
150 in base 10 is 226 in base 8