0% found this document useful (0 votes)
7 views157 pages

Chap 5 PHP (1)

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

Chap 5 PHP (1)

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

CHAPTER Five

PHP

Dawed O

1
2

Contents

Basics of PHP

Features of PHP

Retrieve data from HTML forms

Displaying Errors

Control and Loop statements

References and Arrays

Functions
Introduction
 HTML- focuses on marking up information(define the
content of web pages)
 CSS- focuses on formatting and presenting
information(specify the layout of web pages)
 JavaScript to program the behavior of web pages(
to add dynamic features on the client side)
 PHP is a server scripting language, and a powerful
tool for making dynamic and interactive Web pages. (
used to add dynamic features on the server
side…including database interaction)
Cont’d ...
 Static VS Dynamic Web Sites
• Static Websites-Written in HTML only
• Dynamic Websites – do more interactive things.
 Markup language like HTML
 Scripting (both client and server side) language
 Style sheet (for presentation) like CSS
 Client-Side Scripting VS Server-Side Scripting
 Client-Side
 Server-Side
 PHP is a server scripting language, and a powerful
tool for making dynamic and interactive Web pages.
Client side scripting vs. server side scripting

Client side Server side


Webserver

HTML* PHP engine

HTML PHP
Common Web Application Architecture

Requests
Browser Server

Responses

Requests
Responses
Responses
Script
Database Engine
Requests

6
Client-side Technologies

CLIENT
Server
SIDE

Browser

HTML
JavaScript
CSS

Script
Database Engine

7
Server-Side

Browser Server

Apache

SERVER SIDE

Database Script PHP


MySQL Engine

8
Client side vs Server side scripting
Client-side Server-side
• Scripts are stored on the • Scripts are stored on the
client (engine is in browser) server (engine is on server)

• Scripts can be modified by • Scripts cannot be modified


the end user by the end user
• Browser-dependent • Browser-independent
• Source code can be viewed • Source code can’t be
viewed
• Can’t communicate with a • Can communicate with a
database database
• No network overhead • Dependent on network
bandwidth
• Processing is done by the • Processing is done by the
browser - fast server - slower
How web server works?
 Client specifies document at a specific web address.
E.g. http://www.inu.edu.et/

 If the requested document is HTML or text, the server


simply forwards it back to the client.

 However, the requested document may be an executable


script, or it may be HTML with an embedded script, In
this cases, the server executes the script
 If the entire document was a script, the server
simply sends the output back to the client
 If the document had an embedded script, the script
sections are replaced with the output and the
modified document is then sent to the client

Note that the client never sees the server-side script


code
Introduction
 PHP is a powerful server-side scripting language
for creating dynamic and interactive websites.

• PHP is perfectly appropriate for Web


development and can be embedded directly into
the HTML code.

• The PHP syntax is very similar to C.

• PHP is often used together with Apache(web


server) on various operating systems.

• A PHP file may contain text, HTML tags and


scripts.

11
Cont’d …
 Scripts in a PHP file are executed on the server.
 PHP files are returned to the browser as plain
HTML
 PHP files have a file extension of “.php”

 PHP is whitespace insensitive:


• That means it almost never matters how many
whitespace characters you have in a row
including tabs and carriage returns (end-of-line
characters).

 PHP is case sensitive:[$color, $COLOR, and


$coLOR are different]

12
What is PHP?
 PHP stands for Hypertext Preprocessor

 PHP supports many databases (MySQL, Informix,


Oracle, Sybase, Solid, PostgreSQL, Generic
ODBC, etc.)

 PHP is an open source software (OSS)


 PHP is free to download and use
 PHP runs on different platforms (Windows,
Linux, Unix, etc.)

 PHP is compatible with almost all servers used


today (Apache, IIS, etc.)

13
What is a PHP File?

 PHP files can contain text, HTML, JavaScript


code, and PHP code

 PHP code are executed on the server, and the


result is returned to the browser as plain HTML

 PHP files have a default file extension of “.php"


What Can PHP Do?
• generate dynamic page content

• create, open, read, write, and close files on the


server

• collect form data

• send and receive cookies

• add, delete, modify data in your database

• restrict users to access some pages on your


website
• encrypt data
Why PHP?
 Powerful and flexible,
 easy to learn and runs efficiently on the
server side
 runs on different platforms (Windows, Linux,
Unix, Mac OS X, etc.)
 compatible with almost all servers used today
(Apache, IIS, etc.)
 support for a wide range of databases(MySQL,
Informix, Oracle, Sybase, Solid, PostgreSQL,
Generic ODBC, etc)
 open source software and free to download
and use.
 Cheap and Easy to set up
Basic PHP Syntax
 A PHP scripting block can be placed anywhere in the
document.
 A PHP scripting block always starts with
<?php and ends with ?>
 Syntax:
<?php
// PHP code goes here
?>

 Each code line in PHP must end with a semicolon.

17
Cont’d …
<html>
<body>
<?php
echo "Hello World";
?>
</body>
</html>
 <?php tag informs the server that PHP code is to
follow.
 The server then switches over to PHP mode in
anticipation of a PHP command.
 The ?> tag closes out the PHP mode with the server
resuming its scanning in HTML mode once more.
Cont’d ...
 All PHP code is contained in one of several
script tags:
1. <?php
// Some code here
?>

2. <?
// Some code
?>

3. <script language=“PHP">
// Some code here
</script>
Cont’d ...
 When a PHP file is requested, the PHP interpreter
parses the entire file
 Any content within PHP delimiter tags is
interpreted, and the output substituted
 Any other content (i.e. not within PHP
delimiter tags) is simply passed on unchanged
 This allows us to easily mix PHP and other
content (ex: HTML)

 Each code line in PHP must end with a semicolon.


 The semicolon is a separator which is used to
distinguish one set of instructions from another.
 With PHP, there are two basic statements to output
text in the browser: echo and print.
Example
HTML 5 Document
<!DOCTYPE html>
<html> Root HTML Tag
<head>
<title>Simple PHP Example</title> Document Head
</head>
<body>
<?php echo "<p><h1>Output</h1>";
D
echo "<h2>Output</h2>";
O
echo "<h3>Output</h3></p>"; PHP Code
C
?>
B <script language="PHP">
O echo "\n<b>More PHP Output</b>\n";
D echo "New line in source but not rendered";
Y echo "<br/>";
echo "New line rendered but not in source";
</script>
</body>
</html>
21
Example
<html>
<head><title>Hello World in PHP</title></head>
<body>
<?php //this is a comment in PHP, yes just like in Java
// <?php indicates the start of PHP directives in HTML
echo "Hello World, $_ENV["USER"];
// our Hello World with your username
//Finally terminate the PHP directives
?>
</body>
</html>
Output statements
 Two basic statements to output text with PHP: echo and print.
Echo Format Print Format
echo output1, output2, output3, print output;
output4
echo (output); print (output);

 Unlike echo print can accept only one argument.

 It is possible to embed html tags into echo and print


<?php
statement.
echo "Hello <br> World"; ?>
 For example - we have used the echo statement to output the
text "Hello World".
23
Comments
 Is a line that is not read/executed as part of the program.
 There are two commenting formats in PHP:
 Single-line comments: to make a single-line comment ( // ) or
# ... ; for single line
 Multi-lines comments: to make a multiple line comment block
(/* and */ )
<html> <body>
<?php
//This is a single-line comment
/*
This is
A multiple line comment
block
*/
24 ?>
Script execution

 There are two methods for executing PHP


scripts:
 via the Web server, and
 the command-line interface (CLI).

1. Upload your .php file to your Web account (i.e.,


within the www-home directory).

2. Make sure the permissions are set correctly;

3. Navigate to the file with a Web browser.

25
Cont’d ...
 The PHP processor has two modes: copy (HTML)
and interpret (PHP).
 PHP processor takes a PHP document as input and
produces an HTML document file

 When it finds HTML code in the input file, simply


copies it to the output file

 When it finds PHP script, it interprets it and send


any output of the script to the output file

 This new output file is sent to the requesting


browser.
 The client never sees the PHP script.
26
PHP Facts

 Like JS, PHP is usually purely interpreted

 Syntax and semantics are closely related to JS

 Like JS, PHP uses dynamic typing

 PHP variables are case sensitive, but reserved


words and function names are not.

Eg. while, WHILE, While, and wHiLe are same

27
Cont’d ...
• Interpreted rather than compiled like Java or C.
• an embedded scripting language, meaning that it
can exist within HTML code.
• a server-side technology, everything happens on
the server as opposed to the Web browser’s
computer, the client.
• cross-platform, meaning it can be used on Linux,
Windows, Macintosh, etc., making PHP very
portable.
• compatible with almost all servers used today
(Apache, IIS, etc.)
• easy to learn and runs efficiently on the server
side
28
29
PHP Variables
 A variable is a holder for a type of data.
 They are dynamically typed, so you do not need to
specify the type (e.g., int, float, etc.).
 All variables in PHP start with a $ sign symbol.
<?php
$txt="Hello World!";
$x=16;
?>
 In PHP, a variable does not need to be declared
before adding a value to it.
 PHP is a Loosely Typed Language
Rules for PHP variable
 A variable starts with the $ sign, followed by
the name of the variable
 A variable name must begin with a letter or the
underscore character
 A variable name can only contain alpha-
numeric characters and underscores (A-z, 0-9,
and _ )
 A variable name should not contain spaces
 Variable names are case sensitive ($y and $Y
are two different variables)
Example
<!DOCTYPE html>
<html>
<body>
<?php
$txt = “Php variable example!";
$x = 30;
$y = 20.5;
echo $txt;
echo "<br>";
echo $x;
echo "<br>";
echo $y;
?>
</body>
</html>
Environment/predefined Variables
 Beyond the variables you declare in your code, PHP
has a collection of environment variables, which are
system defined variables that are accessible from
anywhere inside the PHP code ("superglobals“
variables),
 These variables allow the script access to server
information, form parameters, environment
information, etc
 All of these environment variables are stored by PHP
as arrays.
 Some you can address directly by using the name of
the index position as a variable name. Other can
only be accessed through their arrays.
33
Some of the environment variables include:
 $_SERVER
 Contains information about the server and the
HTTP connection. Analogous to the old
$HTTP_SERVER_VARS array (which is still
available, but deprecated).

 $_COOKIE
 Contains any cookie data sent back to the
server from the client. Indexed by cookie name.
Analogous to the old $HTTP_COOKIE_VARS
array (which is still available, but deprecated).

34
Cont....

 $_GET
 Contains any information sent to the server as
a search string as part of the URL. Analogous
to the old $HTTP_GET_VARS array (which is
still available, but deprecated).

 $_POST
 Contains any information sent to the server as
a POST style posting from a client form.
Analogous to the old $HTTP_POST_VARS array
(which is still available, but deprecated).

35
Cont’d …
 $_FILE
 Contains information about any uploaded files.
Analogous to the old $HTTP_POST_FILES array
(which is still available, but deprecated).
 $_ENV
 Contains information about environmental variables
on the server. Analogous to the old
$HTTP_ENV_VARS array (which is still available,
but deprecated).
PHP Variable Scopes
 PHP has four different variable scopes:
• local
• global
• static
Local scope
 A variable declared within a PHP function is local and can only
be accessed within that function:
<?php
$x=5; // global scope
function myTest()
{
$x=6; // local scope
echo $x; // local scope
}
myTest();
?>
 Local variables are deleted as soon as the function is
completed
Global scope
 A variable declared outside a function has a GLOBAL
SCOPE and can only be accessed outside a function:
 The global keyword is used to access a global variable
from within a function(use the global keyword before
the variables (inside the function))
<?php
$x=5; // global scope
$y=10; // global scope
function myTest(){
global $x,$y;
$y=$x+$y; }
myTest();
echo $y; // outputs 15
?>
Cont’d …
 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.
<?php
$x=5;
$y=10;
function myTest()
{
$GLOBALS['y']=$GLOBALS['x']+$GLOBALS['y'];
}
myTest();
echo $y; // outputs 15
?>
Static scope
 When a function is completed/executed, all of its variables are
normally deleted. However, sometimes you want a local variable
to not be deleted for future use.
 To do this, use the static keyword when you first declare the
variable:
<?php
function myTest()
{
static $x=0;
echo $x;
$x++;
}
myTest(); // 0
myTest(); // 1
myTest(); // 2
?>
PHP Data Types
 Variables can store data of different types, and
different data types can do different things.

 PHP supports the following data types:


• String
• Integer
• Float (floating point numbers - also called double)
• Boolean
• Array
• Object
• NULL
• Resource

41
Fundamental variable types
 Numeric
 integer. Integers (±2 raised 31); values outside this
range are converted to floating-point.
 float. Floating-point numbers.
 Boolean: true or false; PHP internally resolves these
to 1 (one) and 0 (zero) respectively.
 string: String of characters.
 array: An array stores multiple values in one single
variable.(an array of values, possibly other arrays )
 object :an object is a data type which stores data and
information on how to process that data. In PHP, an
object must be explicitly declared.

42
Cont’d …

• Resource:

• A handle to something that is not PHP data (e.g., image


data, database query result).

• Or in other words, Resource is to represent a PHP


extension resource (e.g. Database query, open file,
database connection, etc). You will never directly touch
this type, it will be passed to the relevant functions that
know how to interact with the specified resource.

• Null :

• data type with only one possible value: null. Marks


variables as being empty. Works with the isset() operator;
will return ‘false’ for null. Example: $var=NULL;

43
Cont’d ...
 PHP has a useful function named var_dump() that
prints the current type and value for one or more
variables.
 Arrays and objects are printed recursively with their
values indented to show structure.
$a = 35;
$b = "Programming is fun!"; Output of the code
$c = array(1, 1, 2, 3); int(35)
string(19) "Programming is
var_dump($a,$b,$c); fun!"
array(4) {
[0]=> int(1)
[1]=>int(1)
[2]=>int(2)
[3]=>int(3)
44
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
'I am a string in single quotes'
"I am a string in double quotes"
 The PHP parser determines strings by finding matching
quote pairs. So, all strings must start and finish with the
same type of quote - single or double.
 Only one type of quote mark is important when defining
any string, single (') or double (").
$string_1 = "This is a string in double quotes";
$string_0 = ‘’ // a string with zero characters

45
Cont’d …
 Singly quoted strings are treated almost literally, whereas
doubly quoted strings replace variables with their values
as well as specially interpreting certain character
sequences.
 Strings that are delimited by double quotes (as in "this")
are preprocessed in both the following two ways by PHP:
 Certain character sequences beginning with backslash (\)
are replaced with special characters
 Variable names (starting with $) are replaced with string
representations of their values.
String Concatenation Operator

 To concatenate two string variables together, use the dot


(.) operator:
E.g
<?php
$txt1="Hello World!";
$txt2="What a nice day!";
echo $txt1 ." " .$txt2;
?>
Output
Hello World! What a nice day!
The strlen()function
 The strlen() function is used to find the length of a
string.
E.G
<?php
echo strlen("Hello world!");
?>
Output
12
 The length of a string is often used in loops or other
functions, when it is important to know when the string
ends.
The strpos()function
 The strpos() function is used to search for a string or
character within a string. (first position in the string is
0, and not 1.)
 If a match is found in the string, this function will
return the position of the first match. If no match is
found, it will return FALSE.
E.g
<?php
echo strpos("Hello world!","world"); // output=6
?>
The str_word_count() function
 The PHP str_word_count() function counts the
number of words in a string:
E.g
<?php
echo str_word_count("Hello world!");
//output =2
?>
Reverse a String

 The PHP strrev() function reverses a string:


E.g <?php
echo strrev("Hello world!");
//output=!dlrow olleH
?>

51
The str_replace() function
 The PHP str_replace() function replaces some characters
with some other characters in a string.
<?php
echo str_replace("world", “PHP", "Hello world!");
?> Output: Hello PHP!
 The example below replaces the text "world" with “PHP":
 The PHP string functions are part of the PHP core. No
installation is required to use these functions.
 Refer this page for full string functions
http://www.w3schools.com/php/php_ref_string.asp
PHP Constants
 A constant is an identifier (name) for a simple value.
The value cannot be changed during the script.
 A valid constant name starts with a letter or
underscore (no $ sign before the constant name).
 Note: Unlike variables, constants are automatically
global across the entire script.

 Syntax
define(name, value, case-insensitive)
// name: Specifies the name of the constant
// value: Specifies the value of the constant
//case-insensitive: Specifies whether the constant
name should be case-insensitive. Default is false
Cont’d …
 E. g

<?php
// case-sensitive constant name
define("GREETING", "Welcome to Injibara
University!");
echo GREETING;
?>

54
PHP Operators
 Operators are used to perform operations on variables
and values.
 PHP divides the operators in the following groups:
 Arithmetic operators
 Assignment operators
 Comparison operators
 Increment/Decrement operators
 Logical operators
 String operators
 Array operators
PHP Arithmetic Operators
Operator Name Example Result

+ Addition $x + $y Sum of $x and $y

- Subtraction $x - $y Difference of $x and $y

* Multiplication $x * $y Product of $x and $y

/ Division $x / $y Quotient of $x and $y

% Modulus $x % $y Remainder of $x divided by $y

** Exponentiation $x ** $y Result of raising $x to the $y'th power


(Introduced in PHP 5.6)
PHP Assignment Operators
Assignment Same as... Description

x=y x=y The left operand gets set to the value of


the expression on the right

x += y x=x+y Addition

x -= y x=x-y Subtraction

x *= y x=x*y Multiplication

x /= y x=x/y Division

x %= y x=x%y Modulus
PHP Comparison Operators
Operator Name Example Result
== Equal $x == $y Returns true if $x is equal to $y

=== Identical $x === $y Returns true if $x is equal to $y, and they are of the same
type

!= Not equal $x != $y Returns true if $x is not equal to $y

<> Not equal $x <> $y Returns true if $x is not equal to $y

!== Not identical $x !== $y Returns true if $x is not equal to $y, or they are not of
the same type

> Greater than $x > $y Returns true if $x is greater than $y

< Less than $x < $y Returns true if $x is less than $y

>= Greater than or $x >= $y Returns true if $x is greater than or equal to $y


equal to

<= Less than or equal $x <= $y Returns true if $x is less than or equal to $y
to
PHP Increment / Decrement Operators

Operator Name Description

++$x Pre-increment Increments $x by one,


then returns $x
$x++ Post-increment Returns $x, then
increments $x by one
--$x Pre-decrement Decrements $x by one,
then returns $x

$x-- Post-decrement Returns $x, then


decrements $x by one
PHP Logical Operators
Operato Name Example Result
r
and And $x and $y True if both $x and $y are true

or Or $x or $y True if either $x or $y is true

xor Xor $x xor $y True if either $x or $y is true,


but not both

&& And $x && $y True if both $x and $y are true

|| Or $x || $y True if either $x or $y is true

! Not !$x True if $x is not true


PHP String Operators

Operator Name Example Result

. Concatenat $txt1 . $txt2 Concatenation of


ion $txt1 and $txt2

.= Concatenat $txt1 .= $txt2 Appends $txt2 to


ion $txt1
assignment
PHP Array Operators
Operator Name Example Result
+ Union $x + $y Union of $x and $y
== Equality $x == $y Returns true if $x and $y have
the same key/value pairs
=== Identity $x === $y Returns true if $x and $y have
the same key/value pairs in
the same order and of the
same types
!= Inequality $x != $y Returns true if $x is not equal
to $y
<> Inequality $x <> $y Returns true if $x is not equal
to $y
!== Non-identity $x !== $y Returns true if $x is not
identical to $y
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 - specifies a new condition
to test, if the first condition is false
 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;
}
 Example
<?php
$t = date("H"); //24 hours format of an hour

if ($t < “15") {


echo "Have a good day!";
}
?>
PHP - The if...else Statement
 Syntax
if (condition) {
code to be executed if condition is true;
} else {
code to be executed if condition is false;
}
 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
 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;
}
Example
<?php
$d=date("D"); // A textual representation of a day (three letters)
if($d=="Fri")
echo "Have a nice weekend!";
Else if($d=="Sun")
echo "Have a nice Sunday!";
else
echo "Have a nice day!";
?>
PHP switch statement
Example

<?php
$favcolor = "red";
switch ($favcolor) {
case "red":
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 looping statements
PHP Looping - While Loops
<?php
$i=1;
while($i<=5)
{
echo "The number is " . $i . "<br />";
$i++;
}
?>
PHP Looping - For Loops
E.g
<!DOCTYPE html>
<html>
<body>

<?php
for ($x = 0; $x <= 10; $x++) {
echo "The number is: $x <br>";
}
?>
</body>
</html>
Cont’d ...
 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.
E.g.
<?php
$x=array("one","two","three");
foreach($x as $value)
{
echo $value . "<br />";
}
?>
PHP Arrays
 An array is a data structure that stores one or more
similar type of values in a single value.
 In PHP, there are three types of arrays:
 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 arrays- Arrays containing one
or more arrays
Numeric Array
 A numeric array stores each array element with a numeric
index.
E.g
<html><body>
<?php
$numbers = array( 1, 2, 3, 4, 5);
foreach( $numbers as $value )
{
echo "Value is $value <br/>";
}
?>
</body>
</html>
Associative array

 Associative array will have their index as string so that you can
establish a strong association between key and values.
 To store the salaries of employees in an array, a numerically
indexed array would not be the best choice.
 Instead, we could use the employees names as the keys in our
associative array, and the value would be their respective
salary.
<?php
$salary= array(“abel"=>3200, “Sam"=>3000, “bet"=>3400);
echo "Salary of Abel is ". $salary[‘abel'] . "<br />";
echo "Salary of bet is ". $salary[‘bet'] . "<br />";
echo "Salary of sam is ". $salary[‘sam'] . "<br />";
?>
Multidimensional array
 In a multidimensional 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.
$families = array
(
"Griffin"=>array ("Peter","Lois","Megan"),
"Quagmire"=>array ("Glenn"),
"Brown"=>array("Cleveland","Loretta","Junior")
);
echo "Is " . $families['Griffin'][2] . " a part of the Griffin family?";
<html><body>
<?php /*Accessing multi-dimensional array
values */
$marks = array(
echo "Marks for abel in physics : " ;
"abel" => array( echo $marks['abel']['physics'] . "<br />";
"physics" => 35, echo "Marks for sam in maths : ";
"maths" => 30, echo $marks['sam']['maths'] . "<br />";
"chemistry" => 39 ), echo "Marks for sam in chemistry : " ;
echo $marks['sam']['chemistry'] . "<br
"sam" => array( />";
"physics" => 30, ?> </body></html>
"maths" => 32,
"chemistry" => 29 ),

"beti" => array


(
"physics" => 31,
"maths" => 22,
75
"chemistry" => 39) );
Mixing array types

 We can even mix the two if we'd like


 PHP arrays are a cross between numbered arrays and associative
arrays.
In the example below, three literal arrays are declared as follows:
1. A numerically indexed array with indices running from 0 to 4.
2. An associative array with string indices.
3. A numerically indexed array, with indices running from 5 to 7.
<?php
$array1 = array(2, 3, 5, 7, 11);
$array2 = array("one" => 1,
"two" => 2,
"three" => 3);
$array3 = array(5 => "five", "six", "seven");
Print ($array1[3], $array2["one"], $array3[6]);
?>
Get The Length of an Array
<?php
$cars=array("Volvo","BMW","Toyota");
echo count($cars);
?>
Loop Through an Indexed Array
<?php
$cars=array("Volvo","BMW","Toyota");
$arrlength=count($cars);
for($x=0;$x<$arrlength;$x++)
{
echo $cars[$x];
echo "<br>";
}
?>
Example
<?php
$numbers=array(4,6,2,22,11);
sort($numbers);
$arrlength=count($numbers);
for($x=0;$x<$arrlength;$x++)
{
echo $numbers[$x];
echo "<br>";
}
?>
Loop Through an Associative Array
<?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

 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
PHP Functions

 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

81
Example
<html>
<head>
<title>Writing PHP Function</title>
</head>
<body>
<?php
/* Defining a PHP Function */
function writeMessage()
{
echo "You are really a nice person, Have a nice time!";
}
/* Calling a PHP Function */
writeMessage();
?>
</body>
</html>

82
Example
A simple function that writes a name when it is called:
<html>
<body>
<?php
function writeMyName()
{
echo “abebe belachewu";
}
writeMyName();
?>
</body>
</html>
83
PHP Functions with Parameters
 PHP gives you option to pass your parameters inside a function.

 You can pass any number of parameters your like.

 These parameters work like variables inside your function.

 Following example takes two integer parameters and add them together
and then print them.
<?php
function addFunction($num1, $num2)
{
$sum = $num1 + $num2;
echo "Sum of the two numbers is : $sum";
}
addFunction(10, 20);
?>

84
Example
<html>
<body>
<?php
function writeMyName($fname)
{
echo “$fname <br />";
}
echo "My name is ";
writeMyName(“abebe");
?>
</body>
</html>

85
PHP Functions - Return values
 A function can return a value using the return statement in
conjunction with a value or object .

 Return stops the execution of the function and sends the value back
to the calling code.
 Example
<?php
function add($x,$y)
{ The output of
$total = $x + $y; the code will be:
return $total; 1 + 16 = 17
}
echo "1 + 16 = " . add(1,16)
?>
86
Passing Arguments by Reference

 It is possible to pass arguments to functions by reference.

 This means that a reference to the variable is manipulated


by the function rather than a copy of the variable's value.

 Any changes made to an argument in these cases will


change the value of the original variable.

 You can pass an argument by reference by adding an


ampersand to the variable name in either the function call
or the function definition.
87
Example
<html> addFive( &$orignum );
<head> echo "Original Value is $orignum<br />";
<title>Passing Argument by addSix( $orignum );
Reference</title> echo "Original Value is $orignum<br />";
</head> ?>
<body> </body>
<?php </html>
function addFive($num) Output
{ Original Value is 15
$num += 5; Original Value is 21
}
function addSix(&$num)
{
$num += 6;
}
$orignum = 10;

88
Default values for function parameters
 You can set a parameter to have a default value if the
function's caller doesn't pass it.
 Following function prints “no test “ in case the we does not
pass any value to this function.
<?php
function printMe($param = “No test”)
{
print $param;
}
Output
printMe("This is test"); This is test
printMe(); No test
?>

89
PHP Forms and User Input

 The PHP $_GET and $_POST variables are used to retrieve


information from forms, like user input.

 The most important thing to notice when dealing with HTML forms
and PHP is that any form element in HTML page will automatically
be available to your PHP scripts.
Form example:
<form action="welcome.php" method="post">
Name: <input type="text" name="name" />
Age: <input type="text" name="age" />
<input type="submit" />
</form>

90
PHP Forms and User Input
 The example HTML page above contains two input fields
and a submit button.
 When the user fills in this form and click on the submit
button, the form data is sent to the "welcome.php" file.
 The "welcome.php" file looks like this:
<html>
<body>
Welcome <?php echo $_POST["name"]; ?>.<br />
You are <?php echo $_POST["age"]; ?> years old.
</body>
Welcome John.
</html>
You are 28 years old.

91
PHP $_GET
 The $_GET variable is used to collect values from a
form with method="get".
 The $_GET variable is an array of variable names and
values are sent by the HTTP GET method.
Example
<form action="welcome.php" method="get">

Name: <input type="text" name="name" />

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

<input type="submit" />

</form>
92
Cont’d ….
 When the user clicks the "Submit" button, the URL
sent could look something like this:
localhost/welcome.php?name=Peter&age=37
 The "welcome.php" file can now use the $_GET variable
to catch the form data
 Note that the names of the form fields will automatically
be the ID keys in the $_GET array:
 Welcome <?php echo $_GET["name"]; ?>.<br />
 You are <?php echo $_GET["age"]; ?> years old!

93
Why use $_GET

 Information sent from a form with the GET


method is visible to everyone (it will be displayed
in the browser's address bar)
• So this method should not be used when
sending passwords or other sensitive
information!

 Get method has limits on the amount of


information to send
• The value cannot exceed100 characters.
• So it is not suitable on large variable values.

94
PHP $_POST

 The $_POST variable is used to collect values from a


form with method="post".

 The $_POST variable is an array of variable names and


values are sent by the HTTP POST method.

 Information sent from a form with the POST method is


invisible to others and has no limits on the
amount of information to send.

95
Example
<form action="welcome.php" method="post">
Enter your name: <input type="text" name="name" />
Enter your age: <input type="text" name="age" />
<input type="submit" />
</form>

 When the user clicks the "Submit" button, the URL will
not contain any form data, and will look something like
this:
localhost/welcome.php

96
$-REQUEST

 The PHP $_REQUEST variable contains the


contents of both $_GET and $_POST variables.

 The PHP $_REQUEST variable can be used to get


the result from form data sent with both the GET
and POST methods.

 Example
Welcome <?php echo $_REQUEST["name"]; ?>.<br />

You are <?php echo $_REQUEST["age"]; ?> years old!

97
PHP Include File

 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

98
PHP Include File
 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).

99
Cont’d …
 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.
Save the file as all.php
<a href="default.php">Home</a>
<a href="tutorials.php">Tutorials</a>
<a href="examples.php">Examples</a>
<a href="about.php">About Us</a>
<a href="contact.php">Contact Us</a>
<hr>
<p> add some contents here</p>
100
Cont’d …
 Used to include external PHP file into another PHP code
Example
setdate.php:
<?php $today=getdate(time());?>
footer.php:
<SMALL>Today is <?php print $today[weekday];?></SMALL>
Index.php:
<?php
include ("setdate.php");
?>
<H2>Today's Headline:</H2>
<P ALIGN="center">
<?php
print "World Peace Declared";
?>
</P><HR>
<?php include ("footer.php");
?>
Example
Save the file as header.php
<a href="default.php">Home</a>
<a href="tutorials.php">Tutorials</a>
<a href="examples.php">Examples</a>
<a href="about.php">About Us</a>
<a href="contact.php">Contact Us</a>
Save the file as main.php

<?php include(‘header.php’); ?>


<hr>
<p> add some contents here </p>
102
PHP require( ) Function
 The require() function is identical to include(), except that it handles
errors differently.
 The require() generates a fatal error, and the script will stop.
<?php require(‘header1.php’); ?>
<hr>
<p> add some contents here </p>

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

103
CHAPTER Five
Part 2
Manipulating MySQL
Databases with PHP

Dawed O.

104
What is Database?
 A database is a separate application that stores a
collection of data.
 Relational Database Management Systems (RDBMS) is used
to store data in tables and relations are established using
primary keys or other keys known as foreign keys.

 About MySQL
• most popular database system used with PHP.
• used on the web
• a database system that runs on a server
• ideal for both small and large applications
• very fast, reliable, and easy to use
• uses standard SQL
• compiles on a number of platforms, and use
Using PHP with MySQL Database
 The PHP functions for use with MySQL have the following
general format:
mysql_function(value,value,...);
Or
mysqli_function(value,value,...); //PHP 5 and later

 The second part of the function name is specific to the


function, usually a word that describes what the function
does.
Example:
mysqli_connect($connect); // create connection
mysqli_query($connect,"SQL statement"); // to execute
different sql statements
Open a Connection to MySQL Database
 Before we can access data in the MySQL database, we need
to be able to connect to the server.
 PHP provides mysql_connect() function to open a database
connection. THIS FUNCTION takes five parameters and
returns a MySQL link identifier on success, or FALSE on
failure.

Syntax: $conn=mysql_connect(server, user, password);


 Server (Optional) :The host name running database server. If not
specified then default value is localhost.

 User( Optional): The username accessing the database. If not


specified then default is the name of the user that owns the server
process.

 Password(Optional ):The password of the user accessing the


database. If not specified then default is an empty password.
Closing a connection
 The connection will be closed automatically when the script
ends.
 You can disconnect from MySQL database anytime using
mysql_close() PHP function.

 This function takes a single parameter which is a


connection returned by mysql_connect() function.
Syntax: bool mysql_close ($conn);
 If a resource is not specified then last opened database
connection is closed.
 This function returns true if it closes connection
successfully otherwise it returns false.
Example: Connecting MySQL Server

<html><head><title>Connecting MySQL Server</title></head><body>


<?php
$dbhost = 'localhost';
$dbuser = 'rootbdu';
$dbpass = 'root123';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully <br />';
mysql_close($conn);
?>
</body></html>
Creating MySQL Database using PHP

 PHP uses mysql_query() to create or delete a MySQL


database. This function takes two parameters and returns
TRUE on success or FALSE on failure.
 Generic SQL syntax to Create a database:
Syntax: CREATE DATABASE Database_Name;
 To Create a database we can use the PHP mysql_query()
function
Syntax: bool mysql_query( sql, connection );
 Sql (Required) - SQL query to create or delete a MySQL
database (E.g CREATE DATABASE Database_Name)
 Connection(Optional) - if not specified then last opened
connection by mysql_connect will be used.
Example: Creating a Database
<html><head><title>Creating $sql = 'CREATE DATABASE
MySQL Database</title> DDIT';
</head><body> $retval = mysql_query( $sql,
<?php $conn );
$dbhost = 'localhost'; if(! $retval )
$dbuser = 'rootbdu'; {
$dbpass = 'rootbdu123'; die('Could not create
$conn = mysql_connect($dbhost, database: ' . mysql_error());
$dbuser, $dbpass); }
if(! $conn ) echo "Database DDIT created
{ successfully\n";
die('Could not connect: ' . mysql_close($conn);
mysql_error()); ?>
} </body></html>
echo 'Connected successfully<br />';
Drop Database using PHP
 PHP uses mysql_query function to create or delete a MySQL
database.
 This function takes two parameters and returns TRUE on
success or FALSE on failure.
 Generic SQL syntax to drop a database:
Syntax: DROP DATABASE Database_Name;

 To Drop a database we can use the PHP mysql_query()


function
Syntax: bool mysql_query( sql, connection );
 Sql(Required )- SQL query to create or delete a MySQL
database (E.g 'DROP DATABASE Database_Name’
 Connection(Optional) - if not specified then last opened
connection by mysql_connect will be used.
Example
<html><head><title>Creating MySQL $sql = 'DROP DATABASE DDIT;
Database</title> $retval = mysql_query( $sql, $conn );
</head><body> if(! $retval )
<?php {
die('Could not delete database: ' .
$dbhost = 'localhost'; mysql_error());
$dbuser = 'rootbdu'; }
$dbpass = 'rootbdu123'; echo "Database DDIT deleted
successfully\n";
$conn = mysql_connect($dbhost, $dbuser,
mysql_close($conn);
$dbpass);
?>
if(! $conn ) </body></html>
{
die('Could not connect: ' . mysql_error()); Note: While deleting a
database using PHP script, it
} does not prompt you for any
echo 'Connected successfully<br/>'; confirmation( be careful while
deleting a database)
Selecting a Database using PHP

 Once you get connection with MySQL server, it is required to


select a particular database to work with.
 This is because there may be more than one database
available with MySQL Server.
 PHP provides function mysql_select_db to select a database.
 It returns TRUE on success or FALSE on failure.

Syntax: bool mysql_select_db( db_name, connection );


 db_name(Required)- MySQL Database name to be selected
 connection(Optional) - if not specified then last opened
connection by mysql_connect will be used.
Example
<html><head><title> $seldb=mysql_select_db(
Creating MySQL Database</title> ‘DDIT' );
</head><body>
if(! $seldb )
<?php
$dbhost = 'localhost';
{
$dbuser = 'rootbdu'; die('Could not select a
$dbpass = 'rootbdu123'; database: ' . mysql_error());
$conn = mysql_connect($dbhost, }
$dbuser, $dbpass); echo 'Database DDIT
if(! $conn ){ selected<br />';
die('Could not connect: ' .
mysql_close($conn);
mysql_error()); }
echo 'Connected successfully<br />'; ?>
</body> </html>
MySQL supported Data types

 Reading Assignment
 Numeric Data Types
 Date and time Data Types
 String Types
Creating Tables Using PHP
 Requirements to create a table:
 Name of the table
 Names of fields
 Definitions for each field
 Generic SQL syntax to create a table:
Syntax: CREATE TABLE table_name
(column_name column_type);
 To create new table in any existing database we
can use the PHP mysql_query() function
Syntax: mysql_query( sql, connection ); // Sql
represent create table query
 You have to pass the proper SQL command to
create a table in the second argument of
mysql_query() function.
Example

<html><head><title>Creating MySQL Tables</title>


</head><body>
<?php
$dbhost = 'localhost';
$dbuser = 'rootbdu';
$dbpass = 'rootbdu123';
$conn =mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn ){
die('Could not connect: ' . mysql_error()); }
echo 'Connected successfully<br />';
$sql = "CREATE TABLE Students( "
."Student_Id INT NOT NULL AUTO_INCREMENT, "
."Student_Name VARCHAR(100) NOT NULL, "
."Student_Email VARCHAR(40) NOT NULL, "
."PRIMARY KEY (Student_Id )); ";
mysql_select_db(‘DDIT');
$retval = mysql_query( $sql, $conn );
if(!$retval){
die('Could not create table: ' . mysql_error());
}
echo "Table created successfully\n";
mysql_close($conn);
?>
</body>
</html>
Dropping table using PHP
 It is very easy to drop an existing MySQL table but you need
to be very careful while deleting any existing table because
data lost will not be recovered after deleting a table.
 Generic SQL syntax to create a table
Syntax: DROP TABLE table_name ;
 To drop an existing table in any database you can use the PHP
mysql_query() function.
Syntax: mysql_query( sql, connection ); // Sql represent drop
table query
 You have to pass the proper SQL command to drop a table in
the second argument of mysql_query() function.
Example
<html><head><title>Creating $sql = "DROP TABLE
MySQL Tables</title> Students";
</head><body> mysql_select_db('BDUDB');
<?php $retval = mysql_query( $sql,
$dbhost = 'localhost'; $conn);
$dbuser = 'rootbdu'; if(!$retval )
$dbpass = 'rootbdu123'; {
$conn = mysql_connect($dbhost, die('Could not delete table: ' .
$dbuser, $dbpass); mysql_error());
If(! $conn ) { }
die('Could not connect: ' . echo "Table deleted
mysql_error()); successfully\n";
} mysql_close($conn);
echo 'Connected successfully<br />';
?>
</body></html>
121
Inserting data into MySQL table
 After a database and a table have been created, we can start adding
data in the table.
 Here are some syntax rules to follow:
 The SQL query must be quoted in PHP
 String values inside the SQL query must be quoted
 Numeric values must not be quoted
 The word NULL must not be quoted
 To add a new records into MySQL table we can use SQL INSERT
INTO command.
 Generic SQL syntax of INSERT INTO query
Syntax: INSERT INTO table_name ( field1, field2,..fieldN )
VALUES ( value1, value2,...valueN );
 To insert a data in any table you can use the PHP mysql_query()
function.
Syntax: mysql_query( sql, connection ); // Sql represent insert data query
 You have to pass the proper insert data SQL command in the second
argument of mysql_query() function.
Example: Insert a record in a table
<html><head><title>Insert a record</title>
</head><body>
<?php
if(isset($_POST['add']))
{
$dbhost = 'localhost';
$dbuser = 'rootbdu';
$dbpass = 'rootbdu123';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(!$conn){
die('Could not connect: ' . mysql_error());
}
Cont..
if ($_SERVER["REQUEST_METHOD"] == "POST"){
$student_Name = $_POST['student_Name'];
$student_Email = $_POST['student_Email'];
}
$sql = "INSERT INTO Students "."(student_Name,
student_Email)"
."VALUES "."('$student_Name','$student_Email')";
mysql_select_db('BDUDB');
$retval = mysql_query( $sql, $conn );
if(!$retval ) {
die('Could not enter data: ' . mysql_error()); }
echo "Data entered successfully\n";
mysql_close($conn);
} ?>
Cont..

<form method="post" action="<?php $_PHP_SELF ?>">


<p>Name: <input name="student_Name" type="text"></p>
<p>Email: <input name="student_Email" type="email"></p>
<input name="add" type="submit" value="Add Student"></td>
</tr></table></form>
</body>
</html>
Example 2: Insert.html
<html><body>
<form action="insert.php" method="post">
<p>Firstname: <input type="text" name="First_name"></p>
<p>Lastname: <input type="text" name="Last_name"></p>
<p>Age: <input type="text" name="age"></p>
<input type="submit" name="Add_row" value="Register">
</form>
</body></html>

126
Insert.php
<?php
$dbhost = 'localhost';
$dbuser = 'rootbdu';
$dbpass = 'rootbdu123';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
mysql_select_db('BDUDB');
$sql="INSERT INTO Persons(First_Name,Last_Name, Age)
VALUES('$_POST[First_name]','$_POST[Last_name]','$_POS
T[age]')";
mysql_select_db('BDUDB');
$retval = mysql_query( $sql, $conn );
if(!$retval )
{
die('Could not enter data: ' . mysql_error());
}
echo "1 record added";
mysql_close($conn);
?>127
Fetching Data (Selecting data from
database)

 The SQL SELECT command is used to fetch data from


MySQL database.
 Generic SQL syntax of SELECT command
Syntax: SELECT field1, field2,...fieldN FROM table_name1,
table_name2.[WHERE Clause][OFFSET M ][LIMIT N];
 You can use one or more tables separated by comma.
 To include various condition use a WHERE clause but
WHERE clause is an optional part of SELECT command.
 You can fetch one or more fields in a single SELECT
command.
 You can specify star (*) in place of fields. In this case
SELECT will return all the fields.
Cont..

 You can limit the number of fields returned using LIMIT


attribute (used to limit output when we have large output)
 Assume we want to select records from 1-15 ( inclusive) from
a table called “students”
$sql=‘SELECT * FROM students LIMIT 15’; //will return the
first 15 records
 What if we want to select records from 10-15 (inclusive)? We
can specify by using OFFSET
$sql=‘SELECT * FROM students LIMIT 5 OFFSET 9’; //return
5 records , start on record 10(OFFSET 9)
Fetching Data using PHP

 You can use same SQL SELECT command into PHP function
mysql_query() to execute the select command and later another PHP
function mysql_fetch_array() can be used to fetch all the selected data.
 The mysql_fetch_array() function returns as an associative array, a
numeric array, or both.
 mysql_fetch_array() function returns FALSE if there are no more rows.
Example:
$retval = mysql_query( $sql, $conn );
$row = mysql_fetch_array($retval, MYSQL_ASSOC)
 The constant MYSQL_ASSOC can be used as the second argument to
PHP function mysql_fetch_array(), so that it returns the row as an
associative array.
 With an associative array you can access the field by using their name
instead of using the index.
 PHP provides another function called mysql_fetch_assoc() which also
returns the row as an associative array.
Example
<html>
<head><title> Fetch data from a table</title></head>
<body>
<?php
$dbhost = 'localhost';
$dbuser = 'rootbdu';
$dbpass = 'rootbdu123';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(!$conn)
{
die('Could not connect: ' . mysql_error());
}
$sql='SELECT student_Id,student_Name,student_Email
FROM students';
mysql_select_db(‘DDIT');
Cont..
$retval = mysql_query( $sql, $conn );
if(! $retval )
{ die('Could not get data:' . mysql_error()); }
while($row = mysql_fetch_array($retval, MYSQL_ASSOC)){
echo "Student ID :{$row['student_Id']} <br> "
."Student_Name: {$row['student_Name']} <br> "
."Student_Email: {$row['student_Email']}<br> "
. "--------------------------------<br>"; }
echo "Fetched data successfully\n";
mysql_close($conn);
?> </body>
</html>
Example: Select using mysql_fetch_assoc() function
<html>
<head><title> Fetch data from a table</title></head>
<body>
<?php
$dbhost = 'localhost';
$dbuser = 'rootbdu';
$dbpass = 'rootbdu123';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(!$conn)
{
die('Could not connect: ' . mysql_error());
}
$sql='SELECT student_Id,student_Name,student_Email
FROM students';
mysql_select_db(‘DDIT');
$retval = mysql_query( $sql, $conn );
if(! $retval ){
die('Could not get data:' . mysql_error());
}
while ($row = mysql_fetch_assoc($retval)){
echo "Student ID :{$row['student_Id']} <br> "
."Student_Name: {$row['student_Name']} <br> "
."Student_Email: {$row['student_Email']}<br> "
. "--------------------------------<br>"; }
echo "Fetched data successfully\n";
mysql_close($conn);
?> </body>
</html>
 You can also use the constant MYSQL_NUM, as the second
argument to PHP function mysql_fetch_array().
 This will cause the function to return an array with numeric
index.
Example:
<html>
<head><title> Fetch data from a table</title></head>
<body>
<?php
$dbhost = 'localhost';
$dbuser = 'rootbdu';
$dbpass = 'rootbdu123';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(!$conn)
{
die('Could not connect: ' . mysql_error());
}
$sql='SELECT student_Id,student_Name,student_Email
FROM students';
mysql_select_db(‘DDIT');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{ die('Could not get data:' . mysql_error()); }
while($row = mysql_fetch_array($retval, MYSQL_NUM)){
echo "Student ID :{$row[0]} <br> "
."Student_Name: {$row[1]} <br> "
."Student_Email: {$row[2]}<br> "
. "--------------------------------<br>"; }
echo "Fetched data successfully\n";
mysql_close($conn);
?> </body>
</html>
Releasing Memory
 Its a good practice to release cursor memory at the end of each
SELECT statement(free all memory associated with the result
identifier)
 This can be done by using PHP function mysql_free_result().
Example:
<html>
<head><title> Fetch data from a table</title></head>
<body>
<?php
$dbhost = 'localhost';
$dbuser = 'rootbdu';
$dbpass = 'rootbdu123';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(!$conn)
{
Cont..
$sql='SELECT student_Id,student_Name,student_Email
FROM students';
mysql_select_db(‘DDIT');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{ die('Could not get data:' . mysql_error()); }
while($row = mysql_fetch_array($retval, MYSQL_NUM)){
echo "Student ID :{$row[0]} <br> "
."Student_Name: {$row[1]} <br> "
."Student_Email: {$row[2]}<br> "
. "--------------------------------<br>"; }
mysql_free_result($retval);
echo "Fetched data successfully\n";
mysql_close($conn);
?> </body>
</html>
Using WHERE clause
 We have seen SQL SELECT command to fetch data from MySQL
table. We can use a conditional clause called WHERE clause to filter
out results.
 Using WHERE clause we can specify a selection criteria to select
required records from a table.
 Here is generic SQL syntax of SELECT command with WHERE
Syntax: SELECT field1, field2,...fieldN table_name1,
table_name2...[WHERE condition1 [AND [OR]] condition2..
 You can use one or more tables separated by comma to include various
condition using a WHERE clause.
 You can specify more than one conditions using AND or OR
operators.
 A WHERE clause can be used along with DELETE or UPDATE SQL
command also to specify a condition
Example
<html>
<head><title> Fetch data from a table</title></head>
<body>
<?php
$dbhost = 'localhost';
$dbuser = 'rootbdu';
$dbpass = 'rootbdu123';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(!$conn)
{
die('Could not connect: ' . mysql_error());
}
$sql='SELECT student_Id,student_Name,student_Email FROM
students WHERE student_Name="Beti"';
mysql_select_db(‘DDIT');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{ die('Could not get data:' . mysql_error()); }
while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
echo "Student ID :{$row['student_Id']} <br> "
."Student_Name: {$row['student_Name']} <br> "
."Student_Email: {$row['student_Email']}<br> "
. "--------------------------------<br>";
}
mysql_free_result($retval);
echo "Fetched data successfully\n";
mysql_close($conn);
?>
</body>
</html>
Updating data using PHP

 You can do so by using SQL UPDATE command.


 This will modify any field value of any MySQL table
 Generic SQL syntax of UPDATE command
Syntax:UPDATE table_name SET field1=new-value1,
field2=new-value2 [WHERE Clause];
 You can update one or more field all together and You can
also specify any condition using WHERE clause.
 You can update values in a single table at a time.
 The WHERE clause is very useful when you want to
update selected rows in a table.
 You can use SQL UPDATE command with or without
WHERE CLAUSE into PHP function mysql_query().
Example
<html>
<head><title>Update data</title></head>
<body>
<?php
$dbhost = 'localhost';
$dbuser = 'rootbdu';
$dbpass = 'rootbdu123';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(!$conn)
{
die('Could not connect: ' . mysql_error());
}
$sql='UPDATE Students SET student_Name="Abel"
WHERE student_ID=1';
mysql_select_db(‘DDIT');
$retval = mysql_query($sql, $conn );
if(! $retval )
{
die('Could not update data: ' . mysql_error());
}
echo "Updated data successfully\n";
mysql_close($conn);
?>
Deleting data
 If you want to delete a record from any MySQL table then you
can use SQL command DELETE FROM.
 Generic SQL syntax of DELETE command
Syntax: DELETE FROM table_name [WHERE Clause];
 If WHERE clause is not specified then all the records will be
deleted from the given MySQL table.
 You can specify any condition using WHERE clause.
 You can delete records in a single table at a time.
 The WHERE clause is very useful when you want to delete
selected rows in a table.
 You can use SQL DELETE command with or without WHERE
CLAUSE into PHP function mysql_query().
Example

<html>
<head><title>Update data</title></head>
<body>
<?php
$dbhost = 'localhost';
$dbuser = 'rootbdu';
$dbpass = 'rootbdu123';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(!$conn)
{
die('Could not connect:'.mysql_error());
}
$sql = 'DELETE FROM Students WHERE student_Id=1';
mysql_select_db(‘DDIT');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not delete data:'.mysql_error());
}
echo "Deleted data successfully\n";
mysql_close($conn);
?>
Using LIKE clause
 A WHERE clause with equal sign (=) works fine
where we want to do an exact match.
 The LIKE operator is used in a WHERE clause to
search for a specified pattern in a column.
 Generic SQL syntax of SELECT command
Syntax: SELECT field1, field2,...fieldN
table_name1, table_name2...WHERE field1 LIKE
condition1 [AND [OR]] filed2 = 'somevalue'
 You can use LIKE clause along with WHERE clause
in place of equal sign.
 When LIKE is used along with % sign then it will
work like a meta character search (used to define
wildcards (missing letters) both before and after
the pattern)
Example

<html>
<head><title> Fetch data from a table</title></head>
<body>
<?php
$dbhost = 'localhost';
$dbuser = 'rootbdu';
$dbpass = 'rootbdu123';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(!$conn)
{
die('Could not connect: ' . mysql_error());
}
$sql='SELECT student_Id,student_Name,student_Email
FROM students WHERE student_Name LIKE "%et%"';
mysql_select_db(‘DDIT');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{ die('Could not get data:' . mysql_error()); }
while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
echo "Student ID :{$row['student_Id']} <br> "
."Student_Name: {$row['student_Name']} <br> "
."Student_Email: {$row['student_Email']}<br> "
. "--------------------------------<br>";
}
mysql_free_result($retval);
echo "Fetched data successfully\n";
mysql_close($conn);
?>
Using ORDER BY clause
 sort a result set by adding an ORDER BY clause that
names the column or columns you want to sort by.
 Generic SQL syntax of SELECT command along with
ORDER BY
Syntax:SELECT field1, field2,...fieldN table_name1,
table_name2 ORDER BY field1, [field2...] [ASC [DESC]]
 You can sort returned result on any field provided that
filed is being listed out.
 You can sort result on more than one field.
 You can use keyword ASC or DESC to get result in
ascending or descending order. By default its
ascending order.
 You can use WHERE...LIKE clause in usual way to put
condition.
Example
<html>
<head><title> Fetch data from a table</title></head>
<body>
<?php
$dbhost = 'localhost';
$dbuser = 'rootbdu';
$dbpass = 'root123';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(!$conn)
{
die('Could not connect: ' . mysql_error());
}
$sql='SELECT student_ID,student_Name,student_Email FROM
students ORDER BY student_Id DESC';
mysql_select_db(‘DDIT');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{ die('Could not get data:' . mysql_error()); }
while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
echo "Student_Name: {$row['student_Name']} <br> "
."Student_Email: {$row['student_Email']}<br> "
. "--------------------------------<br>";
}
mysql_free_result($retval);
echo "Fetched data successfully\n";
mysql_close($conn);
?>
</body>
</html>
Example

 Write a PHP code to register new user

154
Example
 Develop a simple user registration system that
authenticates users to add new users.

155
Example
 Lets add a link that displays the detail information
of the users

156
Next Chapter Six

157

You might also like