0% found this document useful (0 votes)
17 views

PHP NOtes

The document provides an overview of PHP including what it is, how PHP files work, common PHP functions and syntax. It discusses PHP variables, scopes, and how to declare global and static variables. Key topics covered include PHP tags, comments, data types, operators, and conditional and loop statements.

Uploaded by

khan5568843
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

PHP NOtes

The document provides an overview of PHP including what it is, how PHP files work, common PHP functions and syntax. It discusses PHP variables, scopes, and how to declare global and static variables. Key topics covered include PHP tags, comments, data types, operators, and conditional and loop statements.

Uploaded by

khan5568843
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 55

Web Programming

PHP
 PHP is an acronym for "PHP Hypertext Preprocessor"
 PHP is a widely-used, open source scripting language
 PHP scripts are executed on the server
 PHP is a powerful tool for making dynamic and interactive Web pages quickly.
 PHP costs nothing, it is free to download and use

What is a PHP File?


 PHP files can contain text, HTML, CSS, JavaScript, and PHP code
 PHP code are executed on the server, and the result is returned to the browser as plain HTML
 PHP files have extension ".php"

What Can PHP Do?


 PHP can generate dynamic page content
 PHP can create, open, read, write, and close files on the server
 PHP can collect form data
 PHP can send and receive cookies
 PHP can add, delete, modify data in your database
 PHP can restrict users to access some pages on your website
 PHP can encrypt data

Why PHP?
 PHP runs on various platforms (Windows, Linux, Unix, Mac OS X, etc.)
 PHP is compatible with almost all servers used today (Apache, IIS, etc.)
 PHP supports a wide range of databases
 PHP is easy to learn and runs efficiently on the server side

Basic PHP Syntax


A PHP script can be placed anywhere in the document.
A PHP script starts with <?php and ends with ?>:

Example-------------------------------------------------------------------------------------------------------------------------------
<?php
// PHP code goes here
?>
------------------------------------------------------------------------------------------------------------------------------------------
The default file extension for PHP files is ".php".
A PHP file normally contains HTML tags, and some PHP scripting code.
Below, we have an example of a simple PHP file, with a PHP script that uses a built-in PHP function
"echo" to output the text "Hello World!" on a web page:
Khurasan University Page 1 of 55
Web Programming

Example-------------------------------------------------------------------------------------------------------------------------------
<html>
<body>
<h1>My first PHP page</h1>
<?php
echo "Hello World!";
?>
</body>
</html>
------------------------------------------------------------------------------------------------------------------------------------------
Note: PHP statements are terminated by semicolon (;).

Comments in PHP
A comment in PHP code is a line that is not read/executed as part of the program. Comments are useful
for:
 To let others understand what you are doing
 To remind yourself what you did.
PHP supports three ways of commenting:

Example-------------------------------------------------------------------------------------------------------------------------------
<html>
<body>
<?php
// This is a single line comment
# This is also a single line comment
/*
This is a multiple lines comment block
that spans over more than
one line
*/
?>
</body>
</html>
------------------------------------------------------------------------------------------------------------------------------------------

PHP Case Sensitivity


In PHP, all user-defined functions, classes, and keywords (e.g. if, else, while, echo, etc.) are case-
insensitive. In the example below, all three echo statements below are legal (and equal):

Khurasan University Page 2 of 55


Web Programming

Example-------------------------------------------------------------------------------------------------------------------------------
<html>
<body>
<?php
ECHO "Hello World!<br>";
echo "Hello World!<br>";
EcHo "Hello World!<br>";
?>
</body>
</html>
------------------------------------------------------------------------------------------------------------------------------------------
However; in PHP, all variables are case-sensitive.
In the example below, only the first statement will display the value of the $color variable (this is
because $color, $COLOR, and $coLOR are treated as three different variables):

Example-------------------------------------------------------------------------------------------------------------------------------
<html>
<body>
<?php
$color="red";
echo "My car is " . $color . "<br>";
echo "My house is " . $COLOR . "<br>";
echo "My boat is " . $coLOR . "<br>";
?>
</body>
</html>
------------------------------------------------------------------------------------------------------------------------------------------

PHP Variables
Variables are "containers" for storing information. As with algebra, PHP variables can be used to hold
values (x=5) or expressions (z=x+y).
A variable can have a short name (like x and y) or a more descriptive name (age, carname,
total_volume).
Rules for PHP variables:
 A variable starts with the $ sign, followed by the name of the variable
 A variable name must start with a letter or the underscore character
 A variable name cannot start with a number
 A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
 Variable names are case sensitive ($y and $Y are two different variables)

Khurasan University Page 3 of 55


Web Programming

Creating (Declaring) PHP Variables


PHP has no command for declaring a variable.
A variable is created the moment you first assign a value to it:

Example-------------------------------------------------------------------------------------------------------------------------------
<?php
$txt="Hello world!";
$x=5;
$y=10.5;
?>
------------------------------------------------------------------------------------------------------------------------------------------
After the execution of the statements above, the variable txt will hold the value Hello world!, the
variable x will hold the value 5, and the variable y will hold the value 10.5.

PHP Variables Scope


In PHP, variables can be declared anywhere in the script.
The scope of a variable is the part of the script where the variable can be referenced/used.
PHP has three different variable scopes:
 local
 global
 static

Local and Global Scope


A variable declared outside a function has a GLOBAL SCOPE and can only be accessed outside a function.
A variable declared within a function has a LOCAL SCOPE and can only be accessed within that function.
The following example tests variables with local and global scope:

Example-------------------------------------------------------------------------------------------------------------------------------
<?php
$x=5; // global scope
function myTest()
{
$y=10; // local scope
echo "<p>Test variables inside the function:<p>";
echo "Variable x is: $x";
echo "<br>";
echo "Variable y is: $y";
}
myTest();
echo "<p>Test variables outside the function:<p>";
echo "Variable x is: $x";

Khurasan University Page 4 of 55


Web Programming

echo "<br>";
echo "Variable y is: $y";
?>
------------------------------------------------------------------------------------------------------------------------------------------
In the example above there are two variables $x and $y and a function myTest(). $x is a global variable
since it is declared outside the function and $y is a local variable since it is created inside the function.
When we output the values of the two variables inside the myTest() function, it prints the value of $y as
it is the locally declared, but cannot print the value of $x since it is created outside the function.
Then, when we output the values of the two variables outside the myTest() function, it prints the value
of $x, but cannot print the value of $y since it is a local variable and it is created inside the myTest()
function.

The global Keyword


The global keyword is used to access a global variable from within a function.
To do this, use the global keyword before the variables (inside the function):

Example-------------------------------------------------------------------------------------------------------------------------------
<?php
$x=5;
$y=10;
function myTest()
{
global $x,$y;
$y=$x+$y;
}
myTest();
echo $y; // outputs 15
?>
------------------------------------------------------------------------------------------------------------------------------------------
PHP also stores all global variables in an array called $GLOBALS[index]. The index holds the name of the
variable. This array is also accessible from within functions and can be used to update global variables
directly.

The example above can be rewritten like this:


Example-------------------------------------------------------------------------------------------------------------------------------
<?php
$x=5;
$y=10;
function myTest()
{
$GLOBALS['y']=$GLOBALS['x']+$GLOBALS['y'];

Khurasan University Page 5 of 55


Web Programming

}
myTest();
echo $y; // outputs 15
?>
------------------------------------------------------------------------------------------------------------------------------------------

The static Keyword


Normally, when a function is completed/executed, all of its variables are deleted. However, sometimes
we want a local variable NOT to be deleted. We need it for a further job.
To do this, use the static keyword when you first declare the variable:

Example-------------------------------------------------------------------------------------------------------------------------------
<?php
function myTest()
{
static $x=0;
echo $x;
$x++;
}
myTest();
myTest();
myTest();
?>
------------------------------------------------------------------------------------------------------------------------------------------
Then, each time the function is called, that variable will still have the information it contained from the
last time the function was called.
Note: The variable is still local to the function.

PHP echo and print Statements


There are some difference between echo and print:
 echo - can output one or more strings
 print - can only output one string, and returns always 1

PHP Data Types


String, Integer, Floating point numbers, Boolean, Array, Object, NULL.

PHP Strings
A string is a sequence of characters, like "Hello world!".
A string can be any text inside quotes. You can use single or double quotes:

Khurasan University Page 6 of 55


Web Programming

Example-------------------------------------------------------------------------------------------------------------------------------
<?php
$x = "Hello world!";
echo $x;
echo "<br>";
$x = 'Hello world!';
echo $x;
?>
------------------------------------------------------------------------------------------------------------------------------------------

Some PHP String Functions

The PHP strlen() function


The strlen() function returns the length of a string, in characters.
The example below returns the length of the string "Hello world!":
Example-------------------------------------------------------------------------------------------------------------------------------
<?php
echo strlen("Hello world!");
?>
------------------------------------------------------------------------------------------------------------------------------------------
The output of the code above will be: 12

The PHP strpos() function


The strpos() function is used to search for a specified character or text within a string.
If a match is found, it will return the character position of the first match. If no match is found, it will
return FALSE.
The example below searches for the text "world" in the string "Hello world!":
Example-------------------------------------------------------------------------------------------------------------------------------
<?php
echo strpos("Hello world!","world");
?>
The output of the code above will be: 6.
------------------------------------------------------------------------------------------------------------------------------------------

PHP Integers
An integer is a number without decimals.
Rules for integers:
 An integer must have at least one digit (0-9)
 An integer cannot contain comma or blanks
 An integer must not have a decimal point
 An integer can be either positive or negative
Khurasan University Page 7 of 55
Web Programming

 Integers can be specified in three formats: decimal (10-based), hexadecimal (16-based - prefixed
with 0x) or octal (8-based - prefixed with 0)
In the following example we will test different numbers. The PHP var_dump() function returns the data
type and value of variables:

Example-------------------------------------------------------------------------------------------------------------------------------
<?php
$x = 5985;
var_dump($x);
echo "<br>";
$x = -345; // negative number
var_dump($x);
echo "<br>";
$x = 0x8C; // hexadecimal number
var_dump($x);
echo "<br>";
$x = 047; // octal number
var_dump($x);
?>
------------------------------------------------------------------------------------------------------------------------------------------

PHP Floating Point Numbers


A floating point number is a number with a decimal point or a number in exponential form.
In the following example we will test different numbers. The PHP var_dump() function returns the data
type and value of variables:
Example-------------------------------------------------------------------------------------------------------------------------------
<?php
$x = 10.365;
var_dump($x);
echo "<br>";
$x = 2.4e3;
var_dump($x);
echo "<br>";
$x = 8E-5;
var_dump($x);
?>
------------------------------------------------------------------------------------------------------------------------------------------

PHP Booleans
Booleans can be either TRUE or FALSE. Booleans are often used in conditional testing.
$x=true; $y=false;

Khurasan University Page 8 of 55


Web Programming

PHP NULL Value


The special NULL value represents that a variable has no value. NULL is the only possible value of data
type NULL.
The NULL value identifies whether a variable is empty or not. Also useful to differentiate between the
empty string and null values of databases.
Variables can be emptied by setting the value to NULL:
Example-------------------------------------------------------------------------------------------------------------------------------
<?php
$x="Hello world!";
$x=null;
var_dump($x);
?>
------------------------------------------------------------------------------------------------------------------------------------------

PHP Operators:

PHP Arithmetic Operators

The example below shows the different results of using the different arithmetic operators:

Example-------------------------------------------------------------------------------------------------------------------------------
<?php
$x=10;
$y=6;
echo ($x + $y); // outputs 16
echo ($x - $y); // outputs 4
echo ($x * $y); // outputs 60
echo ($x / $y); // outputs 1.6666666666667
echo ($x % $y); // outputs 4
?>
------------------------------------------------------------------------------------------------------------------------------------------

PHP Assignment Operators


The PHP assignment operators is used to write a value to a variable.

Khurasan University Page 9 of 55


Web Programming

The basic assignment operator in PHP is "=". It means that the left operand gets set to the value of the
assignment expression on the right.

The example below shows the different results of using the different assignment operators:

Example-------------------------------------------------------------------------------------------------------------------------------
<?php
$x=10;
echo $x; // outputs 10

$y=20;
$y += 100;
echo $y; // outputs 120

$z=50;
$z -= 25;
echo $z; // outputs 25

$i=5;
$i *= 6;
echo $i; // outputs 30

$j=10;
$j /= 5;
echo $j; // outputs 2

$k=15;
$k %= 4;
echo $k; // outputs 3
?>
------------------------------------------------------------------------------------------------------------------------------------------

PHP String Operators

Khurasan University Page 10 of 55


Web Programming

The example below shows the results of using the string operators:

Example-------------------------------------------------------------------------------------------------------------------------------
<?php
$a = "Hello";
$b = $a . " world!";
echo $b; // outputs Hello world!

$x="Hello";
$x .= " world!";
echo $x; // outputs Hello world!
?>
------------------------------------------------------------------------------------------------------------------------------------------

PHP Increment / Decrement Operators

The example below shows the different results of using the different increment/decrement operators:

Example-------------------------------------------------------------------------------------------------------------------------------
<?php
$x=10;
echo ++$x; // outputs 11

$y=10;
echo $y++; // outputs 10

$z=5;
echo --$z; // outputs 4

$i=5;
echo $i--; // outputs 5
?>
Khurasan University Page 11 of 55
Web Programming

------------------------------------------------------------------------------------------------------------------------------------------

PHP Comparison Operators


The PHP comparison operators are used to compare two values (number or string):

The example below shows the different results of using some of the comparison operators:

Example-------------------------------------------------------------------------------------------------------------------------------
<?php
$x=100;
$y="100";

var_dump($x == $y);
echo "<br>";
var_dump($x === $y);
echo "<br>";
var_dump($x != $y);
echo "<br>";
var_dump($x !== $y);
echo "<br>";

$a=50;
$b=90;

var_dump($a > $b);


echo "<br>";
var_dump($a < $b);
?>
------------------------------------------------------------------------------------------------------------------------------------------

Khurasan University Page 12 of 55


Web Programming

PHP Logical Operators

PHP Array Operators


The PHP array operators are used to compare arrays:

The example below shows the different results of using the different array operators:

Example-------------------------------------------------------------------------------------------------------------------------------
<?php
$x = array("a" => "red", "b" => "green");
$y = array("c" => "blue", "d" => "yellow");
$z = $x + $y; // union of $x and $y
var_dump($z);
var_dump($x == $y);
var_dump($x === $y);
var_dump($x != $y);
var_dump($x <> $y);
var_dump($x !== $y);
?>
------------------------------------------------------------------------------------------------------------------------------------------

Khurasan University Page 13 of 55


Web Programming

PHP Conditional Statements


Conditional statements are used to perform different actions based on different conditions.
In PHP we have the following conditional statements:
 if statement - executes some code only if a specified condition is true
 if...else statement - executes some code if a condition is true and another code if the condition
is false
 if...elseif....else statement - selects one of several blocks of code to be executed
 switch statement - selects one of many blocks of code to be executed

PHP - The if Statement


The if statement is used to execute some code only if a specified condition is true.
Syntax
if (condition)
{
code to be executed if condition is true;
}
The example below will output "Have a good day!" if the current time (HOUR) is less than 20:

Example-------------------------------------------------------------------------------------------------------------------------------
<?php
$t=date("H");
if ($t<"20")
{
echo "Have a good day!";
}
?>
------------------------------------------------------------------------------------------------------------------------------------------

PHP - The if...else Statement


Use the if....else statement to execute some code if a condition is true and another code if the
condition is false.
Syntax
if (condition)
{
code to be executed if condition is true;
}
else
{
code to be executed if condition is false;
}

Khurasan University Page 14 of 55


Web Programming

The example below will output "Have a good day!" if the current time is less than 20, and "Have a good
night!" otherwise:
Example-------------------------------------------------------------------------------------------------------------------------------
<?php
$t=date("H");
if ($t<"20")
{
echo "Have a good day!";
}
else
{
echo "Have a good night!";
}
?>
------------------------------------------------------------------------------------------------------------------------------------------

PHP - The if...elseif....else Statement


Use the if....elseif...else statement to select one of several blocks of code to be executed.
Syntax
if (condition)
{
code to be executed if condition is true;
}
elseif (condition)
{
code to be executed if condition is true;
}
else
{
code to be executed if condition is false;
}
The example below will output "Have a good morning!" if the current time is less than 10, and "Have a
good day!" if the current time is less than 20. Otherwise it will output "Have a good night!":

Example-------------------------------------------------------------------------------------------------------------------------------
<?php
$t=date("H");
if ($t<"10")
{
echo "Have a good morning!";
}

Khurasan University Page 15 of 55


Web Programming

elseif ($t<"20")
{
echo "Have a good day!";
}
else
{
echo "Have a good night!";
}
?>
------------------------------------------------------------------------------------------------------------------------------------------

The PHP switch Statement


The switch statement is used to perform different actions based on different conditions.
Use the switch statement to select one of many blocks of code to be executed.
Syntax
switch (n)
{
case label1:
code to be executed if n=label1;
break;
case label2:
code to be executed if n=label2;
break;
case label3:
code to be executed if n=label3;
break;
...
default:
code to be executed if n is different from all labels;
}
This is how it works: First we have a single expression n (most often a variable), that is evaluated once.
The value of the expression is then compared with the values for each case in the structure. If there is a
match, the block of code associated with that case is executed. Use break to prevent the code from
running into the next case automatically. The default statement is used if no match is found.

Example-------------------------------------------------------------------------------------------------------------------------------
<?php
$favcolor="red";
switch ($favcolor)
{
case "red":

Khurasan University Page 16 of 55


Web Programming

echo "Your favorite color is red!";


break;
case "blue":
echo "Your favorite color is blue!";
break;
case "green":
echo "Your favorite color is green!";
break;
default:
echo "Your favorite color is neither red, blue, or green!";
}
?>
------------------------------------------------------------------------------------------------------------------------------------------

PHP Loops
Often when you write code, you want the same block of code to run over and over again in a row.
Instead of adding several almost equal code-lines in a script, we can use loops to perform a task like this.
In PHP, we have the following looping statements:
 while - loops through a block of code as long as the specified condition is true
 do...while - loops through a block of code once, and then repeats the loop as long as the
specified 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 PHP while Loop


The while loop executes a block of code as long as the specified condition is true.
Syntax
while (condition is true)
{
code to be executed;
}
The example below first sets a variable $x to 1 ($x=1;). Then, the while loop will continue to run as long
as $x is less than, or equal to 5. $x will increase by 1 each time the loop runs ($x++;):

Example-------------------------------------------------------------------------------------------------------------------------------
<?php
$x=1;
while($x<=5)
{
echo "The number is: $x <br>";
$x++;

Khurasan University Page 17 of 55


Web Programming

}
?>
------------------------------------------------------------------------------------------------------------------------------------------

The PHP do...while Loop


The do...while loop will always execute the block of code once, it will then check the condition, and
repeat the loop while the specified condition is true.
Syntax
do
{
code to be executed;
}
while (condition is true);
The example below first sets a variable $x to 1 ($x=1;). Then, the do while loop will write some output,
and then increment the variable $x with 1. Then the condition is checked (is $x less than, or equal to 5?),
and the loop will continue to run as long as $x is less than, or equal to 5:

Example-------------------------------------------------------------------------------------------------------------------------------
<?php
$x=1;
do
{
echo "The number is: $x <br>";
$x++;
}
while ($x<=5)
?>
------------------------------------------------------------------------------------------------------------------------------------------
Notice that in a do while loop the condition is tested AFTER executing the statements within the loop.
This means that the do while loop would execute its statements at least once, even if the condition fails
the first time.

The example below sets the $x variable to 6, then it runs the loop, and then the condition is checked:
Example-------------------------------------------------------------------------------------------------------------------------------
<?php
$x=6;
do
{
echo "The number is: $x <br>";
$x++;

Khurasan University Page 18 of 55


Web Programming

}
while ($x<=5)
?>
------------------------------------------------------------------------------------------------------------------------------------------

The PHP for Loop


PHP for loops execute a block of code a specified number of times.
The for loop is used when you know in advance how many times the script should run.
Syntax
for (init counter; test counter; increment counter)
{
code to be executed;
}

Parameters:
 init counter: Initialize the loop counter value
 test counter: Evaluated for each loop iteration. If it evaluates to TRUE, the loop continues. If it
evaluates to FALSE, the loop ends.
 increment counter: Increases the loop counter value

The example below displays the numbers from 0 to 10:

Example-------------------------------------------------------------------------------------------------------------------------------
<?php
for ($x=0; $x<=10; $x++) {
echo "The number is: $x <br>";
} ?>
------------------------------------------------------------------------------------------------------------------------------------------

The PHP foreach Loop


The foreach loop works only on arrays, and is used to loop through each key/value pair in an array.
Syntax
foreach ($array as $value)
{
code to be executed;
}
For every loop iteration, the value of the current array element is assigned to $value and the array
pointer is moved by one, until it reaches the last array element.
The following example demonstrates a loop that will output the values of the given array ($colors):

Khurasan University Page 19 of 55


Web Programming

Example-------------------------------------------------------------------------------------------------------------------------------
<?php
$colors = array("red","green","blue","yellow");
foreach ($colors as $value){
echo "$value <br>";
} ?>
------------------------------------------------------------------------------------------------------------------------------------------

Khurasan University Page 20 of 55


Web Programming

PHP User Defined Functions


Besides the built-in PHP functions, we can create our own functions.
 A function is a block of statements that can be used repeatedly in a program.
 A function will not execute immediately when a page loads.
 A function will be executed by a call to the function.

Create a User Defined Function in PHP


A user defined function declaration starts with the word "function":
Syntax
function functionName()
{
code to be executed;
}
In the example below, we create a function named "writeMsg()". The opening curly brace ( { ) indicates
the beginning of the function code and the closing curly brace ( } ) indicates the end of the function. The
function outputs "Hello world!". To call the function, just write its name:

Example-------------------------------------------------------------------------------------------------------------------------------
<?php
function writeMsg()
{
echo "Hello world!";
}
writeMsg(); // call the function
?>
------------------------------------------------------------------------------------------------------------------------------------------

PHP Function Arguments


Information can be passed to functions through arguments. An argument is just like a variable.
Arguments are specified after the function name, inside the parentheses. You can add as many
arguments as you want, just seperate them with a comma.
The following example has a function with one argument ($fname). When the familyName() function is
called, we also pass along a name (e.g. Jani), and the name is used inside the function, which outputs
several different first names, but an equal last name:

Example-------------------------------------------------------------------------------------------------------------------------------
<?php
function familyName($fname)
{
echo "$fname Refsnes.<br>";
}
Khurasan University Page 21 of 55
Web Programming

familyName("Jani");
familyName("Hege");
familyName("Stale");
familyName("Kai Jim");
familyName("Borge");
?>
------------------------------------------------------------------------------------------------------------------------------------------

The following example has a function with two arguments ($fname and $year):
Example-------------------------------------------------------------------------------------------------------------------------------
<?php
function familyName($fname,$year)
{
echo "$fname Refsnes. Born in $year <br>";
}

familyName("Hege","1975");
familyName("Ståle","1978");
familyName("Kai Jim","1983");
?>
------------------------------------------------------------------------------------------------------------------------------------------

PHP Default Argument Value


The following example shows how to use a default parameter. If we call the function setHeight() without
arguments it takes the default value as argument:

Example-------------------------------------------------------------------------------------------------------------------------------
<?php
function setHeight($minheight=50)
{
echo "The height is : $minheight <br>";
}
setHeight(350);
setHeight(); // will use the default value of 50
setHeight(135);
setHeight(80);
?>
------------------------------------------------------------------------------------------------------------------------------------------

Khurasan University Page 22 of 55


Web Programming

PHP Functions - Returning values


To let a function return a value, use the return statement:

Example-------------------------------------------------------------------------------------------------------------------------------
<?php
function sum($x,$y)
{
$z=$x+$y;
return $z;
}

echo "5 + 10 = " . sum(5,10) . "<br>";


echo "7 + 13 = " . sum(7,13) . "<br>";
echo "2 + 4 = " . sum(2,4);
?>
------------------------------------------------------------------------------------------------------------------------------------------

PHP Arrays
An array stores multiple values in one single variable.
An array can hold many values under a single name, and you can access the values by referring to an
index number.

Create an Array in PHP


In PHP, the array() function is used to create an array:
In PHP, there are three types of arrays:
 Indexed arrays - Arrays with numeric index
 Associative arrays - Arrays with named keys
 Multidimensional arrays - Arrays containing one or more arrays

PHP Indexed Arrays


 There are two ways to create indexed arrays:
 The index can be assigned automatically (index always starts at 0):
 $cars=array("Volvo","BMW","Toyota");
 or the index can be assigned manually:
 $cars[0]="Volvo";
$cars[1]="BMW";
$cars[2]="Toyota";

The following example creates an indexed array named $cars, assigns three elements to it, and then
prints a text containing the array values:

Khurasan University Page 23 of 55


Web Programming

Example-------------------------------------------------------------------------------------------------------------------------------
<?php
$cars=array("Volvo","BMW","Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
?>
------------------------------------------------------------------------------------------------------------------------------------------

Get The Length of an Array - The count() Function


The count() function is used to return the length (the number of elements) of an array:

Example-------------------------------------------------------------------------------------------------------------------------------
<?php
$cars=array("Volvo","BMW","Toyota");
echo count($cars);
?>
------------------------------------------------------------------------------------------------------------------------------------------

Loop through an Indexed Array


To loop through and print all the values of an indexed array, you could use a for loop, like this:

Example-------------------------------------------------------------------------------------------------------------------------------
<?php
$cars=array("Volvo","BMW","Toyota");
$arrlength=count($cars);

for($x=0;$x<$arrlength;$x++)
{
echo $cars[$x];
echo "<br>";
}
?>

PHP Associative Arrays


Associative arrays are arrays that use named keys that you assign to them.
There are two ways to create an associative array:
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
or:
$age['Peter']="35";
$age['Ben']="37";
$age['Joe']="43";
The named keys can then be used in a script:

Khurasan University Page 24 of 55


Web Programming

Example-------------------------------------------------------------------------------------------------------------------------------
<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
echo "Peter is " . $age['Peter'] . " years old.";
?>
------------------------------------------------------------------------------------------------------------------------------------------

Loop through an Associative Array


To loop through and print all the values of an associative array, you could use a foreach loop, like this:

Example-------------------------------------------------------------------------------------------------------------------------------
<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");

foreach($age as $x=>$x_value)
{
echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";
}
?>
------------------------------------------------------------------------------------------------------------------------------------------

PHP - Sort Functions For Arrays


In this chapter, we will go through the following PHP array sort functions:
 sort() - sort arrays in ascending order
 rsort() - sort arrays in descending order
 asort() - sort associative arrays in ascending order, according to the value
 ksort() - sort associative arrays in ascending order, according to the key
 arsort() - sort associative arrays in descending order, according to the value
 krsort() - sort associative arrays in descending order, according to the key

Khurasan University Page 25 of 55


Web Programming

PHP Global Variables - Superglobals


Several predefined variables in PHP are "superglobals", which means that they are always accessible,
regardless of scope - and you can access them from any function, class or file without having to do
anything special.

The PHP superglobal variables are:


 $GLOBALS
 $_SERVER
 $_REQUEST
 $_POST
 $_GET
 $_FILES
 $_ENV
 $_COOKIE
 $_SESSION

Khurasan University Page 26 of 55


Web Programming

PHP MySQL Introduction


With PHP, you can connect to and manipulate databases.
MySQL is the most popular database system used with PHP.

What is MySQL?
 MySQL is a database system used on the web
 MySQL is a database system that runs on a server
 MySQL is ideal for both small and large applications
 MySQL is very fast, reliable, and easy to use
 MySQL supports standard SQL
 MySQL compiles on a number of platforms
 MySQL is free to download and use
 MySQL is developed, distributed, and supported by Oracle Corporation
 MySQL is named after co-founder Monty Widenius's daughter: My

The data in MySQL is stored in tables. A table is a collection of related data, and it consists of columns
and rows.

PHP + MySQL
 PHP combined with MySQL are cross-platform (you can develop in Windows and serve on a Unix
platform)

Queries
 A query is a question or a request.
 We can query a database for specific information and have a recordset returned.
 Look at the following query (using standard SQL):
 SELECT LastName FROM Employees
 The query above selects all the data in the "LastName" column from the "Employees" table.

PHP Connect to the MySQL Server


Before we can access data in a database, we must open a connection to the MySQL server.
Before we can access data in a database, we must open a connection to the MySQL server.
In PHP, this is done with the following functions.

Syntax
mysqli_connect('Server_Name', ' User_Name', 'Password' , 'Database_Name');
OR
mysql_connect('Server_Name','User_Name','Password');
and connecting Database with
mysql_select_db('Database_Name');

Khurasan University Page 27 of 55


Web Programming

Parameter Description
Server_Name Optional. Either a host/Server name or an IP address
User_Name Optional. The MySQL user name
Password Optional. The password to log in with
Database_Name Optional. The default database to be used when performing queries

Example-------------------------------------------------------------------------------------------------------------------------------
In the following example we store the connection in a variable ($con) for later use in the script:
<?php
// Create connection
$con=mysqli_connect("example.com","peter","abc123","my_db");

// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
------------------------------------------------------------------------------------------------------------------------------------------

Close a Connection
The connection will be closed automatically when the script ends. To close the connection before, use
the mysqli_close() function:

Example-------------------------------------------------------------------------------------------------------------------------------
<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");

// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

mysqli_close($con);
?>
------------------------------------------------------------------------------------------------------------------------------------------

User this the following code while using local/testing server on your computer and then save it
in a connection.php file. Then import it in all web pages where required with the following code.
include("connection.php");
or
require_once("connection.php");

Example-------------------------------------------------------------------------------------------------------------------------------
Khurasan University Page 28 of 55
Web Programming

<?php
$server='localhost'; //Variable used for Server Name, default Server name is localhost in MySQL.
$user='root'; //Variable used for User name, default user name is root.
$pass=''; //Variable used for Password
$db='db_bcs'; //Variable used for Database Name, since our database name is db_bcs

$conn=mysql_connect($server,$user,$pass) or die("Connection Erro r<br>".mysql_error());


mysql_select_db($db) or die("Database Error <br>".mysql_error()); //Used for DB

/* you can also use


$conn=mysql_connect('localhost', 'root', '') or die("Connection Error <br>".mysql_error());
mysql_select_db('DB_Name') or die("Database Error <br>".mysql_error()); */
?>
------------------------------------------------------------------------------------------------------------------------------------------

Create a Database
The CREATE DATABASE statement is used to create a database table in MySQL.
We must add the CREATE DATABASE statement to the mysqli_query() function to execute the
command.
The following example creates a database named "my_db":

Example-------------------------------------------------------------------------------------------------------------------------------
<?php
$con=mysqli_connect("localhost","root","");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

// Create database
$sql="CREATE DATABASE my_db";
if (mysqli_query($con,$sql))
{
echo "Database my_db created successfully";
}
else
{
echo "Error creating database: " . mysqli_error($con);
}
?>
-----------------------------------------------------------------------------------------------------------------------------------------

Khurasan University Page 29 of 55


Web Programming

Create a Table
The CREATE TABLE statement is used to create a table in MySQL.
We must add the CREATE TABLE statement to the mysqli_query() function to execute the command.
The following example creates a table named "Persons", with three columns: "FirstName", "LastName"
and "Age":

Example-------------------------------------------------------------------------------------------------------------------------------
<?php
$con=mysqli_connect("localhost","root","","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

// Create table
$sql="CREATE TABLE Persons(FirstName CHAR(30),LastName CHAR(30),Age INT)";

// Execute query
if (mysqli_query($con,$sql))
{
echo "Table persons created successfully";
}
else
{
echo "Error creating table: " . mysqli_error($con);
}
?>
------------------------------------------------------------------------------------------------------------------------------------------

Primary Keys and Auto Increment Fields


Each table in a database should have a primary key field.

A primary key is used to uniquely identify the rows in a table. Each primary key value must be
unique within the table. Furthermore, the primary key field cannot be null because the database engine
requires a value to locate the record.

The following example sets the PID field as the primary key field. The primary key field is often
an ID number, and is often used with the AUTO_INCREMENT setting. AUTO_INCREMENT automatically
increases the value of the field by 1 each time a new record is added. To ensure that the primary key
field cannot be null, we must add the NOT NULL setting to the field:

Example-------------------------------------------------------------------------------------------------------------------------------
$sql = "CREATE TABLE Persons
(
PID INT NOT NULL AUTO_INCREMENT,

Khurasan University Page 30 of 55


Web Programming

PRIMARY KEY(PID),
FirstName CHAR(15),
LastName CHAR(15),
Age INT
)";
------------------------------------------------------------------------------------------------------------------------------------------

MySQL Data Types


In MySQL there are three main types : text, number, and Date/Time types.

Text types:
Data type Description
Holds a fixed length string (can contain letters, numbers, and special characters). The
CHAR(size)
fixed size is specified in parenthesis. Can store up to 255 characters

Holds a variable length string (can contain letters, numbers, and special characters). The
VARCHAR(size) maximum size is specified in parenthesis. Can store up to 255 characters. Note: If you
put a greater value than 255 it will be converted to a TEXT type
TINYTEXT Holds a string with a maximum length of 255 characters
TEXT Holds a string with a maximum length of 65,535 characters
BLOB For BLOBs (Binary Large OBjects). Holds up to 65,535 bytes of data
MEDIUMTEXT Holds a string with a maximum length of 16,777,215 characters
MEDIUMBLOB For BLOBs (Binary Large OBjects). Holds up to 16,777,215 bytes of data
LONGTEXT Holds a string with a maximum length of 4,294,967,295 characters
LONGBLOB For BLOBs (Binary Large OBjects). Holds up to 4,294,967,295 bytes of data

Let you enter a list of possible values. You can list up to 65535 values in an ENUM list. If
a value is inserted that is not in the list, a blank value will be inserted.
ENUM(x,y,z,etc.)
Note: The values are sorted in the order you enter them.
You enter the possible values in this format: ENUM('X','Y','Z')

Similar to ENUM except that SET may contain up to 64 list items and can store more
SET
than one choice

Number types:
Data type Description
-128 to 127 normal. 0 to 255 UNSIGNED*. The maximum number of digits may be
TINYINT(size)
specified in parenthesis
-32768 to 32767 normal. 0 to 65535 UNSIGNED*. The maximum number of digits
SMALLINT(size)
may be specified in parenthesis
-8388608 to 8388607 normal. 0 to 16777215 UNSIGNED*. The maximum number
MEDIUMINT(size)
of digits may be specified in parenthesis
INT(size) -2147483648 to 2147483647 normal. 0 to 4294967295 UNSIGNED*. The maximum
Khurasan University Page 31 of 55
Web Programming

number of digits may be specified in parenthesis


-9223372036854775808 to 9223372036854775807 normal. 0 to
BIGINT(size) 18446744073709551615 UNSIGNED*. The maximum number of digits may be
specified in parenthesis
A small number with a floating decimal point. The maximum number of digits may
FLOAT(size,d) be specified in the size parameter. The maximum number of digits to the right of
the decimal point is specified in the d parameter
A large number with a floating decimal point. The maximum number of digits may
DOUBLE(size,d) be specified in the size parameter. The maximum number of digits to the right of
the decimal point is specified in the d parameter
A DOUBLE stored as a string , allowing for a fixed decimal point. The maximum
DECIMAL(size,d) number of digits may be specified in the size parameter. The maximum number of
digits to the right of the decimal point is specified in the d parameter

*The integer types have an extra option called UNSIGNED. Normally, the integer goes from an negative
to positive value. Adding the UNSIGNED attribute will move that range up so it starts at zero instead of a
negative number.

Date types:
Data type Description
A date. Format: YYYY-MM-DD
DATE()
Note: The supported range is from '1000-01-01' to '9999-12-31'
*A date and time combination. Format: YYYY-MM-DD HH:MM:SS
DATETIME()
Note: The supported range is from '1000-01-01 00:00:00' to '9999-12-31 23:59:59'
*A timestamp. TIMESTAMP values are stored as the number of seconds since the
Unix epoch ('1970-01-01 00:00:00' UTC). Format: YYYY-MM-DD HH:MM:SS
TIMESTAMP()
Note: The supported range is from '1970-01-01 00:00:01' UTC to '2038-01-09
03:14:07' UTC
A time. Format: HH:MM:SS
TIME()
Note: The supported range is from '-838:59:59' to '838:59:59'
A year in two-digit or four-digit format.
YEAR() Note: Values allowed in four-digit format: 1901 to 2155. Values allowed in two-digit
format: 70 to 69, representing years from 1970 to 2069

*Even if DATETIME and TIMESTAMP return the same format, they work very differently. In an INSERT or
UPDATE query, the TIMESTAMP automatically set itself to the current date and time.

Insert Data into a Database Table


The INSERT INTO statement is used to add new records to a database table.

Khurasan University Page 32 of 55


Web Programming

Syntax
It is possible to write the INSERT INTO statement in two forms.
The first form doesn't specify the column names where the data will be inserted, only their values:

INSERT INTO table_name


VALUES (value1, value2, value3,...)

The second form specifies both the column names and the values to be inserted:

INSERT INTO table_name (column1, column2, column3,...)


VALUES (value1, value2, value3,...)

In the previous chapter we created a table named "Persons", with three columns; "FirstName",
"LastName" and "Age". We will use the same table in this example. The following example adds two new
records to the "Persons" table:

Example-------------------------------------------------------------------------------------------------------------------------------
<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

mysqli_query($con,"INSERT INTO Persons (FirstName, LastName, Age)


VALUES ('Peter', 'Griffin',35)");

mysqli_query($con,"INSERT INTO Persons (FirstName, LastName, Age)


VALUES ('Glenn', 'Quagmire',33)");

mysqli_close($con);
?>
------------------------------------------------------------------------------------------------------------------------------------------

Insert Data From a Form Into a Database


Now we will create an HTML form that can be used to add new records to the "Persons" table.
Here is the HTML form:

Example-------------------------------------------------------------------------------------------------------------------------------
<html>
<body>

<form action="insert.php" method="post">


Firstname: <input type="text" name="firstname">
Lastname: <input type="text" name="lastname">

Khurasan University Page 33 of 55


Web Programming

Age: <input type="text" name="age">


<input type="submit">
</form>

</body>
</html>
------------------------------------------------------------------------------------------------------------------------------------------

When a user clicks the submit button in the HTML form, in the example above, the form data is sent to
"insert.php".

The "insert.php" file connects to a database, and retrieves the values from the form with the PHP
$_POST variables.

Then, the mysqli_query() function executes the INSERT INTO statement, and a new record will be added
to the "Persons" table.

Here is the "insert.php" page:

Example-------------------------------------------------------------------------------------------------------------------------------
<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$sql="INSERT INTO Persons (FirstName, LastName, Age)


VALUES
('$_POST[firstname]','$_POST[lastname]','$_POST[age]')";

if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "1 record added";

mysqli_close($con);
?>
------------------------------------------------------------------------------------------------------------------------------------------

Select Data From a Database Table


The SELECT statement is used to select data from a database.

Khurasan University Page 34 of 55


Web Programming

Syntax
SELECT column_name(s)
FROM table_name;

To get PHP to execute the statement above we must use the mysqli_query() function. This function is
used to send a query or command to a MySQL connection.

The following example selects all the data stored in the "Persons" table (The * character selects all the
data in the table):

Example-------------------------------------------------------------------------------------------------------------------------------
<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$result = mysqli_query($con,"SELECT * FROM Persons");

while($row = mysqli_fetch_array($result))
{
echo $row['FirstName'] . " " . $row['LastName'];
echo "<br>";
}

mysqli_close($con);
?>
------------------------------------------------------------------------------------------------------------------------------------------

The example above stores the data returned by the mysqli_query() function in the $result variable.

Next, we use the mysqli_fetch_array() function to return the first row from the recordset as an array.
Each call to mysqli_fetch_array() returns the next row in the recordset. The while loop loops through all
the records in the recordset. To print the value of each row, we use the PHP $row variable
($row['FirstName'] and $row['LastName']).

The output of the code above will be:

Peter Griffin
Glenn Quagmire
Display the Result in an HTML Table
Khurasan University Page 35 of 55
Web Programming

The following example selects the same data as the example above, but will display the data in an HTML
table:

Example-------------------------------------------------------------------------------------------------------------------------------
<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$result = mysqli_query($con,"SELECT * FROM Persons");

echo "<table border='1'>


<tr>
<th>Firstname</th>
<th>Lastname</th>
</tr>";

while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['FirstName'] . "</td>";
echo "<td>" . $row['LastName'] . "</td>";
echo "</tr>";
}
echo "</table>";

mysqli_close($con);
?>
------------------------------------------------------------------------------------------------------------------------------------------

The output of the code above will be:

Firstname Lastname
Glenn Quagmire
Peter Griffin

The WHERE clause


Khurasan University Page 36 of 55
Web Programming

The WHERE clause is used to extract only those records that fulfill a specified criterion.
Syntax

SELECT column_name(s)
FROM table_name
WHERE column_name operator value;

To get PHP to execute the statement above we must use the mysqli_query() function. This function is
used to send a query or command to a MySQL connection.

The following example selects all rows from the "Persons" table where "FirstName='Peter'":

Example-------------------------------------------------------------------------------------------------------------------------------
<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$result = mysqli_query($con,"SELECT * FROM Persons


WHERE FirstName='Peter'");

while($row = mysqli_fetch_array($result))
{
echo $row['FirstName'] . " " . $row['LastName'];
echo "<br>";
}
?>
------------------------------------------------------------------------------------------------------------------------------------------

The output of the code above will be:

Peter Griffin

Khurasan University Page 37 of 55


Web Programming

The ORDER BY Keyword


The ORDER BY keyword is used to sort the data in a recordset.
The ORDER BY keyword sort the records in ascending order by default.

If you want to sort the records in a descending order, you can use the DESC keyword.
Syntax

SELECT column_name(s)
FROM table_name
ORDER BY column_name(s) ASC|DESC

The following example selects all the data stored in the "Persons" table, and sorts the result by the
"Age" column:

Example-------------------------------------------------------------------------------------------------------------------------------
<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$result = mysqli_query($con,"SELECT * FROM Persons ORDER BY age");

while($row = mysqli_fetch_array($result))
{
echo $row['FirstName'];
echo " " . $row['LastName'];
echo " " . $row['Age'];
echo "<br>";
}

mysqli_close($con);
?>
------------------------------------------------------------------------------------------------------------------------------------------

The output of the code above will be:

Glenn Quagmire 33
Peter Griffin 35

Khurasan University Page 38 of 55


Web Programming

Order by Two Columns


It is also possible to order by more than one column. When ordering by more than one column, the
second column is only used if the values in the first column are equal:

SELECT column_name(s)
FROM table_name
ORDER BY column1, column2

Update Data in a Database


The UPDATE statement is used to update existing records in a table.
Syntax

UPDATE table_name
SET column1=value, column2=value2,...
WHERE some_column=some_value

Note: Notice the WHERE clause in the UPDATE syntax. The WHERE clause specifies which record or
records that should be updated. If you omit the WHERE clause, all records will be updated!

To get PHP to execute the statement above we must use the mysqli_query() function. This function is
used to send a query or command to a MySQL connection.

Earlier we created a table named "Persons". Here is how it looks:

FirstName LastName Age


Peter Griffin 35
Glenn Quagmire 33

The following example updates some data in the "Persons" table:

Example-------------------------------------------------------------------------------------------------------------------------------
<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

mysqli_query($con,"UPDATE Persons SET Age=36


WHERE FirstName='Peter' AND LastName='Griffin'");

Khurasan University Page 39 of 55


Web Programming

mysqli_close($con);
?>
------------------------------------------------------------------------------------------------------------------------------------------

After the update, the "Persons" table will look like this:

FirstName LastName Age


Peter Griffin 36
Glenn Quagmire 33

Delete Data In a Database


The DELETE FROM statement is used to delete records from a database table.

Syntax

DELETE FROM table_name


WHERE some_column = some_value;

Note: Notice the WHERE clause in the DELETE syntax. The WHERE clause specifies which record or
records that should be deleted. If you omit the WHERE clause, all records will be deleted!

To get PHP to execute the statement above we must use the mysqli_query() function. This function is
used to send a query or command to a MySQL connection.

Look at the following "Persons" table:

FirstName LastName Age


Peter Griffin 35
Glenn Quagmire 33

The following example deletes all the records in the "Persons" table where LastName='Griffin':

Example-------------------------------------------------------------------------------------------------------------------------------
<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

Khurasan University Page 40 of 55


Web Programming

mysqli_query($con,"DELETE FROM Persons WHERE LastName='Griffin'");

mysqli_close($con);
?>
------------------------------------------------------------------------------------------------------------------------------------------

After the deletion, the table will look like this:

FirstName LastName Age


Glenn Quagmire 33

Khurasan University Page 41 of 55


Web Programming

Create an ODBC Connection


ODBC is an Application Programming Interface (API) that allows you to connect to a data source (e.g. an
MS Access database).

With an ODBC connection, you can connect to any database, on any computer in your network, as long
as an ODBC connection is available.
Here is how to create an ODBC connection to a MS Access Database:
1. Open the Administrative Tools icon in your Control Panel.
2. Double-click on the Data Sources (ODBC) icon inside.
3. Choose the System DSN tab.
4. Click on Add in the System DSN tab.
5. Select the Microsoft Access Driver. Click Finish.
6. In the next screen, click Select to locate the database.
7. Give the database a Data Source Name (DSN).
8. Click OK.

Connecting to an ODBC
The odbc_connect() function is used to connect to an ODBC data source. The function takes four
parameters: the data source name, username, password, and an optional cursor type.
The odbc_exec() function is used to execute an SQL statement.

The following example creates a connection to a DSN called northwind, with no username and no
password. It then creates an SQL and executes it:
Example-------------------------------------------------------------------------------------------------------------------------------
$conn=odbc_connect('northwind','','');
$sql="SELECT * FROM customers";
$rs=odbc_exec($conn,$sql);
------------------------------------------------------------------------------------------------------------------------------------------

Retrieving Records
The odbc_fetch_row() function is used to return records from the result-set. This function returns true if
it is able to return rows, otherwise false.
The function takes two parameters: the ODBC result identifier and an optional row number:
odbc_fetch_row($rs)

Retrieving Fields from a Record


The odbc_result() function is used to read fields from a record. This function takes two parameters: the
ODBC result identifier and a field number or name.
The code line below returns the value of the first field from the record:

Khurasan University Page 42 of 55


Web Programming

Example-------------------------------------------------------------------------------------------------------------------------------
$compname=odbc_result($rs,1);
The code line below returns the value of a field called "CompanyName":
$compname=odbc_result($rs,"CompanyName");
------------------------------------------------------------------------------------------------------------------------------------------

Closing an ODBC Connection


The odbc_close() function is used to close an ODBC connection.
odbc_close($conn);

An ODBC Example
The following example shows how to first create a database connection, then a result-set, and then
display the data in an HTML table.

Example-------------------------------------------------------------------------------------------------------------------------------
<html>
<body>
<?php
$conn=odbc_connect('northwind','','');
if (!$conn)
{exit("Connection Failed: " . $conn);}
$sql="SELECT * FROM customers";
$rs=odbc_exec($conn,$sql);
if (!$rs)
{exit("Error in SQL");}
echo "<table><tr>";
echo "<th>Companyname</th>";
echo "<th>Contactname</th></tr>";
while (odbc_fetch_row($rs))
{
$compname=odbc_result($rs,"CompanyName");
$conname=odbc_result($rs,"ContactName");
echo "<tr><td>$compname</td>";
echo "<td>$conname</td></tr>";
}
odbc_close($conn);
echo "</table>";
?>
</body></html>
------------------------------------------------------------------------------------------------------------------------------------------

Khurasan University Page 43 of 55


Web Programming

Khurasan BCS Class Examples:

Connection Page:
PageName: Connection.php

Example-------------------------------------------------------------------------------------------------------------------------------
<?php
//Syntax:
//mysql_connect('Server_Name','User_Name','Password');
//mysql_select_db('Database_Name''');

$server='localhost';
$user='root';
$pass='';
$db='bcsmorning';

mysql_connect($server,$user,$pass) or die("Connection Error <br> ".mysql_error());


// This function is used to connect with MySQL.

mysql_select_db($db) or die("Database Error <br> ".mysql_error());


// This function is used to select Database from MySQL.
?>
------------------------------------------------------------------------------------------------------------------------------------------

Show Page:
PageName: show.php or any other name
 This page is used to show records from your database tables.
 SQL select query is used to extract records from database.

Example-------------------------------------------------------------------------------------------------------------------------------
<?php
include("connection.php");
//require_once("connection.php");
?>
<html > <body>
<?php
echo "<table width='100%' bgcolor='FFFFFF' border='1' align='center'>";
echo "<tr>";
echo "<th>ID</th>";
echo "<th>Name</th>";
echo "<th>Address</th>";
Khurasan University Page 44 of 55
Web Programming

echo "<th>Class</th>";
echo "<th>Fee</th>";
echo "<th>Action</th>";
echo "</tr>";

$sql=mysql_query("select * from tbl_student") or die("Query Error<br>");

while($row=mysql_fetch_array($sql)){
$id=$row['id'];
$name=$row['name'];
$address=$row['address'];
$fee=$row['fee'];
$clas=$row['clas'];
echo "<tr align='center'>";
echo "<td>".$id."</td>";
echo "<td>".$name."</td>";
echo "<td>".$address."</td>";
echo "<td>".$clas."</td>";
echo "<td>".$fee."</td>";
echo '<td><a href="delete.php?id='.$id.'"> Delete</a>
| <a href="update.php?id='.$id.'">Update</a></td>';
echo "</tr>";
}
echo "</table>";
?>
</body> </html>
------------------------------------------------------------------------------------------------------------------------------------------

Delete Page:
Page Name: delete.php or any other name.
 This page is used to delete record from database table.
 When someone click on delete link from show.php page, then specific record is deleted.

Example-------------------------------------------------------------------------------------------------------------------------------
<?php
include("connection.php");
$id=$_GET['id'];
if($_SERVER['REQUEST_METHOD']=='GET'){
mysql_query("delete from tbl_student where id='$id'") or die("Query Error<br>".mysql_error());
header("location:show.php");
} ?>
------------------------------------------------------------------------------------------------------------------------------------------

Khurasan University Page 45 of 55


Web Programming

Update Page:
Page Name: update.php or any other name.
 This page is used to update specific record.
 First create required fields in update.php page and give proper name to each filed.
 When someone clicks on update link from update.php page, then specific record id is send to
update.php page, and that specific record is open in update.php page.
 Following is the code of update.php page

Example-------------------------------------------------------------------------------------------------------------------------------
<?php
include("connection.php");
$id=$_GET['id'];
if($_SERVER['REQUEST_METHOD']=='GET'){
$sql=mysql_query("select * from tbl_student where id='$id'") or die("Query Error<br>");

while($row=mysql_fetch_array($sql)){
$id=$row['id'];
$name=$row['name'];
$address=$row['address'];
$fee=$row['fee'];
$clas=$row['clas'];
}
}

if($_SERVER['REQUEST_METHOD']=='POST'){
$id=$_GET['id'];
$name=$_POST['name'];
$clas=$_POST['clas'];
$fee=$_POST['fee'];
$address=$_POST['address'];

mysql_query("update tbl_student
set
name='$name',
clas='$clas',
fee='$fee',
address='$address'
where id='$id'
") or die("Update Query Error");

header("location:show.php");

Khurasan University Page 46 of 55


Web Programming

}
?>

<html >
<body>
<form name="form1" method="post" action="">
<table width="324" border="1">
<tr>
<td width="130">Name</td>
<td width="140"><input type="text" name="name"
value="<?php echo $name; ?>"></td>
</tr>
<tr>
<td>Class</td>
<td><input type="text" name="clas" value="<?php echo $clas; ?>"></td>
</tr>
<tr>
<td>Address</td>
<td><input type="text" name="address" value="<?php echo $address; ?>"></td>
</tr>
<tr>
<td>Fee</td>
<td><input type="text" name="fee" value="<?php echo $fee; ?>"></td>
</tr>
<tr>
<td>&nbsp;</td>
<td><input type="submit" value="Save" name="save"></td>
</tr>
</table>
</form>
</body>
</html>
------------------------------------------------------------------------------------------------------------------------------------------

Khurasan University Page 47 of 55


Web Programming

Insert Page:
Page Name: insert.php or any other name.
 This page is used to insert data in database table.
 Create required Fields in your Page according to your database table.
 Create text boxes, dropdown lists, checkboxes, radio buttons, file fields etc using HTML
 Give proper names to textboxes, dropdown lists, buttons etc.
 Below is code of insert page

Example-------------------------------------------------------------------------------------------------------------------------------
<?php
include("connection.php");
if(isset($_POST['save'])){
$name=$_POST['name'];
$clas=$_POST['clas'];
$address=$_POST['address'];
$fee=$_POST['fee'];
$gender=$_POST['gender'];

$country=$_POST['country'];

//-----Image/File------
$dir='images\std\ ';
$uploadfile=$dir.basename($_FILES['file']['name']);
if(move_uploaded_file($_FILES['file']['tmp_name'],$uploadfile)){
$filename='images/std/ '.$_FILES['file']['name'];
}

mysql_query("insert into tbl_student


(name,clas,address,fee,image,country,gender)
values
('$name','$clas','$address','$fee','$filename','$country','$gender')")
or die ("Query Error<br>".mysql_error());
header("location:insert.php");

}
?>

<html >
<style>
.my{
font-family:Verdana, Geneva, sans-serif;

Khurasan University Page 48 of 55


Web Programming

color:#FFF;
font-weight:bold;
text-decoration:underline;
font-size:11px
}
img {
border:none;
}
</style>
</head>

<body>
<table border="1" width="772" bgcolor="#CCCCCC">
<tr>
<td width="450" height="179" valign="top">
<form action="" method="post" enctype="multipart/form-data" name="form1">
<table width="100%" border="0">
<tr>
<td colspan="2" class="my"> Insert Student Record</td>
</tr>
<tr>
<td width="28%">Name</td>
<td width="72%"><input type="text" name="name" id="name"></td>
</tr>
<tr>
<td>Class</td>
<td>
<?php
//this code is used to select data from Class table and show in drop down list.
$sql_class=mysql_query("select classname from tbl_class") or die("Error");
echo "<select name='clas'>";
while($row_class=mysql_fetch_array($sql_class)){
echo '<option>'.$row_class['classname'].'</option>';
}

echo "</select>";
?>
</td>
</tr>
<tr>
<td>Address</td>

Khurasan University Page 49 of 55


Web Programming

<td><input type="text" name="address" id="address"></td>


</tr>
<tr>
<td>Fee</td>
<td><input type="text" name="fee" id="fee"></td>
</tr>
<tr>
<td>Country</td>
<td>
<select name=country>
<option value="AFG" > Afghanistan </option>
<option value="PAK"> Pakistan </option>
<option> Iran </option>
<option> India </option>
</select>
</td>
</tr>
<tr>
<td>Gender</td>
<td><input type="radio" name="gender" id="radio" value="Male">
Male
<input type="radio" name="gender" id="radio2" value="Female">
Female</td>
</tr>
<tr>
<td>Picture</td>
<td><input type="file" name="file" id="file"></td>
</tr>
<tr>
<td>&nbsp;</td>
<td><input type="submit" value="Save" name="save"> </td>
</tr>
</table>
</form></td>
</tr>
<tr bordercolor="#CCCCCC">

<td>

<?php
//this code is used to show inserted records.

Khurasan University Page 50 of 55


Web Programming

echo "<table width='100%' bgcolor='' border='1' align='center'>


<tr><th>ID</th>
<th>Name</th>
<th>Class</th>
<th>Action</th>
</tr>";

$sql=mysql_query("select * from tbl_student") or die("Query Error<br>");

while($row=mysql_fetch_array($sql)){
$id=$row['id'];
$name=$row['name'];
$clas=$row['clas'];
echo "<tr align='center'>
<td>".$id."</td>
<td>".$name."</td>
<td>".$clas."</td>
<td><a href='details.php?id=".$row['id']."'>Details</a></td>
</tr>";
}

echo "</table>";
?>
</td>
</tr>
</table>
</body> </html>

------------------------------------------------------------------------------------------------------------------------------------------

Details Page
Page Name: details.php or any other name.
 This page is used to show detail record of student.
 When some click detail icon from insert.php page, then this page will open and show detail
record of student.

Example-------------------------------------------------------------------------------------------------------------------------------
<?php
include("connection.php");
$id=$_GET['id'];
if($_SERVER['REQUEST_METHOD']=='GET'){

Khurasan University Page 51 of 55


Web Programming

$sql=mysql_query("select * from tbl_student where id='$id'") or die("Query Error<br>");

while($row=mysql_fetch_array($sql)){
$id=$row['id'];
$name=$row['name'];
$address=$row['address'];
$fee=$row['fee'];
$clas=$row['clas'];
$image=$row['image'];
$country=$row['country'];
$gender=$row['gender'];
}
}
?>

<html>
<body>

<form name="form1" method="post" action="">


<table width="500" border="0">
<tr>
<td width="102">ID</td>
<td width="388"><input type="text" name="id" id="id"
value="<?php echo $id; ?>"></td>
</tr>
<tr>
<td>Name</td>
<td><input type="text" name="name" id="name" value="<?php echo $name; ?>" ></td>
</tr>
<tr>
<td>Class</td>
<td><input type="text" name="clas" id="clas"
value="<?php echo $clas; ?>"></td>
</tr>
<tr>
<td>Address</td>
<td><input type="text" name="address" id="address" value="<?php echo $address; ?>"></td>
</tr>
<tr>
<td>Fee</td>
<td><input type="text" name="fee" id="fee" value="<?php echo $fee; ?>"></td>

Khurasan University Page 52 of 55


Web Programming

</tr>
<tr>
<td>Gender</td>
<td>
<input
<?php if (!(strcmp($gender,'Male'))) {echo "checked";} ?>
type="radio" name="gender" value="Male"> Male

<input
<?php if ($gender=='Female') {echo "checked";} ?>
type="radio" name="gender" value="Female"> Female

</td>
</tr>
<tr>
<td>Country</td>
<td><input name="country" type="text" id="country" value="<?php echo $country; ?>"></td>
</tr>
<tr>
<td>Picture</td>
<td><img src="<?php echo $image; ?>" width="100" height="100" name="image"></td>
</tr>
</table>
</form>
</body>
</html>
------------------------------------------------------------------------------------------------------------------------------------------

Searching:
Page Name: Create two pages and give names as:
search1.php
search2.php
 First create criteria fields in search1.php page
 And then write php searching code in search2.php page

Search1.php page code:


Example-------------------------------------------------------------------------------------------------------------------------------
<html >
<body>
<form id="form1" name="form1" method="post" action="search2.php">
<table width="100%" border="0">

Khurasan University Page 53 of 55


Web Programming

<tr>
<td colspan="2">
<select name="select">
<option value="">--- Select any catagory ---</option>
<option value="id">ID</option>
<option value="name">Name</option>
<option value="class">Class</option>
</select>
</td>
</tr>
<tr>
<td width="36%"><input type="text" name="search" /></td>
<td width="64%"><input type="submit" name="btnsearch" value="Search" /></td>
</tr>
</table>
</form>
</body>
</html>
------------------------------------------------------------------------------------------------------------------------------------------

Search2.php page code


Example-------------------------------------------------------------------------------------------------------------------------------
<?php
include("connection.php");

$select=$_POST['select'];
$search=$_POST["search"];

if($select=='')
{
echo "Please select any criteria";
}
else if($select=='id')
{
$sql=mysql_query("select * from tbl_student where id='$search'") or die("ID Query Error");
}
else if($select=='name')
{
$sql=mysql_query("select * from tbl_student
where name like '%$search%'")
or die("Name Query Error");

Khurasan University Page 54 of 55


Web Programming

}
else if($select=='class')
{
$sql=mysql_query("select * from tbl_student where clas like '$search%'") or die("Class Query Error");
}
if(mysql_num_rows($sql)==0)
{
echo "No data found";
}
else {

echo "<table border='1'>";


echo '<tr>';
echo '<td>ID</td>';
echo '<td>Name</td>';
echo '<td>Class</td>';
echo '<td>Fee</td>';
echo '<td>Address</td>';
echo '</tr>';
while($data=mysql_fetch_array($sql))
{
$id=$data['id'];
$name=$data['name'];
$clas=$data['clas'];
$address=$data['address'];
$fee=$data['fee'];

echo '<tr>';
echo '<td>'.$id .'</td>';
echo '<td>'.$name .'</td>';
echo '<td>'.$clas .'</td>';
echo '<td>'.$fee .'</td>';
echo '<td>'.$address .'</td>';
}
echo '</table>';
}
?>
------------------------------------------------------------------------------------------------------------------------------------------

Khurasan University Page 55 of 55

You might also like