0% found this document useful (0 votes)
15 views83 pages

Chapter 5-Server-Side Scripting PHP

Chapter 5 introduces PHP as a server-side scripting language used for developing web applications, highlighting its common uses, features, and basic structure. It covers topics such as data types, variables, operators, control structures, and functions, providing examples and syntax for each concept. The chapter emphasizes PHP's flexibility, integration with databases, and ability to create dynamic web content.

Uploaded by

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

Chapter 5-Server-Side Scripting PHP

Chapter 5 introduces PHP as a server-side scripting language used for developing web applications, highlighting its common uses, features, and basic structure. It covers topics such as data types, variables, operators, control structures, and functions, providing examples and syntax for each concept. The chapter emphasizes PHP's flexibility, integration with databases, and ability to create dynamic web content.

Uploaded by

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

Chapter 5: Server-Side

Scripting - PHP

1
Outline
– Introduction to PHP
– What is PHP
– Common uses of PHP
– Features of PHP
– Basics of PHP
– Data Base manipulation using PHP
What is PHP?
• PHP is a server-side scripting language designed specifically for
the Web (basically used for developing web based software
applications), it stands for Hypertext Preprocessor.
– Server-side scripting is a web server technology in which a user's request is
fulfilled by running a script directly on the web server to generate dynamic web
pages.
– It is usually used to provide interactive web sites that interface to databases or other
data stores.
• Is a programming language that allows web developers to create
dynamic content that interacts with databases.
• Within an HTML page, you can embed PHP code that will be
executed each time the page is visited.
• It is integrated with a number of popular databases, including
MySQL, PostgreSQL, Oracle, Sybase, Informix, and Microsoft
SQL Server.
Common uses of PHP
• PHP performs system functions, i.e. from files on a system it
can create, open, read, write, and close them.
• PHP can handle forms, i.e. gather data from files, save data to
a file, through email you can send data, return data to the user.
• You add, delete, modify elements within your database
through PHP.
• Access cookies variables and set cookies.
• Using PHP, you can restrict users to access some pages of your
website.
• It can encrypt data.
Features of PHP
• Open source
– PHP is an Open Source product. You have access to the
source code. You can use it, modify it, and redistribute it all
without charge.
– Simply stated, you can download and use these
applications without a credit card or a free trial period.
• Flexible for integration with HTML
– One or more PHP scripts can be embedded into static
HTML files and this makes client tier integration easy.
Features of PHP
• Suited to complex projects
– It is a fully featured object-oriented programming
language, with more than 110 libraries of programming
functions for tasks as diverse as math, sorting, creating
PDF documents, and sending email.
• Fast at running scripts
• Platform- and operating-system portable:
– PHP run on many different platforms and operating
systems. PHP can also be integrated with other web
servers.
Basics of PHP
Anatomy of a PHP Script
• A PHP script is a file (ending with a .php extension) consisting of text,
HTML, and PHP instructions interspersed throughout the file.
• The PHP instructions are contained within two HTML style tags;
<?php --- is the opening tag and
----
?> --- is the closing tag.
Steps of Writing a PHP Script
• Finding a Text Editor
• Naming the PHP File, .php Extension.
<?php
statement;
statement;
?>
e.g. <?php
echo "Hello, world.<br />";
?>
Embedding php in an html document

<html>
<head>
<title>Hello World</title>
</head>
<body>
<h1>Hello World example</h1>
<?php
echo "It's such a perfect day!<br />";
?>
</body>
</html>
Comments

• PHP comments can be written on a single line or cover multiple


lines.
• A single-line comment starts with either a hash mark # (like Shell
and Perl comments) or double slashes // (like C++ comments).
• The /* */ (C style) comment can be used as a single-line comment
as well, but it is also useful if you want your comments to cover
multiple lines.
Output statements
• Print and Echo
• The only essential difference between echo() and print() is that
echo allows multiple, comma- separated arguments, and print
doesn’t.
• echo() can take a comma-separated list of string arguments:
– echo $name, $state, $salary;
• print() takes one string argument:
Data Types

PHP supports four core data types:


• Integer
• Float
• double
• String
• Boolean
In addition to the four core data types, there are four other
special types:
• Null
• Array
• Object
• Resources
• Boolean Literals
– Boolean literals (introduced in PHP 4) are logical values
that have only one of two values, true or false, both case
insensitive.
• Special Data Types
Null
– NULL represents “no value,” meaning “nothing,” not
even an empty string or zero.
– It is a type of NULL. An uninitialized variable contains
the value NULL.
Resource
– A resource is a special variable, holding a reference to an
external resource such as a database object or file handler
String Literals and Quoting
• String literals are a row of characters enclosed in either double
or single quotes.
• The quotes must be matched. If the string starts with a single
quote, it must end with a matching single quote; likewise if it
starts with a double quote, it must end with a double quote.
<?php
$name = "Nancy"; // Setting a PHP variable
print "<ol>";
print "<li> $name is my friend.</li>"; // Double quotes
print '<li> $name is my neighbor.</li>'; // Single quotes
print "</ol>";
?>
Variables
• Definition and Assignment
– Variables are fundamental to all programming
languages.
– They are data items that represent a memory storage
location in the computer. Variables are containers
that hold data such as numbers and strings.
– In PHP programs there are three types of variables:
1.Predefined variables
2.User defined variables
3.Form variables related to names in an HTML
form
Variables(Cont.)

• Variables have a name, a type, and a value.


• $num = 5; // name: "$num", value: 5, type: numeric
• $friend = "Peter"; // name: "$friend", value: "Peter", type: string
• $x = true; // name: "$x", value: true, type: boolean
Valid Variable Names Invalid Variable Names
$name1 $10names
$price_tag box.front
$_abc $name#last
$Abc_22 A-23
$A23 $5
Declaring and Initializing Variables
Format
• $variable_name = value;
• To declare a variable called firstname, you could say:
$first_name="Ellie";
Displaying Variables
• The print and echo Constructs
• echo() can take a comma-separated list of string arguments:
– echo $name, $state, $salary;
• print() takes one string argument:
– print $name;
• However, the concatenation operator can be used to print
mutliple strings or strings containing multiple variables:
– print $name . $state . $salary;
– echo $name . $state . $salary;
References
• Another way to assign a value to a variable is to create a
reference.
• A reference is when one variable is a pointer to another
variable; that is, they point to the same underlying data.
• <?php
$husband = "Honey"; // Assign the value "Honey" to $husband
$son = & $husband; // Assign a reference to $son. Now
$son is a reference for $husband. They reference the same
data.
print "His wife calls him $husband, and his Mom calls
him$son.
What Is a Constant?
• Unlike variables, a constant is a value that, once set, cannot be changed or
unset during the execution of your script
• Creating Constants with the define () Function
Syntax: define(name,value);
define(‘pi’,3.14);
<?php
define('ISBN', "0-13-140162-9");
define('TITLE', "JavaScript by Example" );
if ( defined('ISBN') and defined('TITLE')){
print ISBN . "<br />";
print TITLE . "<br />";
}
define('TITLE', "PHP by Example"); // Can't change TITLE,and print
TITLE;
?>
PHP - Operator
• What is Operator? Let us take this expression 4 + 5
is equal to 9. Here 4 and 5 are called operands and +
is called operator. PHP language supports following
type of operators.
– Arithmetic Operators
– Comparison Operators
– Logical (or Relational) Operators
– Assignment Operators
– Conditional(or ternary) Operators

18
• Arithmetic Operators
– The following arithmetic operators supported by PHP
language : +,-,*,%,++,--
• Comparison Operators
– The following comparison operators supported by PHP
language: ==,!=,>,<,<=,>=
• Logical Operators
– The following Logical operators supported by PHP
language: &&,||,!,and,or
• Assignment Operators
– The following assignment operators supported by PHP language: =,
+=,-=,*=,/=,%=
• The Conditional Operator
– The conditional operator is called a ternary operator because it requires
three operands. It is often used as a shorthand method for if/else
conditional statements
19
The Conditional Operator
• This first evaluates an expression for a true or false value
and then execute one of the two given statements
depending upon the result of the evaluation.
Format
conditional expression ? expression : expression
Examples:
$x ? $y : $z If $x evaluates to true, the value of the
expression becomes $y, else the value of the
expression becomes $z.
$big = ($x >$y)?$x :$y If x is greater than $y, $x is
assigned to variable $big, else $y is assigned to
variable $big.

20
Control structures
• Determines whether a block of statements will be executed.
• if statement
if (condition)
{ statements; }
• if - else statement
if (condition)
{ statements1; }
else
{ statements2; }
• if - else - if statement
if (condition) { statements1; }
elseif (condition) { statements2; }
elseif (condition) { statements3; }
else{ statements4; } 21
The switch Statement
switch (expression)
{
case label :
statement(s);
break;
case label :
statement(s);
break;
---
---
default :
statement;
}
22
The switch Statement

Example:
$color=“blue”;
switch ($color)
{
case "red":
print "Hot!";
break;
case "blue":
print "Cold.";
break;
default:
print "Not a good choice.";
break;
}

23
Loop statements
• Loops are used to execute a segment of code repeatedly until some condition is
met
• PHP’s basic looping:-
• while loop
while (condition)
{
statements;
increment/decrement counter;
}
• do - while loop
do
{
statements;
}
while (condition);
• for loop
for (initialize; condition; increment/decrement) 24
Loop statements(cont.)
• foreach Loop: The foreach statement is used to loop through arrays.
• The foreach loop is designed to work with arrays and works only
with array.
• For each pass the value of the current array element is assigned to
$value and the array pointer is moved by one and in the next pass
next element will be processed.
$array_name=array( item1, item2, item3, ...);
foreach ($array_name as $value)
{
do-something with the element's value;
}
Example:
$fruit =array(“orange”, “banana”, “strawberry”,);
foreach ( $fruit as $fruit_list)
{
25
echo $Fruit_list. "<br />";
The break statement
• The PHP break keyword is used to terminate the execution of a loop prematurely.
• The break statement is located inside the statement block. It gives you full control
and whenever you want to exit from the loop you can come out. After coming out
of a loop immediate statement to the loop will be executed.
• Example: In the following example condition test becomes true when the counter
value reaches 3 and loop terminates.
<html><body>
<?php
$i = 0; Output
Value is 1
while( $i < 10) Value is 2
{
$i++;
if( $i == 3 )break;
echo (“Value is $i”);
}
?>
26
</body></html>
The continue statement
• The PHP continue keyword is used to stop the current iteration of a loop
but it does not terminate the loop.
• Just like the break statement the continue statement is located inside the
statement block containing the code that the loop executes, preceded by a
conditional test. For the pass encountering continue statement, rest of the
loop code is skipped and next pass starts.
• Example: In the following example loop prints the value of array but for
which condition becomes true it just skip the code and next value is printed.
Output
<html><body> Value is 1
<?php Value is 2
$array = array( 1, 2, 3, 4, 5); Value is 4
Value is 5
foreach( $array as $value ) {
if( $value == 3 )continue;
echo "Value is $value <br />";
}
?> 27
Arrays in PHP
Two types of array:
• Numeric Array:- an array indexed by a number.
• Associative Array:- an array indexed by a string.

Syntax:
$array_name = array(value1, value2, value3 ...);
$array_name = array(key=>value, key=>value, ...);
Example:
$colors = array('red', 'green', 'blue');
$colors = array(1 => 'red', 2 => 'green', 3 => 'blue');
28
Let’s look at the following Example, which shows a numeric
array, an array indexed by number.
<html>
<head><title>Array of Products</title></head>
<body bgcolor="lightgreen">
<?php
$products=array('Pen','Pencil', 'Book', 'Exersice book');
echo "<b>Product list</b><br/>";
echo "\$products[0] is $products[0].<br/>";
echo "\$products[1] is $products[1].<br/>";
echo "\$products[2] is $products[2].<br />";
echo "\$products[3] is $products[3].<br />";
?>
</body> 29
Now let’s look at the following Example, which
shows an associative array, an array indexed by a
string.
<?php
$show=array( 'Title'=>'Aga-Boom','Author'=>
'Dmitri Bogatirev','Genre'=> 'Physical comedy',);
echo "\$show is $show.<br />\n";
?>
$show['Title'] is <?=$show['Title']?>.<br />
$show['Author'] is <?=$show['Author']?>.<br />
$show['Genre'] is <?=$show['Genre']?>.<br />
30
PHP - Functions
• A function is a piece of code which takes one more input in the form of
parameter and does some processing and returns a value.
– Creating a PHP Function and Calling a PHP Function
• function name should start with keyword function and all the PHP
code should be put inside { and } braces.
<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();
?> 31
PHP Functions with Parameters

• PHP gives you option to pass your parameters inside a function.


• You can pass as many as parameters your like. These parameters
work like variables inside your function.
<html><head>
<title>Writing PHP Function with Parameters</title>
</head>
<body>
<?php
function addFunction($num1, $num2) {
$sum = $num1 + $num2;
echo "Sum of the two numbers is : $sum";
}
addFunction(10,20);
?>
32
</body></html>
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.
function goodbye( &$greeting ) {
$greeting = "See you later";
}
$myVar = "Hi there";
goodbye( $myVar );
echo $myVar; // Displays “See you later”
– Here we created a function, goodbye(), that accepts a reference to a
variable. The reference is stored in the parameter $greeting. The
function assigns a new value ("See you later") to $greeting, which
changes the value stored in the variable that was passed to the 33
<html>
<head>
<title>Passing Argument by Reference</title>
</head>
<body>
<?php
function addFive($num) {
$num += 5;
}
function addSix(&$num) {
$num += 6;
}
$orignum = 10;
addFive( $orignum );
echo "Original Value is $orignum<br />";
addSix( $orignum );
echo "Original Value is $orignum<br />";
?>
</body> 34
</html>
PHP Functions returning value
• A function can return a value using the return
statement in conjunction with a value. return
stops the execution of the function and sends the
value back to the calling code.
• You can return more than one value from a
function using return array(1,2,3,4).
• Following example takes two integer parameters
and add them together and then returns their sum
to the calling program. Note that return keyword
is used to return a value from a function.
35
<html>
<head>
<title>Writing PHP Function which returns value</title>
</head>
<body>
<?php
function addFunction($num1, $num2) {
$sum = $num1 + $num2;
return $sum;
}
$return_value = addFunction(10, 20);
echo "Returned value from the function : $return_value";
?>
</body>
</html>
36
Predefined variables
• PHP provides a large number of predefined variables to any
script which it runs.
• 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.
• All the following variables are automatically available in every
scope.
• $GLOBALS: is a PHP super global variable which is used to
access global variables from anywhere in the PHP script (also
from within functions or methods).
• PHP stores all global variables in an array called
$GLOBALS[index]. The index holds the name of the variable.
37
Example
<?php
$x = 75;
$y = 25;
function addition() {
$GLOBALS['z'] = $GLOBALS['x'] + $GLOBALS['y'];
}
addition();
echo $z;
?>
In the example, since z is a variable present within the
$GLOBALS array, it is also accessible from outside the
function!
38
PHP Superglobals
• PHP provides a large number of predefined variables. All the following variables
are automatically available in every scope.
• $_SERVER is a PHP super global variable which holds information about
headers, paths, and script locations.
• Some of the most important elements that can go inside $_SERVER:
– $_SERVER['PHP_SELF']:Returns the filename of the currently executing
script.
– $_SERVER['SERVER_ADDR']:Return IP address of the server under
which the current script is executing.
– $_SERVER['SERVER_NAME']:Return name of the server host under
which the current script is executing.
– $_SERVER['REQUEST_METHOD']:Returns the request method used to
access the page (such as POST).
– $_SERVER['HTTP_USER_AGENT']: This is a string denoting the user
agent being which is accessing the page.
– $_SERVER['REMOTE_PORT']:The port being used on the user's machine
to communicate with the web server.
– $_SERVER['HTTP_REFERER']:Returns the complete URL of the current
39
page.
PHP Superglobals
• $_GET: used to collect form data after submitting an HTML form
with method="get".
• $_POST: is widely used to collect form data after submitting an
HTML form with method="post". $_POST is also widely used to
pass variables.
• $_FILES: used to uploaded file.
• $_REQUEST: is used to collect data after submitting an HTML
form.
• $_COOKIE: An associative array of variables passed to the
current script via HTTP cookies.
• $_SESSION: An associative array containing session variables
available to the current script.
• $php_errormsg: is a variable containing the text of the last error
message generated by PHP.
40
PHP Per-defined function : PHP String functions

• PHP provides different functions for manipulating strings.


1. The strlen() function
• The PHP strlen() function returns the length of a string (number of
characters).
Example:
<?php
echo strlen("Hello world!"); // outputs 12
?>
2. The str_word_count() function
• The PHP str_word_count() function counts the number of words in a string:
Example:
<?php
echo str_word_count("Hello world!"); // outputs 2
?>

41
PHP Per-defined function : PHP String functions
3. The
strrev() function
The PHP strrev() function reverses a string:
Example:
<?php
echo strrev("Hello world!"); // outputs !dlrow olleH
?>
4. The strpos() function: searches for a specific text within a string.
• If a match is found, the function returns 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"); // outputs 6
?>
5. The str_replace()
• The PHP str_replace() function replaces some characters with some other characters in
a string.
Example:
<?php
echo str_replace("world", "Dolly", "Hello world!"); // outputs Hello Dolly! 42
PHP 5 Array Functions

• PHP array() Function: is used to create an array.


– Syntax for indexed arrays:
array(value1,value2,value3,etc.);
– Syntax for associative arrays:
array(key=>value,key=>value,key=>value,etc.);
• PHP array_change_key_case() Function: Changes all keys in an
array to lowercase or uppercase
– array_change_key_case(array,case);
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
print_r(array_change_key_case($age,CASE_UPPER));
• PHP array_pop() Function: Deletes the last element of an array.
– array_pop(array)
• PHP array_push() Function: Inserts one or more elements to the
end of an array
43
– array_push(array,value1,value2...)
Form Processing using PHP

44
Retrieve data from html forms
• Setting up the HTML form
– To set up a form for server processing and data retrieval, two
important form attributes that controls how the form data is
processed whenever it is submitted must be specified. These two
form attributes are:
– Method Attributes
– Action Attributes
<form action="" method=""> ... </form>
• Action Attributes: specifies the PHP script file location for
processing when it is submitted.
• Method Attributes: specifies what type of method the form will
use to send the data. We have two methods, the GET and POST.
– Note: By default, if no method is specified, the GET method is used.
• Setting access keys for the form data by using the element's name
45
attribute
Retrieve data from html forms
• Name attribute
– The element's name attribute ( name="unique-name-
here" ) value is used by PHP as key to enable access to the
data value of the specified form field element when you
submit the form.
– Without the name attribute specified for each element
contained in the form, PHP can't access that element form
data value after the form has been submitted to the server
because its key is undefined.
<input type="text" name="unique-name-here" />

46
Retrieve data from html forms
• How form data is sent
– Client browsers can send information to a web server in
two different ways:
• GET Method
• POST Method
• GET Method: This method instructs the browser to send the information
(the name/value pairs) through the URL parameter by appending it to the
page request.
Example: How the form GET method data is submitted

• How to retrieve form data sent via GET


– PHP provides a super global variable, called $_GET. PHP uses
this $_GET variable to create an associative array with keys to 47
access all the sent information (form data ).
The GET method sends form input in the URL.

48
Retrieve data from html forms
Retrieve form data sent via GET
<form action=“Get-method.php" method="get">
Firstname:<input type="text" name="firstname">
Lastname:<input type="text" name="lastname">
<input type="submit" value="submit" name="submit">
</form>
Get-method.php look like this
<?php
if( isset( $_GET['submit'] ) )
{
$FN=$_GET['firstname'];
$LN=$_GET['lastname'];
echo 'Your name is ' . $FN . ' ' . $LN;
}
?> N:B The PHP isset() function is used to determine if a variable is
set and is not null. 49
Using the POST

• POST method sends information via HTTP header. All


name/value pairs sent through this method is invisible to
anyone else since all the information are embedded within
the body of the HTTP request
• When you submit a form to a server through the POST
method, PHP provides a super global variable called
$_POST.
• The $_POST variable is used by PHP to create an
associative array with an access key ($_POST['name as
key']).
• The key is created automatically by PHP when the form is
submitted. PHP uses the form field element name attribute
(name="unique-name-here") to create the key.
50
The POST method sends form input in an HTTP header.

• If using the POST method, the METHOD attribute


must be added to the HTML <form> tag
METHOD="POST" (case insensitive).

51
Using the POST
<form action="post-method.php" method="post">
<input type="text" name="firstname"/>
<input type="text" name="lastname" />
<input type="submit" name="submit" />
</form>
post-method.php look like this
<?php
$FN = $_POST['firstname'];
$LN = $_POST['lastname'];
echo 'Your name is ' . $FN . ' ' . $LN;
?>

52
The $_REQUEST variable
• The $_REQUEST variable is another PHP superglobal variable
that you can use to dynamically retrieve form data sent from
both Form GET and POST methods.
<form action="request-variable.php" method="post">
<input type="text" name="firstname" />
<input type="text" name="lastname" />
<input type="submit" name="submit" />
</form>
request-variable.php look like this
<?php
$firstname = $_REQUEST['firstname'];
$lastname = $_REQUEST['lastname'];
echo 'Your name is ' . $lastname .' ' . $firstname;
?> 53
Example
<html>
<head>
<title>Simple HTML Form</title>
</head>
<body bgcolor="lightblue"><font size="+1">
<form action=“form_example.php“/><p>
please enter your name: <br />
<input type="text" size=30 name="your_name" /><br />
please enter your phone number: <br />
<input type="text" size=30 name="your_phone" /><br />
<input type=submit value="submit" />
</form>
</body> 54
(The PHP Script)

form_example.php
<?php
extract($_REQUEST);
print "Your name is $your_name. <br />";
print "Your phone number is $your_phone.";
?>

55
Example 2
<html>
<body>
<form method="post" action="account.php">
Username<input type="text" name="uname"><br/>
Password<input type="password" name="pass"><br/>
<input type="submit" value="login">
</form>
</body>
</html>
#account.php
<?php
$u=$_POST['uname'];
$p=$_POST['pass'];
echo $u," ",$p;
?>
56
Data Base manipulation using PHP
Connecting PHP to MySQL Database

The client/server architecture


• To communicate with the MySQL server, you will need a language, and SQL
(Structured Query Language) is the language of choice for most modern
multiuser, relational databases.
MySQL
• Easy to Use
• Large Community of Developers
• Open Source License
• Commercial License
• Scalability
Connecting PHP to MySQL Database
The Anatomy of a Relational Database
• What makes up a database? The main components of an
RDBMS are:

a. The database server

b. The database

c. Tables

d. Records and fields

e. Primary key

f. Schema
The Anatomy of a Relational Database

The Database Server


• The database server is the actual server process running the
databases.
• It controls the storage of the data, grants access to users, updates
and deletes records, and communicates with other servers
The Database
• A database is a collection of related data elements, usually
corresponding to a specific application
Tables
• Each database consists of two-dimensional tables. In fact, a
relational database stores all of its data in tables, and nothing
more
Records and Fields
• A table has a name and consists of a set of rows and columns. It
resembles a spreadsheet where each row, also called a record, is
comprised of vertical columns, also called fields.
SQL Language
• The standard language for communicating with
relational databases is SQL, the Structured Query
Language.
• SQL is an ANSI (American National Standards
Institute) standard computer language, designed to be
as close to the English language as possible, making it
an easy language to learn.
• The standard basic commands for querying a database
such as SELECT, INSERT, DELETE, UPDATE,
CREATE, and DROP will handle most of the essential
tasks you will need to perform database operations.
SQL Data Manipulation Language (DML)

• SQL is a nonprocedural language providing a syntax


for extracting data, including a syntax to update,
insert, and delete records.
• These query and update commands together form
the Data Manipulation Language (DML) part of
SQL.
• Some of SQL commands:
a. SELECT— Extracts data from a database table.
b. UPDATE— Updates data in a database table.
c. DELETE— Deletes data from a database table.
d. INSERT INTO— Inserts new data into a database table
The SELECT Command
Format
SELECT column_name(s) FROM table_name
Example:
SELECT LastName, FirstName, Address FROM Students;
The INSERT Command
• Format
• INSERT INTO table_name VALUES (value1, value2,....)
• INSERT INTO Shippers (CompanyName, Phone) VALUES ('Canada Post', '416-
555-1221');
The UPDATE Command
• UPDATE table_name SET column_name = new_value WHERE column_name =
some_value
Example:
• UPDATE orders SET DispatchCountry=“Ethiopia" WHERE CustomerId=‘E0023';
The DELETE Statement
• DELETE FROM table_name WHERE column_name = some_value
• DELETE FROM Shippers WHERE CompanyName='Canada Post';
SQL Data Definition Language

• The Data Definition Language (DDL) part of SQL


permits database objects to be created or destroyed.
• The most important data definition statements in SQL
are:
– CREATE TABLE— Creates a new database table.
– ALTER TABLE— Alters (changes) a database table.
– DROP TABLE— Deletes a database table.
– CREATE INDEX— Creates an index (search key).
– DROP INDEX— Deletes an index.
Connecting PHP to MySQL Database

• PHP provides various functions to access the MySQL database


and to manipulate the data records inside the MySQL
database. You would require to call the PHP functions in the
same way you call any other PHP function.
• The PHP functions for use with MySQL have the following
general format − mysql_function(value,value,...);
• 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);
mysqli_query($connect,"SQL statement");
Connecting PHP to MySQL Database
1. Open a Connection to MySQL
– Before we can access data in the MySQL database, we need to be
able to connect to the server:
– To establish a connection to the MySQL database server from your
PHP script, use the PHP mysql_connect() function.
Syntax:
resource mysql_connect (server, username, password)
Example:
$link = mysql_connect("localhost", "root", "password");
• The first argument is the host server where the MySQL server
will be running.
• The second argument is the username, the default value for the
name of the owner of the server process.
• The next argument is the password, if there is one.
Connecting PHP to MySQL Database
• When a Web page or PHP script ends, the database is
automatically closed and the resource that links to it is
released, so that if you start another page you will have to
reconnect to the database.
• If you want to close the database before the program
ends, PHP provides the mysql_close() function.
• The mysql_close() function closes the connection to the
MySQL server referenced by the link.
Format
bool mysql_close ( [resource link_identifier]
Example:
• mysql_close($link);
Connecting PHP to MySQL Database
2. Choosing the Database
• Once connected to the database server, the next step is to set the
database that you will be using.
• The mysql_select_database() function is used to select a
MySQL database.
Syntax:
mysql_select_db (database_name, MySQL connection );
Example:
$link = mysql_connect(‘localhost', ‘root', ‘ ');
$db_selected =mysql_select_db(‘db_name', $link);
• The first argument is the name of the database. The second
argument is the MySQL connection (the link) established when
the mysql_connect() function was executed.
Connecting PHP to MySQL Database
3. Executing SQL Statements (INSERT, UPDATE, DELETE)
• Once connected to the database server, and having selected a
database, it is time to start executing SQL commands.
• PHP provides the mysql_query() function to perform database
queries. You must have adequate permissions to execute
queries on a given database .(“The Grant and Revoke
Commands”).
Syntax:
resource mysql_query (query )
Example:
$result = mysql_query("SELECT CompanyName, Phone FROM
Shippers");
$result =mysql_query("DESCRIBE Shippers");
Connecting PHP to MySQL Database
Retrieving the Query Results (SELECT)
• SQL commands INSERT, UPDATE, and DELETE do not return
any data
• SELECT statement normally returns a set of data records,
called the result-set
• Syntax:
resource mysql_query (query );
• Example:
$result_set = mysql_query( "SELECT sid, name FROM
students" );
• To display the result-set, PHP has provided a number of
functions including mysql_result(),mysql_fetch_array(), and
mysql_fetch_row().
Retrieving the Query Results (SELECT)
• The mysql_fetch_row() Function
– The mysql_fetch_row() function is used to extract
one record of the data from the result-set.
Format
array mysql_fetch_row ( resource result )
Example:
$result_set = mysql_query($query_string)
$record = mysql_fetch_row( $result_set);
– The $result_set variable is assigned the value returned
from mysql_query() function, a numeric array.
Retrieving the Query Results (SELECT)
• The mysql_fetch_assoc() Function
– In the previous example we fetched a record from the record
set and the record returned was a numerically indexed array.
– However, PHP also supports associative arrays, which are
sometimes much easier to use.
– The mysql_fetch_assoc() function is very similar to
mysql_fetch_row() except that the result returned is an
associative array.
Format
array mysql_fetch_assoc ( resource result )
Example:
$record = mysql_fetch_assoc( $record_set )
Retrieving the Query Results (SELECT)

• Mysql_fetch_array( ) function
– Fetch a result row as an associative array, a numeric array,
or both
Syntax:
• array mysql_fetch_array( resource result )
Example:
• $record=mysql_fetch_array($record_set)
• mysql_num_rows()
– returns the number of rows in the result-set
– $number_of_rows = mysql_num_rows( $result_set )
• mysql_num_fields()
– returns the number of fields in a table
– $number_of_fields = mysql_num_fields( $result_set )
• mysql_field_name()
– returns the name of a specific field
– $field_name = mysql_field_name( $result_set, $index )
Retrieving the Query Results (SELECT)
• The mysql_num_rows() Function
– The mysql_num_rows() function returns the number of rows in the
result-set.
Format
int mysql_num_rows( resource result )
Example:
$number_of_rows = mysql_num_rows( $result_set )
• The mysql_num_fields() Function
– The mysql_num_fields() function returns the number of fields in a
table and the mysql_field_name() function returns the name of a field.
Format
int mysql_num_fields( resource result )
Example:
$number_of_fields = mysql_num_fields( $result_set )
Retrieving the Query Results (SELECT)

• The mysql_field_name() Function


The mysql_field_name() function returns the name of a
specific field.
Format
string mysql_field_name( resource result, int field_offset )
Example:
$field_name = mysql_field_name( $result_set, $index )
• mysql_error()
– returns the text of the error message generated by the
MySQL server
Web security and cryptography theory
• Cryptography
– The process of writing and reading secrete message or codes
– The science or study of secret communications
– Classically stared thousand of years ago and advanced during ware of
20th century
• Encryption: is an algorithm that can encode a message such that it
is only readable by authorized person.
– To change information from one form to another especially to hide its
meaning
• En:to make
• Crypto: secret or hidden
• A pair of algorithms such that to output of cipher text of the
encoding algorithm can be efficiently transform to the original
text by the decoding algorithm.
Web security and cryptography theory

• Cipher
– A way of changing a message to keep it secret
– An algorithm used to encrypt or decrypt
• Role of cryptography
– Secure communications from tired parties
– Confidentiality of communication
PHP Built-in Encryption Functions
• PHP ships with three built-in encryption functions:
– md5(),
– crypt(), and
– sha1().
1. The md5() function :The function calculates the MD5 hash of a
supplied string using the MD5 Message-Digest algorithm.
Format :
string md5(string $str [, bool $raw_output ])
• The $str argument represents the string to be encrypted.
• If you pass FALSE in the $raw_output argument (the default), the
function returns the hash as a 32-character hexadecimal number.
• If you pass TRUE then the function returns a 16-byte raw binary
value
PHP Built-in Encryption Functions
2. The PHP crypt() function :It returns an encrypted string
using the standard Unix DES-based encryption algorithm (or
alternative algorithms that may be available on the system).

Format :string crypt (string $str [, string $salt ])

• The $str argument is the string to be encrypted and the


optional $salt argument is a string on which to base the
encryption.
• If you don’t provide the salt string, PHP will randomly
generate one each time you call this function.
PHP Built-in Encryption Functions

3. The PHP sha1() function : The function returns the SHA-1


hash as a string.
Format string sha1 (string $str [, bool $raw_output ])
• the $str argument represents the input string.
• If you set the optional $raw_output argument to TRUE, the
function returns the sha1 hash in raw binary format with a
length of 20 characters; if you set it to FALSE, it returns a 40-
character hexadecimal number.
Example
<?php
$cryptKey= 'qJB0rGtIn5UB1xG03efyCp';
$password = 'Hellow@world';
//Calculates the md5 hash
$md5_data = md5($password);
//This function encrypts data
$crypt = crypt($password,$cryptKey);
//Calculate the sha1 hash
$sha1 = sha1($password);
echo "md5: ". $md5_data."<br/>crypt: ".
$crypt."<br/>sha1: ".$sha1;
?>
Question ?

83

You might also like