Professional Documents
Culture Documents
page: 1
Contents
PHP
Chapter 1: Introduction to PHP
Chapter 2: Data type and Variable
Chapter 3: Control Structure
Chapter 4: Loop Structure
Chapter 5: PHP Array Objects
Chapter 6: PHP Function
Chapter 7: PHP Forms
Chapter 8: PHP Date Function
MySQL
Chapter 9: MySQL Database
Chapter10: PHP MySQL Database Connection
Chapter11: PHP cookies and sessions
Chapter12: PHP Include and Require
page: 2
Table of Contents
PHP
Chapter 1:
Introduction to PHP
Introduction to PHP .................................................................................6
How the Pieces of the AMP Module Work Together ..............................6
Apache .....................................................................................................7
PHP (Hypertext Preprocessor) .................................................................7
MySQL ....................................................................................................8
Chapter 2:
Chapter 3:
Control Structure
If Statement ..............................................................................................15
if.....else Statements ........................................................................15
if.....else if Statements .....................................................................16
switch Statements.....................................................................................17
Chapter 4:
Loop Structure
Looping ................................................................................................19
The while Statement ................................................................................19
The do while statement ....................................................................22
The for statement .....................................................................................23
The foreach statement ..............................................................................25
page: 3
Chapter 5:
Chapter 6:
PHP Function
PHP Function ...........................................................................................41
What is function? .....................................................................................41
Naming Your Function ............................................................................42
Using Parameters .....................................................................................43
Returning from Functions ........................................................................46
Returning Values from Functions ............................................................48
Chapter 7:
PHP Forms
Overview ................................................................................................50
The GET method......................................................................................50
The POST method....................................................................................53
The $_REQUEST variable ......................................................................55
Using Array as form elements values ......................................................57
Chapter 8:
MySQL
Chapter 9:
MySQL Database
What is MySQL? .....................................................................................62
Text Types ...............................................................................................62
Number Types ..........................................................................................63
Date Types ...............................................................................................63
Column Modifiers ....................................................................................63
Working with SQL Command .................................................................64
Working with SQL statements .................................................................65
page: 4
page: 5
Chapter 1:
Introduction to PHP
Introduction to PHP
PHP is a powerful language and the interpreter, whether included in a web server as a module
or executed as a separate CGI binary, is able to access files, execute commands and open
network connections on the server. These properties make anything run on a web server
insecure by default. PHP is designed specifically to be a more secure language for writing CGI
programs than Perl or C, and with correct selection of compile-time and runtime configuration
options, and proper coding practices, it can give you exactly the combination of freedom and
security you need.
As there are many different ways of utilizing PHP, there are many configuration options
controlling its behavior. A large selection of options guarantees you can use PHP for a lot of
purposes, but it also means there are combinations of these options and server configurations
that result in an insecure setup.
The configuration flexibility of PHP is equally rivaled by the code flexibility. PHP can be used
to build complete server applications, with all the power of a shell user, or it can be used for
simple server-side includes with little risk in a tightly controlled environment. How you build
that environment, and how secure it is, is largely up to the PHP developer.
Apache: This is your highly trained master of culinary arts, the chef. Whatever people
ask for, she prepares it without complaint. She is quick, flexible, and able to prepare a
multitude of different types of foods. Apache acts in much the same way as your HTTP
server, parsing files and passing on the results.
PHP: This is the waiter. He gets requests from the patron and carries them back to the
kitchen with specific instructions about how the meal should be prepared.
MySQL: This is your stockroom of ingredients (or in this case, information).
page: 6
When a patron (or Web site visitor) comes to your restaurant, he or she sits down and orders a
meal with specific requirements, such as a steak, well done. The waiter (PHP) takes those
specific requirements back to the kitchen and passes them off to the chef (Apache). The chef
then goes to the stockroom (MySQL) to retrieve the ingredients (or data) to prepare the meal
and presents the final dish to the patron, exactly the way he or she ordered the meal.
Apache
Apache acts as your Web server. Its main job is to parse any file requested by a browser and
display the correct results according to the code within that file. Apache is quite powerful and
can accomplish virtually any task that you, as a Webmaster, require.
The version of Apache covered in this book is the most recent and stable at the time of this
writing: version 2.0.47. The features and server capabilities available in this version include the
following:
According to the Netcraft Web site (www.netcraft.com), at the time of this writing Apache is
running over 27 million Internet servers, more than Microsoft, Sun ONE, and Zeus combined.
Its flexibility, power, and, of course, price make it a popular choice. It can be used to host a
Web site to the general public, or a company-wide intranet, or for simply testing your pages
before they are uploaded to a secure server on another machine. Later in this chapter, we
discuss how to configure your Apache setup to accommodate all of these options.
page: 7
The version of PHP referenced in this book is the most recent stable release at the time of
publication: version 4.3.3. Although we discuss several of the most common uses and
functions of PHP, you can find a complete list of PHP functions in Appendix B of this book.
As you continue to program in PHP and your comfort level increases (or the demands of your
boss grow), we encourage you to expand your use of built-in PHP functions to take advantage
of its tremendous power. You can download the PHP software from PHPs Web site at
www.php.net.
MySQL
Another open source favorite, MySQL is the database construct that enables PHP and Apache
to work together to access and display data in a readable format to a browser. It is a Structured
Query Language server designed for heavy loads and processing of complex queries. As a
relational database system, MySQL allows many different tables to be joined together
for maximum efficiency and speed.
This book references version 4.0.15a, the most stable release of MySQL at the time of
publication. While a complete list of features can be found at the MySQLWeb site
(www.mysql.com), some of the more popular features of this program are as follows:
MySQL is the perfect choice for providing data via the Internet because of its ability to handle
heavy loads and its advanced security measures.
page: 8
Chapter 2:
page: 9
You should always keep in mind these two basic rules of PHP:
PHP is denoted in the page with opening and closing tags as follows:
<?php
. . . . . .
?>
Or
<?
. . . . . .
?>
PHP Comments
Comments can be added to explain the JavaScript, or to make it more readable.
Single line comments start with //.
Multi line comments start with /* and end with */.
page: 10
Ex: first_prog.php
<html>
<head>
<title>Build Bright University</title>
</head>
<body>
<?php
define ("favmovie", "PHP(Hypertext Preprocessor) ");
echo "My favorite language is ";
echo favmovie;
?>
</body>
</html>
Result:
Overview of variables
Unlike constants, variables are obviously meant to be variablethey are meant to change or be
changed at some point in your program. Variables also do not need to be defined or declared
and can simply be assigned when needed.
Variables are denoted with a dollar sign ($) and are not case-sensitive as are constants.
Syntax:
$variable_name=value;
Note: Variable Naming Rules
- A variable name must start with a letter or an underscore "_"
- A variable name can only contain alpha-numeric characters and underscores
- A variable name should not contain spaces. If a variable name is more than one word, it
should be separated with underscore ($my_string), or with capitalization ($MyString)
page: 11
Ex: first_prog.php
<html>
<head>
<title>Build Bright University</title>
</head>
<body>
<?php
$phpstand="Hypertext Preprocessor";
$current_year=2010;
echo "PHP stand ";
echo $phpstand;
echo "<br>Current Year: ";
echo $current_year;
?>
</body>
</html>
Result:
?>
page: 12
Description
Addition
Subtraction
Multiplication
Division
Modulus (division remainder)
%
++
--
Increment
Decrement
Example
x=2
x+2
x=2
5-x
x=4
x*5
15/5
5/2
5%2
10%8
10%2
x=5
x++
x=5
x--
Result
4
3
20
3
2.5
1
2
0
x=6
x=4
Assignment Operators
Youve already seen the basic assignment operator (=). Always refer to this as the assignment
operator and read it as is set to.
Combination Assignment Operators
In addition to the simple assignment, there is a set of combined assignment operators. Each of
them is a shorthand way of performing another operation on a variable and assigning the result
back to that variable.
Operator
=
+=
-=
*=
/=
.=
%=
Example
x=y
x+=y
x-=y
x*=y
x/=y
x.=y
x%=y
Is The Same As
x=y
x=x+y
x=x-y
x=x*y
x=x/y
x=x.y
x=x%y
page: 13
Comparison Operators
The comparison operators compare two values. Expressions using these operators return either
of the logical values true or false depending on the result of the comparison.
Given that x=5, the table below explains the comparison operators:
Operator
==
===
!=
>
<
>=
<=
Description
Example
is equal to
is exactly equal to (value and type)
is not equal
is greater than
is less than
is greater than or equal to
is less than or equal to
x= =8 is false
x= = =5 is true
x= = ="5" is false
x!=8 is true
x>8 is false
x<8 is true
x>=8 is false
x<=8 is true
Logical Operators
Logical operators are used to determine the logic between variables or values.
Given that x=6 and y=3, the table below explains the logical operators:
Operator
&&
||
!
and
or
Description
AND
OR
NOT
AND
OR
Example
(x < 10 && y > 1) is true
(x==5 || y==5) is false
!(x==y) is true
Same as &&, but with lower precedence
Same as ||, but with lower precedence The
Conditional Operator
PHP also contains a conditional operator that assigns a value to a variable based on some
condition.
Syntax:
Ex:cond_operator.php
<?php
$score=49;
echo $score>50?"Pass":"False";
?>
page: 14
Chapter 3:
Control Structure
If you want to sensibly respond to your users input, your code needs to be able to make
decisions. The constructs that tell your program to make decisions are called conditionals.
If Statement
You can use an if statement to make a decision. You should give the if statement a
condition to use. If the condition is true, the following block of code will be executed.
Conditions in if statements must be surrounded by parentheses ( ).
Syntax:
if (condition){
Block statement;
}
Ex: if_statement.php
<html>
<head>
<title>Test php</title>
</head>
<body>
<?
$a=10;
$b=15;
if($a>$b){$max=$a;}
if($a<$b){$max=$b;}
echo "a=".$a." & b=".$b. "<br>Max is ".$max;
?>
</body>
</html>
if.....else Statements
You may often need to decide not only whether you want an action performed, but also
which of a set of possible actions you want performed.
An else statement allows you to define an alternative action to be taken when the
condition in an if statement is false. Say you want to warn Bobs customers when they do not
order anything. On the other hand, if they do make an order, instead of a warning, you want to
show them what they ordered.
Syntax:
if (condition){
Statement to be execute if condition is true}
else{
Statement to be execute if condition is not true}
page: 15
Ex: if_else.php
<html>
<body>
<?
$a=10;
$b=15;
if($a>$b){
$max=$a;
}
else{
$max=$b;
}
echo "a=".$a." & b=".$b. "<br>Max is ".$max;
?>
</body>
</html>
if.....else if Statements
For many of the decisions you make, you have more than two options. You can create a
sequence of many options using the else if statement, which is a combination of an else and an
if statement. When you provide a sequence of conditions, the program can check each until it
finds one that is true.
Syntax:
if (condition){block statement1;}
elseif (condition1) {block statement 2;}
elseif (condition2) {block statement 3;}
else{block n;}
Ex: if_elseif.php
<html>
<body>
<?php
$d=date("D");
if ($d=="Fri")
echo "Today is $d <br>Have a nice weekend!";
elseif ($d=="Sun")
echo "Today is $d <br>Have a nice Sunday!";
else
echo "Today is $d <br>Have a nice day!";
?>
</body>
</html>
page: 16
switch Statements
The switch statement works in a similar way to the if statement, but it allows the condition to
take more than two values. In an if statement, the condition can be either true or false. In a
switch statement, the condition can take any number of different values, as long as it evaluates
to a simple type (integer, string, or float).You need to provide a case statement to handle each
value you want to react to and, optionally, a default case to handle any that you do not provide
a specific case statement for.
Syntax:
switch (expression)
{
case label1:
code to be executed if expression = label1;
break;
case label2:
code to be executed if expression = label2;
break;
default:
code to be executed
if expression is different
from both label1 and label2;
}
Ex:switch.php
<html>
<body>
<?php
$x=date("N");
switch ($x)
{
case 1:
echo "Number
break;
case 2:
echo "Number
break;
case 3:
echo "Number
break;
case 4:
echo "Number
break;
case 5:
echo "Number
break;
$x = Monday";
$x = Tuesday";
$x = Wednesday";
$x = Thursday";
$x = Friday";
page: 17
switch.php (continues)
case 6:
echo "Number $x = Satureday";
break;
default:
echo "Number $x = Sunday";
}
?>
</body>
</html>
page: 18
Chapter 4:
Loop Structure
Looping statements in PHP are used to execute the same block of code a specified number of
times.
Looping
Very often when you write code, you want the same block of code to run a number of times.
You can use looping statements in your code to perform this.
In PHP we have the following looping statements:
while - loops through a block of code if and as long as a specified condition is true
do...while - loops through a block of code once, and then repeats the loop as long as a
special condition is true.
for - loops through a block of code a specified number of times
foreach - loops through a block of code for each element in an array
Syntax:
while (condition){
code to be executed;
}
page: 19
Ex: while_loop.php
<html>
<head>
<title>A while Statement</title>
</head>
<body>
<?php
$counter = 1;
while ( $counter <= 10 ) {
print "$counter times 2 is ".($counter*2)."<br>";
$counter++;
}
?>
</body>
</html>
Result:
page: 20
Result:
page: 21
do
{
code to be executed;
}
while (condition);
Ex1: do_while.php
<html>
<body>
<?php
$i = 100;
do {
echo $i;
} while ($i <0);
?>
</body>
</html>
Ex2:even_odd.php
<html>
<head>
<title>A while Statement</title>
</head>
<body>
<?php
$i = 1;
do {
if ($i % 2 == 1) {
print "$i is an odd number<br>";
} else {
print "$i is an even number<br>";
}
++$i;
} while ($i < 10);
?>
</body>
</html>
page: 22
Result:
Ex:for.php
<html>
<head>
<title>A while Statement</title>
</head>
<body>
<?php
$i = 0;
for($i=0;$i<=10;$i+=2){
print "line: ".$i."<br>";
}
?></body>
</html>
page: 23
Result:
Ex2: table_bgcolor.php
<html>
<head>
<title>The for loop statement</title>
</head>
<body>
<table width="300" border="0" cellspacing="0" cellpadding="0"
align="center">
<tr>
<td bgcolor="#CCCCFF">Alternating row colors</td>
</tr>
<?php
for ($i = 1; $i <= 10; $i++) {
if ($i % 2) {
$color = '#FFFFCC';
}
else {
$color = '#CCCCCC';
}
?>
<tr>
<td bgcolor="<?php echo $color; ?>">
<?php echo "Line: ".$i; ?>
</td>
</tr>
<?php
}
?>
</table>
</body>
</html>
page: 24
Result:
Syntax:
For every loop, the value of the current array element is assigned to $value (and the array
pointer is moved by one) - so on the next loop, you'll be looking at the next element.
Ex:foreach.php
<html>
<body>
<?php
$arr=array("one", "two", "three");
foreach ($arr as $value){
echo "Value: " . $value . "<br />";
}
?>
</body>
</html>
page: 25
Ex2:foreach_table.php
<html>
<body>
<table border="1" width="300" align="center"
cellspacing="0" cellpadding="1">
<tr>
<th bgcolor="lightblue">
Read array value into table
</th>
</tr>
<?php
$arr=array("one", "two", "three");
foreach ($arr as $value){
echo "<tr>";
echo "<td>" . $value . "</td>";
echo "</tr>";
}
?>
</table>
</body>
</html>
Result:
page: 26
Chapter 5:
Introduction
Weve talked about variables and how they are used, but what if we had more than one value
assigned to that variable? That, my friends, is a good old-fashioned array. Arrays are nothing
more than lists of bits of information mapped with keys and stored under one variable name.
For example, you can store a persons name and address or a list of states in one variable.
Whats array?
An array is a data structure that stores one or more similar type of values in a single value.
There are three different kinds of arrays and each array value is accessed using an ID which is
called array index.
Numeric array - An array with a numeric index. Values are stored and accessed in linear
fashion
Associative array - An array with strings as index. This stores element values in
association with key values rather than in a strict linear index order.
Multidimensional array - An array containing one or more arrays and values are accessed
using multiple indices.
Numeric Array
These arrays can store numbers, strings and any object but their index will be pre-presented by
numbers. By default array index starts from zero.
Syntax:
$names[key] = value; or
$names = array("value0","value1","value2");
Set string value into array:
Ex:
$name=array(Sok ,Chan, Nara, Nary, Ratha);
or
$name[0]=Sok;
$name[1]=Chan;
$name[2]=Nara;
$name[3]=Nary;
$name[4]=Ratha;
Set string value into array:
Ex:
$score=array(10,20,30,40,50);
page: 27
page: 28
Result:
page: 29
Associative Arrays
The associative arrays are very similar to numeric arrays in term of functionality but they
are different in terms of their index. Associative array will have their index as string so that
you can establish a strong association between key and values.
Syntax:
$array_name=("key0"=>"value0","key1"=>"value1",); or
$array_name["key"]= "value";
Set string value into array:
Ex:
$name[firstname] = Sok;
$name[lastname] = San;
or
$name = array(firstname=>Sok, lastname=>San);
Note:
If you wanted to simply store a list and not worry about the particular order, or what each
value should be mapped to (such as a list of states or flavors of shaved ice), you dont need to
explicitly name the keys and PHP will assign invisible internal keys for processing. This would
be set up as follows:
page: 30
<?php
$flavor[] = "blue raspberry";
$flavor[] = "root beer";
$flavor[] = "pineapple";
?>
Ex:asso_array.php
<html>
<head>
<title>
Associate Array
</title>
</head>
<body>
<h3>First method</h3>
<hr color="darkblue" size=1>
<?php
/* First method to create associative array. */
$salaries = array("sophal" => "500 $","sreyleak" => "300 $",
"narry" => "100 $");
echo "Salary of sophal is ". $salaries['sophal'] . "<br />";
echo "Salary of sreyleak is ".$salaries['sreyleak']."<br />";
echo "Salary of narry is ". $salaries['narry']. "<br />";
/* Second method to create associative array. */
echo "<h3>Second method</h3>";
echo "<hr color='darkblue' size=1>";
$salaries['sophal'] = "high";
$salaries['sreyleak'] = "medium";
$salaries['narry'] = "low";
echo "Salary of sophal is ". $salaries['sophal'] . "<br />";
echo "Salary of sreyleak is ".$salaries['sreyleak']."<br />";
echo "Salary of narry is ".$salaries['narry']. "<br />";
?>
</body>
</html>
page: 31
Result:
page: 32
Result:
each( ) construct
The following code lists the contents of the $prices array using the each() construct:
Ex: each_ass.php
<html>
<head>
<title>Using each() construct</title>
</head>
<body>
<h3>Using each() construct to access associative</h3>
<hr color="darkblue" size="1">
<?php
$salaries = array("sophal" => "500 $","sreyleak" => "300 $",
"narry" => "100 $");
while( $element = each( $salaries ) )
{
echo $element[ 'key' ];
echo ' - ';
echo $element[ 'value' ];
echo '<br />';
}
?>
</body>
</html>
page: 33
Result:
list( ) construct
There is a more elegant and more common way of doing the same thing. The construct
list( ) can be used to split an array into a number of values. You can separate two of the values
that the each( ) function gives you like this:
$salaries = array("sophal" => "500 $","sreyleak" => "300 $",
"narry" => "100 $");
list( $employee, $value ) = each( $salaries);
This line uses each() to take the current element from $prices, return it as an array, and make
the next element current. It also uses list() to turn the 0 and 1 elements from the array returned
by each() into two new variables called $employee and $value. You can loop through the entire
$value array, echoing the contents using this short script:
page: 34
Ex:list_ass.php
<html>
<head>
<title>Using list() construct</title>
</head>
<body>
<h3>Using list() construct to access associative</h3>
<hr color="darkblue" size="1">
<?php
$salaries = array("sophal" => "500 $","sreyleak" => "300 $",
"narry" => "100 $");
while( list( $employee, $value )= each($salaries))
{
echo "$employee - $value <br />";
}
?>
</body>
</html>
Result:
page: 35
Multidimensional Arrays
A multi-dimensional array each element in the main array can also be an array. And
each element in the sub-array can be an array, and so on. Values in the multi-dimensional array
are accessed using multiple index.
Ex:mul_array.php
<html>
<head>
<title>Multidimensional Array</title>
</head>
<body>
<h3 style="letter-spacing:2px;font-family:arial; backgroundcolor: lightblue">Using Multidimensional Array
</h3>
<hr size="1" color="darkblue">
<?php
$markes = array(
"sophal"
?>
</body>
</html>
page: 36
Result:
Description
array( )
Create an array
array_combine( )
Creates an array by using one array for keys and another for its
values
array_count_values( )
array_diff( )
array_diff_assoc( )
array_diff_key( )
array_diff_uassoc( )
array_diff_ukey( )
array_fill( )
array_fill_keys( )
array_filter( )
array_flip( )
page: 37
array_intersect( )
array_intersect_assoc( )
array_intersect_key( )
array_intersect_uassoc( )
array_intersect_ukey( )
array_key_exists( )
array_keys( )
array_map( )
array_merge( )
array_merge_recursive( )
array_multisort( )
array_pad( )
array_pop( )
array_product( )
array_push( )
array_rand( )
array_reduce( )
array_reverse( )
array_search( )
array_shift( )
Removes the first element from an array, and returns the value of
the removed element
array_slice( )
array_splice( )
array_sum( )
array_udiff( )
array_udiff_assoc( )
array_udiff_uassoc( )
page: 38
array_uintersect( )
array_uintersect_assoc( )
array_unshift( )
array_values( )
array_walk( )
array_walk_recursive( )
arsort( )
asort( )
compact( )
count( )
current( )
each( )
end( )
extract( )
in_array( )
key( )
krsort( )
ksort( )
list( )
natcasesort( )
natsort( )
next( )
pos( )
Alias of current()
prev( )
range( )
reset( )
rsort( )
page: 39
shuffle( )
Shuffles an array
sizeof( )
Alias of count( )
sort( )
Sorts an array
uasort( )
uksort( )
usort( )
page: 40
Chapter 6:
PHP Function
PHP Function
PHP functions are similar to other programming languages. A function is a piece of code
which takes one more input in the form of parameter and does some processing and returns a
value.
Functions exist in most programming languages; they separate code that performs a
single, well-defined task. This makes the code easier to read and allows you to reuse the code
each time you need to perform the same task.
What is function?
A function is a block of code that can be executed whenever we need it.
Creating PHP functions:
All functions start with the word "function()"
Name the function - It should be possible to understand what the function does by its
name. The name can start with a letter or underscore (not a number)
Add a "{" - The function code starts after the opening curly brace
Insert the function code
Add a "}" - The function is finished by a closing curly brace
Syntax:
function function_name($Argument1,$Argument2)
{
block statements;
}
Note:
There are two parts which should be clear to you:
Creating a PHP Function
Calling a PHP Function
page: 41
Ex: show_msg.php
<html>
<head>
<title>.::Hypertext Proprocessor Function.</title>
<?
function showmsg(){
echo "Something really cool with Php.";
}
?>
</head>
<body>
<?
showmsg();
?>
</body>
</html>
Many languages do allow you to reuse function names. his feature is called function
overloading. However, PHP does not support function overloading, so your function cannot
have the same name as any built-in function or an existing user-defined function. Note that
although every PHP script knows about all the built-in functions, user-defined functions exist
only in scripts where they are declared. his means that you could reuse a function name in a
different file, but this would lead to confusion and should be avoided.
The following function names are legal:
name()
name2()
name_three()
_namefour()
These names are illegal:
5name()
name-six()
fopen()
page: 42
Note that although $name is not a valid name for a function, a function call like
$name( );
May well execute, depending on the value of $name. The reason is that PHP takes the value
stored in $name, looks for a function with that name, and tries to call it for you. This type of
function is referred to as a variable function and may occasionally be useful to you.
Using Parameters
To do their work, most functions require one or more parameters. A parameter allows
you to pass data into a function. Here is a sample function that requires a parameter; it takes a
one-dimensional array and displays it as a table:
Ex: getdata_into_table.php
function create_table($data)
{
echo "<table border = 1>";
reset($data); //Remember this is used to point to the
beginning
$value = current($data);
while ($value)
{
echo "<tr><td>$value</td></tr>\n";
$value = next($data);
}
echo "</table>";
}
page: 43
Summary code:
<?php
function create_table($data)
{
echo "<table border = 1 width=150>";
reset($data); //Remember this is used to point to the
beginning
$value = current($data);
while ($value)
{
echo "<tr><td>$value</td></tr>\n";
$value = next($data);
}
echo "</table>";
}
?>
<html>
<body>
<h3>Function with Parameter</h3>
<hr color="darkblue" size=1>
<?php
$my_array = array('Line one.','Line two.','Line three.');
create_table($my_array);
?>
</body>
</html>
Result:
page: 44
Ex: sum_func.php
<html>
<head>
<title>.:: Function with parameter</title>
<?php
function calculator($a,$b){
$x= $a+$b;
print $x;
}
?>
</head>
<body>
<h3>Function with Parameter</h3>
<hr color="darkblue" size=1>
<?php
echo "4+5=";
calculator(4,5);
?>
</body>
</html>
Result:
page: 45
Result:
page: 46
Obviously, this is not a very useful way to use return. Normally, you want to return
from the middle of a function only in response to a condition being met.
An error condition is a common reason to use a return statement to stop execution of a
function before the end. If, for instance, you write a function to find out which of two numbers
is greater, you might want to exit if any of the numbers are missing:
Ex2: larger.php
<?php
function larger( $x, $y )
{
if (!isset($x)||!isset($y))
{
echo "This function requires two numbers<br>";
return;
}
if ($x>=$y)
echo $x."<br>";
else
echo $y."<br>";
}
?>
<html>
<body>
<h3>Returning from function</h3>
<hr color="darkblue" size=1>
<?php
$a = 1;
$b = 2.5;
$c = 1.9;
larger($a, $b);
larger($c, $a);
larger($d, $a);
?>
</body>
</html>
page: 47
Result:
page: 48
Result:
Ex3: resturn_sum_func.php
<html>
<?
function sum_value($a,$b){
$sum=$a+$b;
return $sum;
}
?>
</head>
<h3>Returning value from function</h3>
<hr color="darkblue" size=1>
<body>
<?
$result=sum_value(4,5);
print "The result of sum 4 and 5 is ". $result;
?></body></html>
Result:
page: 49
Chapter 7:
PHP Forms
Overview
Using forms in a web based application is very common. Most forms are used to gather
information like in a signup form, survey / polling, guestbook, etc.
A form can have the method set as post or get. When using a form with method = "post" you
can use $_POST to access the form values. And when the form is using method = "get" you
can use $_GET to access the values. The $_REQUEST super global can be used to access
form values with method="post" and method="get" but it is recommended to use $_POST or
$_GET instead so you will know from what method did the values come from.
The GET method produces a long string that appears in your server logs, in the browser's
Location: box.
The GET method is restricted to send upto 1024 characters only.
Never use GET method if you have password or other sensitive information to be sent to the
server.
GET can't be used to send binary data, like images or word documents, to the server.
The data sent by GET method can be accessed using QUERY_STRING environment
variable.
The PHP provides $_GET associative array to access all the sent information using GET
method.
page: 50
Ex: post_method.php
<html>
<head><title>Using Method Get</title></head>
<body>
<form action="<?php $_PHP_SELF ?>" method="get">
<fieldset>
<legend>Using Get method</legend>
<table border=0>
<tr>
<td>Name:</td>
<td><input type="text" name="name"/></td>
</tr>
<tr>
<td>Age:</td>
<td><input type="text" name="age" /></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" /></td>
</tr>
<tr>
<td colspan="2">
<?php
if( $_GET["name"] !="" || $_GET["age"]!="" )
{
echo "Welcome <b>". $_GET['name']. "</b><br />";
echo "You are <b>". $_GET['age']. "</b> years old.";
exit();
}
?>
</td>
</tr>
</table>
</fieldset>
</form>
</body>
</html>
page: 51
Result:
After submit:
Everyone can see the values of the variables, so passing sensitive information isnt
really very secure using this method.
The user can change the variable value in the URL, leaving your site potentially open to
showing something youd rather not show.
A user might also pull up inaccurate or old information using a saved URL with older
variables embedded in it.
page: 52
The PHP provides $_POST associative array to access all the sent information using GET method.
Ex:post_method.php
<html>
<head><title>Using Method Get</title></head>
<body>
<form action="<?php $_PHP_SELF ?>" method="post">
<fieldset>
<legend>Using Post method</legend>
<table border=0>
<tr>
<td>Name:</td>
<td><input type="text" name="name"/></td>
</tr>
<tr>
<td>Age:</td>
<td><input type="text" name="age" /></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" /></td>
</tr>
<tr>
<td colspan="2">
<?php
if( $_POST["name"] !="" || $_POST["age"]!="" )
{
echo "Welcome <b>". $_POST['name']. "</b><br />";
echo "You are <b>". $_POST['age']. "</b> years old.";
exit();
}
?>
</td>
</tr>
</fieldset>
</form>
</body>
</html>
page: 53
Result:
After submit:
page: 54
page: 55
Result:
After submit:
page: 56
page: 57
Result:
After submit:
page: 58
Chapter 8:
Parameter
format
timestamp
date(format,timestamp);
Description
Required. Specifies the format of the timestamp
Optional. Specifies a timestamp. Default is the current date and time
Ex: date.php
<html>
<body>
<h3>Using Data Function</h3>
<hr color=darkblue size=1>
<?php
echo date("Y/m/d") . "<br />";// result: 2009/06/18
echo date("Y.m.d") . "<br />";// result: 2009.06.18
echo date("Y-m-d");
// result: 2009-06-18
?>
</body>
</html>
Result:
page: 59
Example
returned values
--01 to 31
Mon through Sun
1 to 31
Sunday through
l (lowercase) A full textual representation of the day of the week
Saturday
1 (for Monday)
ISO-8601 numeric representation of the day of the week
N
through 7 (for
(added in PHP 5.1.0)
Sunday)
st, nd, rd or th.
S
English ordinal suffix for the day of the month, 2 characters
Works well with j
0 (for Sunday)
w
Numeric representation of the day of the week
through 6 (for
Saturday)
z
The day of the year (starting from 0)
0 through 365
Week
----Example: 42 (the
ISO-8601 week number of year, weeks starting on Monday
W
42nd week in the
(added in PHP 4.1.0)
year)
Month
----A full textual representation of a month, such as January or January through
F
March
December
m
Numeric representation of a month, with leading zeros
01 through 12
M
A short textual representation of a month, three letters
Jan through Dec
n
Numeric representation of a month, without leading zeros
1 through 12
t
Number of days in the given month
28 through 31
Year
----1 if it is a leap
L
Whether it's a leap year
year, 0 otherwise.
ISO-8601 year number. This has the same value as Y, except
Examples: 1999 or
o
that if the ISO week number (W) belongs to the previous or
2003
next year, that year is used instead. (added in PHP 5.1.0)
Examples: 1999 or
Y
A full numeric representation of a year, 4 digits
2003
Examples: 99 or
y
A two digit representation of a year
03
Time
----format
Description
character
Day
--d
Day of the month, 2 digits with leading zeros
D
A textual representation of a day, three letters
j
Day of the month without leading zeros
page: 60
am or pm
AM or PM
000 through 999
1 through 12
0 through 23
01 through 12
00 through 23
00 to 59
00 through 59
page: 61
Chapter 9:
MySQL Database
1. What is MySQL?
MySQL is an open source Relational Database Management System (RDBMS) based
around the Structured Query Language (SQL). In short, MySQL is software that allows you to
manage your databases.
The data in MySQL is stored in database objects called tables. A table is a collection of related
data entries and it consists of columns and rows.
Database File
Database File: This is your main file that encompasses the entire
Database and that is saved to your hard-drive or floppy disk.
Tables
Table:
A table is a collection of data about a specific topic.
There can be multiple tables in a database.
Field:
Datatypes:
Field
Data type
Value
TEXT TYPES
CHAR( )
VARCHAR( )
TINYTEXT
TEXT
BLOB
MEDIUMTEXT
MEDIUMBLOB
LONGTEXT
LONGBLOB
The ( ) brackets allow you to enter a maximum number of characters will be used in the
Column.
CHAR and VARCHAR are the most widely used types. CHAR is a fixed length string and is
mainly used when the data is not going to vary much in it's length. VARCHAR is a variable
length string and is mainly used when the data may vary in length.
CHAR may be faster for the database to process considering the fields stay the same length
down the column. VARCHAR may be a bit slower as it calculates each field down the column,
but it saves on memory space. Which one to ultimately use is up to you.
Using both a CHAR and VARCHAR option in the same table, MySQL will automatically
change the CHAR into VARCHAR for compatibility reasons.
page: 62
BLOB stands for Binary Large Object. Both TEXT and BLOB are variable length types that
store large amounts of data. They are similar to a larger version of VARCHAR. These types
can store a large piece of data information, but they are also processed much slower.
NUMBER TYPES
TINYINT( )
SMALLINT( )
MEDIUMINT( )
INT( )
BIGINT( )
FLOAT
DOUBLE( , )
DECIMAL( , )
The integer types have an extra option called UNSIGNED. Normally, the integer goes from an
negative to positive value. Using an UNSIGNED command will move that range up so it starts
at zero instead of a negative number.
DATE TYPES
DATE
DATETIME
TIMESTAMP
TIME
YYYY-MM-DD.
YYYY-MM-DD HH:MM:SS.
YYYYMMDDHHMMSS.
HH:MM:SS.
2. Column Modifiers
A column modifier is an extra add on command to help the database organize and work better.
As mentioned on the previous page, the integer types have an extra option called UNSIGNED.
Normally, the integer goes from an negative to positive value. Using an UNSIGNED command
will move that range up so it starts at zero instead of a negative number.
Modifier commands are: INDEX, UNIQUE, PRIMARY KEY, AUTO_INCREMENT, NULL,
NOT NULL, DEFAULT, BINARY, and ZEROFILL.
Indexing:
is a way to improve a database performance. You are telling the database that THIS
specific column is special and may help organize the data. If there is a column you will be
referring to often, it would probably be the best to be an INDEX column.
An INDEX column may have more than one cell holding the same data value. The two other
index types are UNIQUE and PRIMARY KEY. UNIQUE states that each cell in the column
should have a unique value. PRIMARY KEY is a special variety of the UNIQUE command.
page: 63
The AUTO_INCREMENT
modifier works on any of the integer types. Each time a new row is added
into the database table, the number in this column will appear and automatically
increase by one from the previous row.
NULL:
is no value. It is not space, it is not zero. A majority of the time you will want to specify
a field to be NOT NULL so that any blank entries will be considered as "something".
DEFAULT:
will assign a default value to a cell if nothing is entered for the value. It will work on
most data types except BLOB and TEXT.
BINARY:
is used with CHAR and VARCHAR types. It causes the values to be treated as "binary
strings" making them Case Sensitive.
ZEROFILL:
is used with numeric data types. It will display leading zeros of a number based on the
display width.
page: 64
page: 65
b) Select statement
SELECT [ALL | DISTINCT | DISTINCTROW]
[Select expression ..]
FROM [tables]
WHERE [condition]
GROUP BY [column name]
HAVING [where condition]
ORDER BY {column name} [ASC | DESC]
LIMIT {[offset,] row_count};
Ex:
SELECT colA, colB FROM mytable;
SELECT colA, colB FROM mytable WHERE colA= condition;
c) Delete Statement
DELETE FROM table-name WHERE condition;
Ex: DELETE FROM tblstudents WHERE studentid=001;
d) Update Statement
UPDATE table-name SET column-name= WHERE condition;
Ex: UPDATE tblstudent SET dob=1980-11-21 WHERE studentid=001;
page: 66
Chapter 10:
page: 67
Ex: insertdata.php
tblstudents
Field Name
id
name
sex
dob
Data type
int(3)
varchar(50)
varchar(7)
date
page: 68
<html>
<head><title>Execute query string.</title></head>
<body>
<?php
$conn=mysql_connect("localhost","root","bbu") or
die("Connection Error ".mysql_error());
$db=mysql_select_db("studentsdb") or
die("Could not select database".mysql_error());
$sql=mysql_query("INSERT INTO tblstudents
VALUES(001,dara,Male,1988-07-21)")
or die(mysql_error());
if($sql)
echo "<br>Data inserted.";
else
echo "<br>Insert Fail.";
mysql_close($conn);
?>
</body>
</html>
mysql_fetch_row(query string);
mysql_fetch_array(query string);
page: 69
page: 70
Chapter 11:
PHP Cookies
What is a Cookie?
A cookie is often used to identify a user. A cookie is a small file that the server embeds on the
user's computer. Each time the same computer requests a page with a browser, it will send the
cookie too. With PHP, you can both create and retrieve cookie values.
How to Create a Cookie?
The setcookie() function is used to set a cookie.
Note: The setcookie() function must appear BEFORE the <html> tag.
Syntax:
setcookie(name, value, expire, path, domain);
Ex1: In the example below, we will create a cookie named "user" and assign the value "Alex
Porter" to it. We also specify that the cookie should expire after one hour:
Ex: cookie.php
<?php
setcookie("user", "Alex Porter", time()+3600);
?>
<html>
.....
Note:
The value of the cookie is automatically URLencoded when sending the cookie, and
automatically decoded when received (to prevent URLencoding, use setrawcookie() instead).
page: 71
Ex2: You can also set the expiration time of the cookie in another way. It may be easier than
using seconds.
cookie2.php
<?php
setcookie("user", "Alex Porter", time()+3600);
?>
<html>
.....
In the example above the expiration time is set to a month (60 sec * 60 min * 24 hours * 30
days).
In the following example we use the isset() function to find out if a cookie has been set:
isset_cookie.php
<html>
<body>
<?php
if (isset($_COOKIE["user"]))
echo "Welcome " . $_COOKIE["user"] . "!<br />";
else
echo "Welcome guest!<br />";
?>
</body>
page: 72
PHP Sessions
A PHP session variable is used to store information about, or change settings for a user
session. Session variables hold information about one single user, and are available to all pages
in one application.
page: 73
Ex1: session.php
<?php session_start(); ?>
<html>
<body>
</body>
</html>
The code above will register the user's session with the server, allow you to start saving user
information, and assign a UID for that user's session.
page: 74
Ex2: isset-session.php
<?php
session_start();
if(isset($_SESSION['views']))
$_SESSION['views']=$_SESSION['views']+1;
else
$_SESSION['views']=1;
echo "Views=". $_SESSION['views'];
?>
Destroying a Session
If you wish to delete some session data, you can use the unset() or the session_destroy()
function.
The unset() function is used to free the specified session variable:
Ex:delete_session.php
<?php
unset($_SESSION['views']);
?>
You can also completely destroy the session by calling the session_destroy() function:
<?php
session_destroy();
?>
Note: session_destroy() will reset your session and you will lose all your stored session data.
page: 75
Chapter 12:
These two functions are used to create functions, headers, footers, or elements that will be
reused on multiple pages.
Server side includes saves a lot of work. This means that you can create a standard header,
footer, or menu file for all your web pages. When the header needs to be updated, you can only
update the include file, or when you add a new page to your site, you can simply change the
menu file (instead of updating the links on all your web pages).
<html>
<body>
<?php include("header.php"); ?>
<h1>Welcome to my home page!</h1>
<p>Some text.</p>
</body>
</html>
page: 76
Ex2: Assume we have a standard menu file, called "menu.php", that should be used on all
pages:
<a
<a
<a
<a
<a
<a
href="/default.php">Home</a>
href="/tutorials.php">Tutorials</a>
href="/references.php">References</a>
href="/examples.php">Examples</a>
href="/about.php">About Us</a>
href="/contact.php">Contact Us</a>
All pages in the Web site should include this menu file. Here is how it can be done:
<html>
<body>
<div class="leftmenu">
<?php include("menu.php"); ?>
</div>
<h1>Welcome to my home page.</h1>
<p>Some text.</p>
</body>
</html>
page: 77
Error message:
Warning: include(wrongFile.php) [function.include]:
failed to open stream:
No such file or directory in C:\home\website\test.php on line
5
Warning: include() [function.include]:
Failed opening 'wrongFile.php' for inclusion
(include_path='.;C:\php5\pear')
in C:\home\website\test.php on line 5
Notice:
that the echo statement is executed! This is because a Warning does not stop the script
execution.
page: 78
Reference Book
Julie C. Meloni (2000), PHP Fast & Easy Web Development,
Prentice-Hall of India.
Bill McCarty (2001), PHP4: A Beginners Guide,
Osborne/McGraw-Hill
page: 79