Chap 5 PHP (1)
Chap 5 PHP (1)
PHP
Dawed O
1
2
Contents
Basics of PHP
Features of PHP
Displaying Errors
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
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
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)
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”
12
What is PHP?
PHP stands for Hypertext Preprocessor
13
What is a PHP File?
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)
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
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.
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:
• 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
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
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 identical $x !== $y Returns true if $x is not equal to $y, or they are not of
the same type
<= Less than or equal $x <= $y Returns true if $x is less than or equal to $y
to
PHP Increment / Decrement Operators
<?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 ),
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.
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
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 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">
</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
94
PHP $_POST
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
Example
Welcome <?php echo $_REQUEST["name"]; ?>.<br />
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.
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
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
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
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)
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
<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
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