Beruflich Dokumente
Kultur Dokumente
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 as the
array key.
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.
Whichever database you’re using, the steps to interact with a database are
similar:
1. Connect to the database.
2. Send an SQL query that contains instructions for the database software.
3. If you retrieved data from the database, process the data.
4. Close the connection to the database.
3.1 Database Programming…
Connecting to the database
The first step in a database interaction is connecting 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, $password);
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 the query you want to
run:
$query = “select * from books“;
You pass it the query you want to run, and optionally, the database
connection created.
3.1 Database Programming…
If connection isn’t specified, the function will use the last opened link.
If there isn’t one, the function will open the default one as if you had
called mysql_connect().
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”;
$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…
Processing Data
To process the data returned from database, you need to get it from
the temporary table where it is placed when the SQL query is
executed.
We use PHP database functions to get the data from the temporary
table.
$query = “SELECT ID, LastName, FirstName FROM users WHERE Status = 1”;
$result = mysql_query($query);
while ($row = mysql_fetch_assoc($result))
{
echo “$row[‘ID’], $row[‘LastName’], $row[‘FirstName’]<BR>\n”;
}
3.1 Database Programming…
The function mysql_fetch_object performs much the same
task
But the row is returned as an object rather than an array.
Obviously, this is helpful for those among those who utilize
the object-oriented notation:
$query = “SELECT ID, LastName, FirstName FROM users WHERE Status = 1”;
$result = mysql_query($query);
while ($row = mysql_fetch_object($result))
{
echo “$row->ID, $row->LastName, $row->FirstName<BR>\n”;
}
3.1 Database Programming…
The most general one is mysql_fetch_row, which can be
used something like this:
$query = “SELECT ID, LastName, FirstName FROM users WHERE Status = 1”;
$result = mysql_query($query);
while ($name_row = mysql_fetch_row($result))
{
print(“$name_row[0] $name_row[1] $name_row[2]<BR>\n”);
}
This code will output the specified rows from the
database, each line containing one row or the
information associated with a unique ID.
3.1 Database Programming…
In early versions of PHP, mysql_fetch_row was considered to be significantly faster
than mysql_fetch_object and mysql_fetch_array, but this is no longer an issue.
The PHP group now recommends use of mysql_fetch_array over mysql_fetch_row
because it offers increased functionality and choice at little cost in terms of
programming difficulty, performance loss, or maintainability.
The mysql_result function takes three arguments: result identifier, row identifier, and
field.
Field can take the value of the field offset as above, or its name as in an associative
array, or its MySQL field-dot-table name (“personal_info.Surname”).
3.1 Database Programming…
Example: a program that retrieves data from database and display in table
<?php
$con = mysql_connect("localhost",“root",“vertrigo"); //if no username and password needed
mysql_select_db(“customers”);
$query = “SELECT * FROM users”;
$result = mysql_query($query);
echo(“<TABLE>\n<TR><TH>Customers of ABC company</TH></TR>\n”);
while ($users_row = mysql_fetch_array($result)) {
echo “<TR>”;
echo(“<TD>$users_row[‘ID’]</TD>\n”);
echo(“<TD>$users_row[‘FirstName’]</TD>\n”);
echo(“<TD>$users_row[‘LastName’]</TD>\n”);
echo(“<TD>$users_row[‘Sex’]</TD>\n”);
echo(“<TD>$users_row[‘Telephone’]</TD>\n”);
echo(“<TD>$users_row[‘Status’]</TD>\n”);
echo “</tr>”;
}
echo(“</TABLE><BR>\n”);
?>
3.1 Database Programming…
Inserting Data into Database
Inserting new items into the database is remarkably
make a connection,
send a query, and
$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() == 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
mysql_affected_rows () — Get number of affected rows in previous
MySQL operation.
It helps you to know how many rows have been deleted, inserted,
modified, etc. by the last mysql_query() operation.
int mysql_affected_rows ( [resource link_identifier])
The optional fourth parameter sets the type of cursor to be used for this connection.
This parameter is not normally needed, but can be useful.
The following constants are defined for cursortype:
SQL_CUR_USE_IF_NEEDED
SQL_CUR_USE_ODBC
SQL_CUR_USE_DRIVER
SQL_CUR_DEFAULT
Using ODBC…
odbc_exec (resource connection_id, string query_string)
This returns an ODBC result identifier if the SQL command was
executed successfully.
odbc_exec() will send an SQL statement to the database
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).
A class is the script that serves as the template that is used to create
an object.
The class defines the properties, the attributes, of the object.
It also defines the things the object can do — its responsibilities.
Classes in PHP…
Defining a Class
A minimal class definition looks as follows:
class classname
{
//code
}
In order to be useful, our classes need attributes and operations.
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:
When the user submits the form, the file is uploaded to a temporary
location.
The script that processes the form needs to copy the file to another
location because the temporary file is deleted as soon as the script
is finished.
You can use phpinfo() to see where the temporary files are stored.
If you don’t like the location of the temporary directory, you can
change it by changing upload_tmp_dir in the php.ini file.
If no directory is specified in php.ini, a default temporary directory
is used.
3.2 Working with Files…
Accessing Information About An Uploaded File
Along with the file, information about the file is sent with the form.
For example, suppose you use the following field to upload a file:
<input type=”file” name=”user_file”>
3.2 Working with Files…
If the user uploads a file named test.txt by using the form, the
resulting array that can be used by the processing script looks
something like this:
echo $_FILES[‘user_file’][‘name’]; // test.txt
echo $_FILES[‘user_file’][‘type’]; // text/plain
echo $_FILES[‘user_file’][‘tmp_name’]; //D:\WINNT\php92C.tmp
echo $_FILES[‘user_file][size’]; // 435
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 system directory on Windows (Windows for
Win98/XP and Winnt for Win2000) 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.
Ability to handle multiple users: When many users store or access data in
a single file, such as a file containing names and addresses, a database
ensures that users take their turn with the file to avoid overwriting each
other’s data.
File Input/Output…
Using Flat Files
Flat files are also called text files.
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”)
The variable, $fh, referred to as a file handle, is used in the statements that
write data to or read data from the opened file.
$fh contains the information that identifies the location of the open file.
File Input/Output…
Mode what it means what happens when file does not exist
You can also open a file on another Web site by using a statement
such as the following:
$fh = fopen(“http://www.data.com/index.html”,”r”);
You can use a URL only with a read mode, not with a write mode.
File Input/Output…
To close a file after you have finished reading or writing it, use:
fclose($fh);
In this statement, $fh is the file handle variable you created when
you opened the file.
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.
fwrite($fp, $outputstring);
This tells PHP to write the string stored in $outputstring to the file
pointed to by $fp.
The function fwrite() actually takes three parameters but the third
one is optional.
The prototype for fwrite() is:
int fwrite(int fp, string str, int [length]);
File Input/Output…
The third parameter, length, is the maximum number of bytes to write.
If this parameter is supplied, fwrite() will write string to the file pointed to
by fp until it reaches the end of string or has written length bytes, whichever
comes first.
PHP has functions that allow you to find out file information about the files
from within a script.
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 TRUE or FALSE
than 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
PHP's time() function gives you all the information that
you need about the current date and time.
It requires no arguments and returns an integer.
For us humans, the returned number is a little hard on
the eyes, but it's extremely useful nonetheless.
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
Today is 29 of November 2011, at 11.26 am
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
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.
Be careful, though a date might be valid, it may not be acceptable
to other date functions.
For example, the following line returns true:
checkdate(4, 4, 1066);
Working with Date and Time…
If you were to attempt to build a date with mktime() using
these values, you'd end up with a timestamp of -1.
As a rule of thumb, don't use mktime() with years before
1902
Also be cautious of using date functions with any date
before 1970, as negative numbers are not valid dates.
Because the epoch began January 1, 1970, anything
before that is an invalid (negative) timestamp.
Mathematical Functions
PHP has built-in mathematical constants, and trigonometric,
logarithmic, and base conversion functions.
PHP constants are:
Constant Description Constant Description
M_PI Pi M_SQRT2 sqrt(2)
M_PI_2 pi/2 M_SQRT1_2 1/sqrt(2)
M_PI_4 pi/4 M_LOG2E log2(e)
M_1_PI 1/pi M_LOG10E log10(e)
M_2_PI 2/pi M_LN2 loge(2)
M_2_SQRTPI 2/sqrt(pi) M_LN10 loge(10)
M_E the constant e
function Behavior
pow() Takes two numerical arguments and returns the first argument raised to the power of the
second. The value of pow($x, $y) is xy.
exp() Takes a single argument and raises e to that power. The value of exp($x) is ex.
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 10y = x, then the value of log10($x)
is y.
pi() Takes no arguments and returns an approximation of pi (3.1415926535898). Can be used
interchangeably with the constant M_PI.
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
Mathematical Functions…
Function Behavior
BinDec() Takes a single string argument representing a binary (base 2)
integer, and returns a string representation of that number in base
10.
DecBin() Like BinDec(), but converts from base 10 to base 2.
OctDec() Like BinDec(), but converts from base 8 to base 10.
DecOct() Like BinDec(), but converts from base 10 to base 8.
HexDec() Like BinDec(), but converts from base 16 to base 10.
DecHex() Like BinDec(), but converts from base 10 to base 16.
Base_convert Takes a string argument (the integer to be converted) and two
() integer arguments (the original base, and the desired base). Returns
a string representing the converted number—digits higher than 9
(from 10 to 35) are represented by the letters a–z. Both the original
and desired bases must be in the range 2–36.
Mathematical Functions…
Example:
function display_bases($val, $first_base) {
for ($new_base = 2; $new_base <= 9; $new_base++)
{
$converted = base_convert($val, $first_base, $new_base);
print(“$val in base $first_base is $converted in base $new_base<BR>”);
}
}
display_bases(“150”, 10);
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
150 in base 10 is 176 in base 9