You are on page 1of 79

Build Bright University

Faculty of Information and Technology

Web Application Development

PHP and MySQL

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
Chapter 9: MySQL Database
Chapter10: PHP MySQL Database Connection
Chapter11: PHP cookies and sessions
Chapter12: PHP Include and Require

page: 1

Build Bright University

Faculty of Information and Technology

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

Build Bright University

Faculty of Information and Technology

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:

Data type and Variable


Overview of PHP Structure and Syntax...................................................9
How PHP Fits with HTML ......................................................................9
What is a PHP File? .................................................................................9
How to write php code .............................................................................9
PHP Comments ........................................................................................10
PHP Constants and Variables ..................................................................10
Overview of constants........................................................................10
Overview of variables ........................................................................11
The Concatenation Operator ....................................................................12
The PHP Operators ..................................................................................13
Arithmetic Operators .........................................................................13
Assignment Operators ........................................................................13
Comparison Operators .......................................................................14
Logical Operators...............................................................................14
Conditional Operator .........................................................................14

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

Build Bright University

Chapter 5:

Faculty of Information and Technology

PHP Array Objects


Introduction ..............................................................................................27
The while Statement ................................................................................27
Whats array? ...........................................................................................27
Numeric Array .........................................................................................27
Accessing Array Contents........................................................................30
Associative Arrays ...................................................................................30
Using Loops to Access the Array Contents .............................................32
The foreach loop ................................................................................32
each( ) construct .................................................................................33
list( ) construct ...................................................................................34
Multidimensional Arrays .........................................................................36
List of Array Functions ............................................................................37

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:

PHP Date Function


The PHP Date( ) Function........................................................................59
Date( ) - Format the Date .........................................................................60

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

Build Bright University

Faculty of Information and Technology

Chapter 10: PHP MySQL Database Connection


How to connect to php with mysql database server? ...............................67
How to close connection ....................................................................67
How to select database .......................................................................68
How to manipulate data from php with mysql...................................68

Chapter 11: PHP cookies and sessions


PHP Cookies ............................................................................................71
What is a Cookie? ..............................................................................71
How to Create a Cookie? ...................................................................71
How to Retrieve a Cookie Value? .....................................................72
How to Delete a Cookie? ...................................................................73
PHP Sessions ...........................................................................................73
PHP Session Variables .......................................................................73
Starting a PHP Session.......................................................................73
Storing a Session Variable .................................................................74
Destroying a Session ..........................................................................75

Chapter 12: PHP Include and Require


Server Side Includes (SSI) .......................................................................76
PHP include() Function............................................................................76
PHP require() Function ............................................................................77
Error Example require() Function ............................................................78
Error message...........................................................................................78

page: 5

Build Bright University

Chapter 1:

Faculty of Information and Technology

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.

How the Pieces of the AMP Module Work Together


Now that we have covered some of the history of open source, its important to understand the
role each of these programs (Apache, MySQL, and PHP) plays in creating your Web site.
Imagine that your dynamic Web site is a fancy restaurant. Diners come to your place, and each
one wants something different and specific. They dont worry so much about how the food is
prepared, as long as it looks and tastes delicious. Unlike a buffet-type spread, where everything
is laid out and your patrons simply choose from whats available (the analogy being a more
static, informational Web site with little interaction and input from your visitors), a nice
restaurant encourages patron/waiter interaction and complete customization for any specific
dietary needs (a dynamic Web site where the visitor can choose what he or she wants to see).
In this scenario, we can attribute the three components of the AMP module as follows:





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

Build Bright University

Faculty of Information and Technology

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:








Password-protected pages for a multitude of users


Customized error pages
Display of code in numerous levels of HTML, and the capability to determine at what
level the browser can accept the content
Usage and error logs in multiple and customizable formats
Virtual hosting for different IP addresses mapped to the same server
Directory Index directives to multiple files
URL aliasing or rewriting with no fixed limit

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.

PHP (Hypertext Preprocessor)


PHP is a server-side scripting language that allows your Web site to be truly dynamic. PHP
stands for PHP: Hypertext Preprocessor (and, yes, were aware PHP is a recursive cronym
probably meant to confuse the masses). Its flexibility and relatively small learning curve
(especially for programmers who have a background in C, Java, or Perl) make it one of the
most popular scripting languages around. PHPs popularity continues to increase as businesses
and individuals everywhere embrace it as an alternative to Microsofts ASP language and
realize that PHPs benefits most certainly outweigh the costs (three cheers for open source!).
According to Zend Technologies, Ltd., the central source of PHP improvements and designers
of the Zend Engine, which supports PHP applications, PHP code can now be found in
approximately 9 million Web sites.

page: 7

Build Bright University

Faculty of Information and Technology

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:










Multiple CPUs usable through kernel threads.


Multi-platform operation.
Numerous column types cover virtually every type of data.
Group functions for mathematical calculations and sorting.
Commands that allow information about the databases to be easily and succinctly
shown to the administrator.
Function names that do not affect table or column names.
A password and user verification system for added security.
Up to 32 indexes per table permitted; this feature has been successfully implemented at
levels of 60,000 tables and 5,000,000,000 rows.
International error reporting usable in many different countries.

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

Build Bright University

Chapter 2:

Faculty of Information and Technology

Data type and Variable

Overview of PHP Structure and Syntax


PHP programs are written using a text editor, such as Notepad or WordPad, just like
HTML pages. However, PHP pages, for the most part, end in a .php extension. This extension
signifies to the server that it needs to parse the PHP code before sending the resulting HTML
code to the viewers Web browser.
How PHP Fits with HTML
We assume that you know some HTML before you embark on your
PHP/Apache/MySQL journey, and youve undoubtedly seen how JavaScript code and other
languages can be interspersed within the HTML code in an HTML page. What makes PHP so
different is that it not only allows HTML pages to be created on the fly; it is invisible to your
Web site visitors. The only thing they see when they view the source of your code is the
resulting HTML output. This gives you more security for your PHP code and more flexibility
in writing it.
HTML can also be written inside the PHP section of your page; this allows you to format text
while keeping blocks of code together. This will also help you write organized, efficient code,
and the browser (and, more important, the viewer) wont know the difference.
PHP can also be written as a standalone program, with no HTML at all. This is helpful for
storing your connection variables, redirecting your visitors to another page of your site, or
performing other functions that we discuss in this book.

What is a PHP File?


 PHP files can contain text, HTML tags and scripts
 PHP files are returned to the browser as plain HTML
 PHP files have a file extension of ".php", ".php3", or ".phtml"
How to write php code
One of the benefits of using PHP is that it is relatively simple and straightforward. As with any
computer language, there is usually more than one way to perform the same function. Once
you feel comfortable writing some PHP programs, you can research shortcuts to make yourself
and your code more efficient. For the sake of simplicity, we cover only the most common uses,
rules, and functions of PHP.

page: 9

Build Bright University

Faculty of Information and Technology

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 lines end with a semicolon, generally speaking:


<?php
// First line of code goes here;
// Second line of code goes here;
// Third line of code goes here;
?>

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 */.

PHP Constants and Variables


Overview of constants
A constant is a placeholder for a value that you reference within your code. Constants are
typically named with capital letters (so you can easily find them within your code), and the
values are usually formally defined before using them. Constant names must begin with a letter
or underscore and cannot begin with a number. Names are also case-sensitive.
The values assigned to constants are defined with the PHP function define(). Once theyve
been defined, they cant be changed or undefined.
Syntax:
define(ConstantsName,Constans value);

page: 10

Build Bright University

Faculty of Information and Technology

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

Build Bright University

Faculty of Information and Technology

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:

The Concatenation Operator


There is only one string operator in PHP. The concatenation operator (.) is used to put two
string values together.
Ex:
<?
$str1=Good morning !;
$str2=how are you?;
echo $str1. .$str2; //

Good morning !how are you?

?>

page: 12

Build Bright University

Faculty of Information and Technology

The PHP Operators


Operators are symbols that you can use to manipulate values and variables by performing an
operation on them.
 Arithmetic Operators
Arithmetic operators are straightforward; they are just the normal mathematical operators.
PHPs arithmetic operators are shown in table below:
Operator
+
*
/

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

Build Bright University

Faculty of Information and Technology

 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:

condition ? value if true : value if false

Ex:cond_operator.php
<?php
$score=49;
echo $score>50?"Pass":"False";
?>

page: 14

Build Bright University

Chapter 3:

Faculty of Information and Technology

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

Build Bright University

Faculty of Information and Technology

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

Build Bright University

Faculty of Information and Technology

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

Build Bright University

Faculty of Information and Technology

switch.php (continues)
case 6:
echo "Number $x = Satureday";
break;
default:
echo "Number $x = Sunday";
}
?>
</body>
</html>

page: 18

Build Bright University

Chapter 4:

Faculty of Information and Technology

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

The while Statement


The simplest kind of loop in PHP is the while loop. Like an if statement, it relies on a
condition. The difference between a while loop and an if statement is that an if statement
executes the following block of code once if the condition is true. A while loop executes the
block repeatedly for as long as the condition is true.
You generally use a while loop when you dont know how many iterations will be required to
make the condition true. If you require a fixed number of iterations, consider using a for loop.

Syntax:
while (condition){
code to be executed;
}

page: 19

Build Bright University

Faculty of Information and Technology

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

Build Bright University

Faculty of Information and Technology

 Create table with while loop:


create_table_while.php
<html>
<body>
<table border="1" cellpadding="0" cellspacing="0" width="400"
align="center">
<tr bgcolor="#29b1ff">
<th align="center">Distance</th>
<th align="center">Cost</th>
</tr>
<?php
$distance = 50;
while ($distance <= 250 )
{
echo "<tr>\n <td align = 'center'>$distance</td>\n";
echo " <td align = 'center'>".$distance/10"</td>\n</tr>\n";
$distance += 50;
}
?>
</table>
</body>
</html>

Result:

page: 21

Build Bright University

Faculty of Information and Technology

The do while statement


A do..while loop differs from a while loop because the condition is tested at the end. This
means that in a do..while loop, the statement or block within the loop is always executed at
least once.
Even if you consider this example in which the condition will be false at the start and can
never become true, the loop will be executed once before checking the condition and ending
Syntax:

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

Build Bright University

Faculty of Information and Technology

Result:

The for statement


The for statement is the most advanced of the loops in PHP.
In it's simplest form, the for statement is used when you know how many times you want to
execute a statement or a list of statements.
Syntax:

for(init; cond; incr){


code to be execute;
}

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

Build Bright University

Faculty of Information and Technology

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

Build Bright University

Faculty of Information and Technology

Result:

The foreach statement


The foreach statement is used to loop through arrays.

Syntax:

foreach ($array as $value)


{
code to be executed;
}

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

Build Bright University

Faculty of Information and Technology

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

Build Bright University

Chapter 5:

Faculty of Information and Technology

PHP Array Objects

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

Build Bright University

Faculty of Information and Technology

Ex: num_array.php (first method to create array)


<html>
<head>
<title>
The Array Objects
</title>
</head>
<body>
<h3>Using Numerically array</h3>
<hr>
<?php
$numbers[0] = "one";
$numbers[1] = "two";
$numbers[2] = "three";
$numbers[3] = "four";
$numbers[4] = "five";
foreach( $numbers as $value )
{
echo "array content: <b>$value</b> <br />";
}
?>
</body>
</html>
Result:

page: 28

Build Bright University

Faculty of Information and Technology

Ex: num_array1.php (second method to create array)


<html>
<head>
<title>
The Array Objects
</title>
</head>
<body>
<h3>Using Numerically array</h3>
<hr>
<?php
$numbers = array("one","two","three","four","five");
foreach( $numbers as $value )
{
echo "array content: <b>$value</b> <br />";
}
?>
</body>
</html>

Result:

page: 29

Build Bright University

Faculty of Information and Technology

Accessing Array Contents


To access the contents of a variable, you use its name. If the variable is an array, you access the
contents using the variable name and an index. The index indicates which of the values in the
array you access. The index is placed in square brackets after the name.
Ex:
$numbers = array("one","two","three","four","five");
echo $numbers[2];// three
Using Loops to Access the Array Contents
Because the array is indexed by a sequence of numbers, you can use a for loop to more easily
display its contents:
Ex:
$numbers = array("one","two","three","four","five");
for($i=0;$i<5;$i++)
{
echo $numbers[$i];
}

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

Build Bright University

Faculty of Information and Technology

<?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

Build Bright University

Faculty of Information and Technology

Result:

Using Loops to Access the Array Contents


Because the indices in an array are not numbers, you cannot use a simple counter in a for loop
to work with the array. However, you can use the foreach loop or the list( )
and each( ) constructs.
 The foreach loop
The foreach loop has a slightly different structure when using associative arrays. You can
use it exactly as you did in the previous example, or you can incorporate the keys as well:
Ex: foreach_ass.php
<html>
<body>
<h3>Using foreach to access associative array contents</h3>
<hr color="darkblue" size="1">
<?php
$salaries = array("sophal" => "500 $","sreyleak" => "300 $",
"narry" => "100 $");
foreach ($salaries as $key => $value)
echo $key.' is salary: '.$value.'<br />';
?>
</body></html>

page: 32

Build Bright University

Faculty of Information and Technology

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

Build Bright University

Faculty of Information and Technology

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:

$salaries = array("sophal" => "500 $","sreyleak" => "300 $",


"narry" => "100 $");
while( list( $employee, $value )= each($salaries))
{
echo $employee - $value <br />;
}

page: 34

Build Bright University

Faculty of Information and Technology

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

Build Bright University

Faculty of Information and Technology

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"

=> array("physics" => 35,


"maths" => 30,
"chemistry" => 39),
"sreyleak" => array("physics" => 30,
"maths" => 32,
"chemistry" => 29),
"theara"
=> array("physics" => 31,
"maths" => 22,
"chemistry" => 39)
);

/* Accessing multi-dimensional array values */


echo
echo
echo
echo
echo
echo

"Markes for Sophal in physics : " ;


$markes['sophal']['physics'] . "<br />";
"Markes for SreyLeak in maths : ";
$markes['sreyleak']['maths'] . "<br />";
"Markes for Mr.Theara in chamistry : " ;
$markes['theara']['chemistry'] . "<br />";

?>
</body>
</html>

page: 36

Build Bright University

Faculty of Information and Technology

Result:

List of Array Functions


PHP: indicates the earliest version of PHP that supports the function.
Function

Description

array( )

Create an array

array_change_key_case( ) Returns an array with all keys in lowercase or uppercase


array_chunk( )

Splits an array into chunks of arrays

array_combine( )

Creates an array by using one array for keys and another for its
values

array_count_values( )

Returns an array with the number of occurrences for each value

array_diff( )

Compares array values, and returns the differences

array_diff_assoc( )

Compares array keys and values, and returns the differences

array_diff_key( )

Compares array keys, and returns the differences

array_diff_uassoc( )

Compares array keys and values, with an additional user-made


function check, and returns the differences

array_diff_ukey( )

Compares array keys, with an additional user-made function


check, and returns the differences

array_fill( )

Fills an array with values

array_fill_keys( )

Fill an array with values, specifying keys

array_filter( )

Filters elements of an array using a user-made function

array_flip( )

Exchanges all keys with their associated values in an array

page: 37

Build Bright University

Faculty of Information and Technology

array_intersect( )

Compares array values, and returns the matches

array_intersect_assoc( )

Compares array keys and values, and returns the matches

array_intersect_key( )

Compares array keys, and returns the matches

array_intersect_uassoc( )

Compares array keys and values, with an additional user-made


function check, and returns the matches

array_intersect_ukey( )

Compares array keys, with an additional user-made function


check, and returns the matches

array_key_exists( )

Checks if the specified key exists in the array

array_keys( )

Returns all the keys of an array

array_map( )

Sends each value of an array to a user-made function, which


returns new values

array_merge( )

Merges one or more arrays into one array

array_merge_recursive( )

Merges one or more arrays into one array

array_multisort( )

Sorts multiple or multi-dimensional arrays

array_pad( )

Inserts a specified number of items, with a specified value, to an


array

array_pop( )

Deletes the last element of an array

array_product( )

Calculates the product of the values in an array

array_push( )

Inserts one or more elements to the end of an array

array_rand( )

Returns one or more random keys from an array

array_reduce( )

Returns an array as a string, using a user-defined function

array_reverse( )

Returns an array in the reverse order

array_search( )

Searches an array for a given value and returns the key

array_shift( )

Removes the first element from an array, and returns the value of
the removed element

array_slice( )

Returns selected parts of an array

array_splice( )

Removes and replaces specified elements of an array

array_sum( )

Returns the sum of the values in an array

array_udiff( )

Compares array values in a user-made function and returns an


array

array_udiff_assoc( )

Compares array keys, and compares array values in a user-made


function, and returns an array

array_udiff_uassoc( )

Compares array keys and array values in user-made functions,


and returns an array

page: 38

Build Bright University

Faculty of Information and Technology

array_uintersect( )

Compares array values in a user-made function and returns an


array

array_uintersect_assoc( )

Compares array keys, and compares array values in a user-made


function, and returns an array

array_uintersect_uassoc( ) Compares array keys and array values in user-made functions,


and returns an array
array_unique( )

Removes duplicate values from an array

array_unshift( )

Adds one or more elements to the beginning of an array

array_values( )

Returns all the values of an array

array_walk( )

Applies a user function to every member of an array

array_walk_recursive( )

Applies a user function recursively to every member of an array

arsort( )

Sorts an array in reverse order and maintain index association

asort( )

Sorts an array and maintain index association

compact( )

Create array containing variables and their values

count( )

Counts elements in an array, or properties in an object

current( )

Returns the current element in an array

each( )

Returns the current key and value pair from an array

end( )

Sets the internal pointer of an array to its last element

extract( )

Imports variables into the current symbol table from an array

in_array( )

Checks if a specified value exists in an array

key( )

Fetches a key from an array

krsort( )

Sorts an array by key in reverse order

ksort( )

Sorts an array by key

list( )

Assigns variables as if they were an array

natcasesort( )

Sorts an array using a case insensitive "natural order" algorithm

natsort( )

Sorts an array using a "natural order" algorithm

next( )

Advance the internal array pointer of an array

pos( )

Alias of current()

prev( )

Rewinds the internal array pointer

range( )

Creates an array containing a range of elements

reset( )

Sets the internal pointer of an array to its first element

rsort( )

Sorts an array in reverse order

page: 39

Build Bright University

Faculty of Information and Technology

shuffle( )

Shuffles an array

sizeof( )

Alias of count( )

sort( )

Sorts an array

uasort( )

Sorts an array with a user-defined function and maintain index


association

uksort( )

Sorts an array by keys using a user-defined function

usort( )

Sorts an array by values using a user-defined function

page: 40

Build Bright University

Chapter 6:

Faculty of Information and Technology

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

Build Bright University

Faculty of Information and Technology

Ex: show_msg.php
<html>
<head>
<title>.::Hypertext Proprocessor Function.</title>
<?
function showmsg(){
echo "Something really cool with Php.";
}
?>
</head>
<body>
<?
showmsg();
?>
</body>
</html>

Naming Your Function:


The most important point to consider when naming your functions is that the name should be
short but descriptive.
A few restrictions follow:




Your function cannot have the same name as an existing function.


Your function name can contain only letters, digits, and underscores.
Your function name cannot begin with a digit.

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

Build Bright University

Faculty of Information and Technology

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>";
}

If you call the create_table( ) function


$my_array = array('Line one.','Line two.','Line three.');
create_table($my_array);

page: 43

Build Bright University

Faculty of Information and Technology

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

Build Bright University

Faculty of Information and Technology

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

Build Bright University

Faculty of Information and Technology

Returning from Functions


The keyword return stops the execution of a function. When a function ends because either all
statements have been executed or the keyword return is used, execution return is to the
statement after the function call.
Ex:test_return.php
<?php
function test_return()
{
echo "This statement will be executed";
return;
echo "This statement will never be executed";
}
?>
<html>
<body>
<h3>Returning from function</h3>
<hr color="darkblue" size=1>
<?php
test_return();
?>
</body>
</html>

Result:

page: 46

Build Bright University

Faculty of Information and Technology

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

Build Bright University

Faculty of Information and Technology

Result:

Returning Values from Functions


Exiting from a function is not the only reason to use return. Many functions use return
statements to communicate with the code that called them. Instead of echoing the result of the
comparison in the larger() function, the function might have been more useful if it returned the
answer. This way, the code that called the function can choose if and how to display or use it.
The equivalent built-in function max() behaves in this way.
Ex: You can write the larger() function as follows: (larger1.php)
<?php
function larger ($x, $y)
{
if (!isset($x)||!isset($y))
return false;
else if ($x>=$y)
return $x;
else
return $y;
}
?>
<html>
<body>
<h3>Returning value from function</h3>
<hr color="darkblue" size=1>
<?php
$a = 1; $b = 2.5; $c = 1.9;
echo larger($a, $b)."<br />";
echo larger($c, $a)."<br />";
echo larger($d, $a)."<br />";
?>
</body>
</html>

page: 48

Build Bright University

Faculty of Information and Technology

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

Build Bright University

Chapter 7:

Faculty of Information and Technology

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


The GET method sends the encoded user information appended to the page request. The page
and the encoded information are separated by the ? character.
http://www.test.com/index.htm?name1=value1&name2=value2

 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

Build Bright University

Faculty of Information and Technology

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

Build Bright University

Faculty of Information and Technology

Result:

After submit:

 There are a few disadvantages to passing variables through a URL:






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

Build Bright University

Faculty of Information and Technology

The POST method


The POST method transfers information via HTTP headers. The information is encoded as
described in case of GET method and put into a header called QUERY_STRING.
 The POST method does not have any restriction on data size to be sent.
 The POST method can be used to send ASCII as well as binary data.
 The data sent by POST method goes through HTTP header so security depends on HTTP protocol.
By using Secure HTTP you can make sure that your information is secure.

 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

Build Bright University

Faculty of Information and Technology

Result:

After submit:

page: 54

Build Bright University

Faculty of Information and Technology

The $_REQUEST variable


The PHP $_REQUEST variable contains the contents of both $_GET, $_POST, and
$_COOKIE. We will discuss $_COOKIE variable when we will explain about cookies.
The PHP $_REQUEST variable can be used to get the result from form data sent with
both the GET and POST methods.
Ex: request_variable.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: 55

Build Bright University

Faculty of Information and Technology

Result:

After submit:

page: 56

Build Bright University

Faculty of Information and Technology

Using Array as form elements values


You can get value from form elements by using array to store the values.
Ex: array_with_form.php
<html>
<head>
<title>Using Array as Form Value.</title>
</head>
<body>
<form method="post" action="array_with_form.php">
Select the programming languages you can use<br>
<input name="language[]" type="checkbox" value="C++">C++ <br>
<input name="language[]" type="checkbox" value="Java">Java<br>
<input name="language[]" type="checkbox" value="PHP">PHP <br>
<input name="language[]" type="checkbox" value="ASP">ASP <br>
<input name="language[]" type="checkbox" value="Delphi">
Delphi<br>
<input name="send" type="submit" id="send" value="Submit>
</form>
<?php
if(isset($_POST['language']))
{
$language = $_POST['language'];
$n
= count($language);
$i
= 0;
echo "The languages you selected are" .
"<ol>";
while ($i < $n)
{
echo "<li>{$language[$i]}</li>";
$i++;
}
echo "</ol>";
}
?>
</body>
</html>

page: 57

Build Bright University

Faculty of Information and Technology

Result:

After submit:

page: 58

Build Bright University

Chapter 8:

Faculty of Information and Technology

PHP Date Function

The PHP date() function is used to format a time and/or date.

The PHP Date( ) Function


The PHP date() function formats a timestamp to a more readable date and time.
A timestamp is a sequence of characters, denoting the date and/or time at which a certain event
occurred.
Syntax:

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

Build Bright University

Faculty of Information and Technology

Date( ) - Format the Date


The required format parameter in the date() function specifies how to format the date/time.
The following characters are recognized in the format parameter string:

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

Build Bright University


a
A
B
g
G
h
H
i
s

Faculty of Information and Technology

Lowercase Ante meridiem and Post meridiem


Uppercase Ante meridiem and Post meridiem
Swatch Internet time
12-hour format of an hour without leading zeros
24-hour format of an hour without leading zeros
12-hour format of an hour with leading zeros
24-hour format of an hour with leading zeros
Minutes with leading zeros
Seconds, with leading zeros

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

Build Bright University

Chapter 9:

Faculty of Information and Technology

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:

Fields are the different categories within a Table.


Tables usually contain multiple fields.

Datatypes:

Datatypes are the properties of each field.


A field only has 1 datatype.
There are three main types: text, numbers, and Dates/Times.

Field
Data type

Value

TEXT TYPES
CHAR( )
VARCHAR( )
TINYTEXT
TEXT
BLOB
MEDIUMTEXT
MEDIUMBLOB
LONGTEXT
LONGBLOB

A fixed section from 0 to 255 characters long.


A variable section from 0 to 255 characters long.
A string with a maximum length of 255 characters.
A string with a maximum length of 65535 characters.
A string with a maximum length of 65535 characters.
A string with a maximum length of 16777215 characters.
A string with a maximum length of 16777215 characters.
A string with a maximum length of 4294967295 characters.
A string with a maximum length of 4294967295 characters.

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

Build Bright University

Faculty of Information and Technology

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( , )

-128 to 127 normal


0 to 255 UNSIGNED.
-32768 to 32767 normal
0 to 65535 UNSIGNED.
-8388608 to 8388607 normal
0 to 16777215 UNSIGNED.
-2147483648 to 2147483647 normal
0 to 4294967295 UNSIGNED.
-9223372036854775808 to 9223372036854775807 normal
0 to 18446744073709551615 UNSIGNED.
A small number with a floating decimal point.
A large number with a floating decimal point.
A DOUBLE stored as a string , allowing for a fixed decimal point.

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

Build Bright University

Faculty of Information and Technology

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.

3. Working with SQL Command


3.1 How to create database on MYSQL server
CREATE DATABASE [database-name];
Ex: create database managestudent;
3.2 How to show database
SHOW DATABASES;
3.3 How to change database
USE [database-name];
3.4 How to delete database
DROP database-name;
Ex: DROP tblstudents;
3.4 How to create table
CREATE TABLE table-name (field1 datatype, field2 datatype,);
Ex: CREATE TABLE students(
id int( 6 ) NOT NULL auto_increment,
name text,
sex char( 6 ) ,
dob date,
);

page: 64

Build Bright University

Faculty of Information and Technology

3.5 How to delete table


DROP TABLE [table-name];
Ex: DROP TABLE tblstudent;
3.6 How to rename table
RENAME TABLE [old-table-name] TO [new-table-name];
or ALTER TABLE [old-table-name] RENAME TO [new-table-name];
3.7 How to show table on database
SHOW TABLES;
3.8 How to view table structure
EXPLAIN [table-name]; or DESCRIBE [table-name];
Ex: EXPLAIN tblstudents;
3.9 How to modify table structure
a) Add new field
ALTER TABLE [table-name] ADD COLUMN [new-field-name] datatype;
Ex: ALTER TABLE tblscore ADD COLUMN maxscore int(2);
b) Delete column of table
ALTER TABLE [table-name] DROP [field-name];
c) Change column name
ALTER TABLE [table-name] CHANGE [old-column] [new-column] datatype;
d) Modify column on table
ALTER TABLE [table-name] MODIFY [column-name] datatype;
4. Working with SQL statements
a) Insert statement
INSERT INTO [table-name] (field1, field2,..) VALUES (value1,value2,..);
INSERT INTO [table-name] (field1, field2,..) SELECT (field1,field2,.);
ex: INSERT INTO tblstudents(id,name,sex,dob) VALUES(001,dara,male,1984-12-20);
INSERT INTO tblstudents(id,name,sex,dob)
VALUES(002,vantha,male,1984-12-20), (003,raksa,female,
1984- 12-20);

page: 65

Build Bright University

Faculty of Information and Technology

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

Build Bright University

Chapter 10:

Faculty of Information and Technology

PHP MySQL Database Connection

1. How to connect to php with mysql database server?


Before you can access data in a database, you must create a connection to the database.
In PHP, this is done with the mysql_connect() function.
Syntax:
mysql_connect(servername,username,password);
Parameters:
 servername: is the name if IP address of server that contain Mysql server.
 username: is the username of Mysql server.
 password: is the password to log in.
Ex:connect.php
<?php
$conn=mysql_connect("localhost","root","bbu");
if (!$conn){
die("Could not connect: " . mysql_error());
}
?>

a) How to close connection


mysql_close($connection);
Ex:close_connect.php
<?php
$conn=mysql_connect("localhost","root","bbu");
if (!$conn){
die("Could not connect: " . mysql_error());
}
// some code to retrieve data from database.
mysql_close($conn);
?>

page: 67

Build Bright University

Faculty of Information and Technology

b) How to select database


mysql_select_db();
Ex: select_database.php
<?php
$conn=mysql_connect("localhost","root","bbu") or
die("Connection Error ".mysql_error());
$db=mysql_select_db("test") or die("Could not select
database".mysql_error());
if($db)
echo "Database selected";
else
echo "Select database fail";
?>

c) How to manipulate data from php with mysql


mysql_query(sql statement);

This function is used to execute SQL command


 How to insert data into Mysql
When data is put into a MySQL table it is referred to as inserting data. When inserting data
it is important to remember the exact names and types of the table's columns.

Ex: insertdata.php
tblstudents
Field Name
id
name
sex
dob

Data type
int(3)
varchar(50)
varchar(7)
date

page: 68

Build Bright University

Faculty of Information and Technology

<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>

 How select data from Mysql


There are two functions to select data from Mysql table.
Syntax:
-

mysql_fetch_row(query string);
mysql_fetch_array(query string);

page: 69

Build Bright University

Faculty of Information and Technology

Ex: select a record from database.


<?php
//create connection
$conn=mysql_connect("localhost","root","bbu")
or die("Connection Error ".mysql_error());
//select database
$db=mysql_select_db("test")
or die("Could not select database".mysql_error());
//create query string
$sql=mysql_query("SELECT * FROM tbltest where
name=dara")
or die(mysql_error());
//fetch data
$row=mysql_fetch_array($sql);
echo $row["name"]." ".$row["score"];
//close connection
mysql_close();
?>
Ex: select all records from database.
<?php
//create connection
$conn=mysql_connect("localhost","root","bbu") or
die("Connection Error ".mysql_error());
echo("Connection Successful.<br>");
//select database
$db=mysql_select_db("test") or die("Could not select
database".mysql_error());
echo("Database selected.<br>");
//create query string
$sql=mysql_query("SELECT * FROM tbltest") or
die(mysql_error());
//fetch data
while($row=mysql_fetch_row($sql)){
echo $row[0]." ".$row[1];
echo "<br>";
}
//close connection
mysql_close();
?>

page: 70

Build Bright University

Chapter 11:

Faculty of Information and Technology

PHP cookies and sessions

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

Build Bright University

Faculty of Information and Technology

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).

How to Retrieve a Cookie Value?


The PHP $_COOKIE variable is used to retrieve a cookie value.
In the example below, we retrieve the value of the cookie named "user" and display it on a
page:
read_cookie.php
<?php
// Print a cookie
echo $_COOKIE["user"];
// A way to view all cookies
print_r($_COOKIE);
?>

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

Build Bright University

Faculty of Information and Technology

How to Delete a Cookie?


When deleting a cookie you should assure that the expiration date is in the past.
Ex: delete_cookie.php
<?php
// set the expiration date to one hour ago
setcookie("user", "", time()-3600);
?>
</body>
</html>

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.

PHP Session Variables


When you are working with an application, you open it, do some changes and then you close it.
This is much like a Session. The computer knows who you are. It knows when you start the
application and when you end. But on the internet there is one problem: the web server does
not know who you are and what you do because the HTTP address doesn't maintain state.
A PHP session solves this problem by allowing you to store user information on the server for
later use (i.e. username, shopping items, etc). However, session information is temporary and
will be deleted after the user has left the website. If you need a permanent storage you may
want to store the data in a database.
Sessions work by creating a unique id (UID) for each visitor and store variables based on this
UID. The UID is either stored in a cookie or is propagated in the URL.

Starting a PHP Session


Before you can store user information in your PHP session, you must first start up the session.
Note: The session_start() function must appear BEFORE the <html> tag:

page: 73

Build Bright University

Faculty of Information and Technology

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.

Storing a Session Variable


The correct way to store and retrieve session variables is to use the PHP $_SESSION variable:
Ex1: set-read-session.php
<?php
session_start();
// store session data
$_SESSION['views']=1;
?>
<html>
<body>
<?php
//retrieve session data
echo "Pageviews=". $_SESSION['views'];
?>
</body>
</html>
In the example below, we create a simple page-views counter. The isset() function checks if the
"views" variable has already been set. If "views" has been set, we can increment our counter. If
"views" doesn't exist, we create a "views" variable, and set it to 1:

page: 74

Build Bright University

Faculty of Information and Technology

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

Build Bright University

Chapter 12:

Faculty of Information and Technology

PHP Include and Require

Server Side Includes (SSI)


You can insert the content of one PHP file into another PHP file before the server executes it,
with the include() or require() function.
The two functions are identical in every way, except how they handle errors:



include() generates a warning, but the script will continue execution


require() generates a fatal error, and the script will stop

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).

PHP include() Function


The include() function takes all the content in a specified file and includes it in the
current file. If an error occurs, the include() function generates a warning, but the script will
continue execution.
Ex: Assume that you have a standard header file, called "header.php". To include the header
file in a page, use the include() function:

<html>
<body>
<?php include("header.php"); ?>
<h1>Welcome to my home page!</h1>
<p>Some text.</p>
</body>
</html>

page: 76

Build Bright University

Faculty of Information and Technology

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>

PHP require() Function


The require() function is identical to include(), except that it handles errors differently.
If an error occurs, the include() function generates a warning, but the script will continue
execution. The require() generates a fatal error, and the script will stop.
Error Example include() Function
<html>
<body>
<?php
include("wrongFile.php");
echo "Hello World!";
?>
</body>
</html>

page: 77

Build Bright University

Faculty of Information and Technology

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.

Error Example require() Function


Now, let's run the same example with the require() function.
<html>
<body>
<?php
require("wrongFile.php");
echo "Hello World!";
?>
</body>
</html>
Error message:
Warning: require(wrongFile.php) [function.require]:
failed to open stream:
No such file or directory in C:\home\website\test.php on line 5
Fatal error: require() [function.require]:
Failed opening required 'wrongFile.php'
(include_path='.;C:\php5\pear')
in C:\home\website\test.php on line 5
The echo statement is not executed, because the script execution stopped after the fatal error.
It is recommended to use the require() function instead of include(), because scripts should not
continue after an error.

page: 78

Build Bright University

Faculty of Information and Technology

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

You might also like