chapter 5 Server-Side Scripting (PHP).pdf

burasyacob012 725 views 80 slides Apr 15, 2024
Slide 1
Slide 1 of 80
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19
Slide 20
20
Slide 21
21
Slide 22
22
Slide 23
23
Slide 24
24
Slide 25
25
Slide 26
26
Slide 27
27
Slide 28
28
Slide 29
29
Slide 30
30
Slide 31
31
Slide 32
32
Slide 33
33
Slide 34
34
Slide 35
35
Slide 36
36
Slide 37
37
Slide 38
38
Slide 39
39
Slide 40
40
Slide 41
41
Slide 42
42
Slide 43
43
Slide 44
44
Slide 45
45
Slide 46
46
Slide 47
47
Slide 48
48
Slide 49
49
Slide 50
50
Slide 51
51
Slide 52
52
Slide 53
53
Slide 54
54
Slide 55
55
Slide 56
56
Slide 57
57
Slide 58
58
Slide 59
59
Slide 60
60
Slide 61
61
Slide 62
62
Slide 63
63
Slide 64
64
Slide 65
65
Slide 66
66
Slide 67
67
Slide 68
68
Slide 69
69
Slide 70
70
Slide 71
71
Slide 72
72
Slide 73
73
Slide 74
74
Slide 75
75
Slide 76
76
Slide 77
77
Slide 78
78
Slide 79
79
Slide 80
80

About This Presentation

kljl


Slide Content

Chapter Five
Server-Side Scripting (PHP)
1
Compiled by Dawit Uta. (M. Tech.)
Computer Science Department, WSU
website address: www.davidtechnotips.com

Chapter 4
Basics of PHP
In this chapter you will learn basics of php:-
Introduction
What is PHP?
Features of PHP
Setting up PHP with apache
Basic PHP syntax
PHP comments, variables and its type
Control structures
Retrieving html form data
Arrays and Functions
Compiled by: Dawit U. (M. Tech.) 2

What is PHP?
Introduction
PHP(HypertextPreprocessor)
Itisaserversidescriptinglanguagethatcanbeembedded
inHTML.
PHPisaprogramminglanguagethatallowswebdevelopers
tocreatedynamiccontentthatinteractswithdatabases.
Itisbasicallyusedfordevelopingwebbasedsoftware
applications,sessiontracking,forbuildingentiree-
commercesites.
PHPcoderunsontheserverandisstoredinphpscriptsthat
usuallyhavea.phpfileextension.
PHPstartedoutasasmallopensourceprojectthatevolved
asmoreandmorepeoplefoundouthowusefulitwas.
PHPwascreatedbyRasmusLerdorfin1994butappeared
inthemarketin1995.PHP8.1isnewversionwithmajor
updateandmanynewfeatures.
Compiled by: Dawit U. (M. Tech.) 3

PHPsupportsamajorprotocolssuchasPOP3,IMAP,andLDAP.
WhentheserverrunsaPHPscripttheendresultisalways
pureHTMLandCSS.
SoeveryPHPscriptultimatelygetsturnedintoHTMLandCSS
onceit’sfinishedrunningontheserver.
Itisintegratedwithanumberofpopulardatabases,including
ᴥMySQL
ᴥOracle
ᴥPostgreSQL
ᴥInformix
ᴥMicrosoftSQLServer
ᴥMSAccess
Compiled by: Dawit U. (M. Tech.) 4

Common applications 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 we can send data, return data to the user.
We can add, delete, modify elements within database.
Using PHP, we can restrict users to access some pages of your
website.
Add login feature to website
Encrypt data Etc…
Compiled by: Dawit U. (M. Tech.) 5

Why PHP ? What are PHP Features
PHP is very popular language because of its simplicity and
open source. There are some important features of PHP given
below:
Compiled by: Dawit U. (M. Tech.) 6

Why PHP ? What are PHP Features cont…
Performance:
PHP script is executed much faster than those scripts which are
written in other languages such as JSP and ASP.
PHP uses its own memory, so the server workload and loading
time is automatically reduced, which results in faster processing
speed and better performance.
Open Source:
PHP source code and software are freely available on the web.
You can develop all the versions of PHP and its components
according to your requirement without paying any cost from
official web address www.php.net
Familiarity with syntax: PHP has easily understandable syntax.
Programmers are comfortable coding with it.
Compiled by: Dawit U. (M. Tech.) 7

Why PHP ? What are PHP Features cont…
Platform Independent:
PHP is available for WINDOWS, MAC, LINUX & UNIX
operating system.
A PHP application developed in one OS can be easily executed in
other OS also.
Database Support:
PHP supports all the leading databases such as MySQL, SQLite,
ODBC, Postgresql, Oracle etc.
Error Reporting -
PHP has predefined error reporting constants to generate an error
notice or warning at runtime. E.g., E_ERROR, E_WARNING,
E_STRICT, E_PARSE
Embedded
PHP code can be easily embedded within HTML tags and script.
Compiled by: Dawit U. (M. Tech.) 8

Why PHP ? What are PHP Features cont…
Security:
PHP is a secure language to develop the website. It consists of
multiple layers of security to prevent threads and malicious
attacks.
Control:
Different programming languages require long script or code,
whereas PHP can do the same work in a few lines of code.
It has maximum control over the websites like you can make
changes easily whenever you want.
A Helpful PHP Community:
It has a large community of developers who regularly updates
documentation, tutorials, online help, and FAQs.
Learning PHP from the communities is one of the significant
benefits.
Compiled by: Dawit U. (M. Tech.) 9

Loosely Typed Language:
PHP allows us to use a variable without declaring its
datatype. It will be taken automatically at the time of
execution based on the type of data it contains on its value.
Setting up PHP environment
In order to develop and run PHP scripts, three vital
components need to be installed on your computer system.
Those are:-
Web server (Apache, Microsoft IIS )
Database (in our case MySQL)
PHP parser/interpreter : which processes the pages
before they are directed to clients as html output
Compiled by: Dawit U. (M. Tech.) 10
Why PHP ? What are PHP Features cont…

For simplicity and efficient way we will use an integrated module
XAMPPwebserver which includes PHP, Apache, and MySQL.
XAMPP
Is a small and light apache distribution containing the most
common web development technologies in a single package.
Is a module that integrate PHP, Apache web serverand
MySQLdatabase
Its Open source
Other option is also using WAMPserver
Compiled by: Dawit U. (M. Tech.) 11

PHP Syntax
<?php…your phpcode goes here…?>
PHP code is always enclosed by <?phpand ?>.
If there is any PHP code embedded with html, it should be
saved with .php, not .html
Statement should end with a semicolon ;
Compiled by: Dawit U. (M. Tech.) 12

Comments
// Single line comment
# This is a comment, and
/*
Multiline comment
*/
Echo and print statement
Used to write a text on the browser. They are more or less the
same. They are both used to output data to the screen.
The differences are small: echo has no return value while print
has a return value of 1 so it can be used in expressions. echo can
take multiple parameters while print can take one argument.
echo is marginally faster than print.
<?phpecho‘Hello World’;
print“Hello world”; ?>
Compiled by: Dawit U. (M. Tech.) 13

Phpvariables
A variable is a container that you can store data in, and every
variable has a unique name.
Few variable naming rules
The first character must be a dollar sign ($).
A variable name must be at least one character in length.
The first character after the dollar sign can be a letter or an
underscore (_), and characters after that can be a letter, an
underscore, or a number.
Example of valid variable. $email, $how_long. etc
Example of invalid variable. email, $how-long. Etc
Variables in PHP do not have intrinsic types -a variable does
not know in advance whether it will be used to store a number
or a string of characters.
Phpautomatically converting types from one to another when
necessary
Compiled by: Dawit U. (M. Tech.) 14

Variable types in PHP
Integers:-are whole numbers, without a decimal point, like
343,123,55 ….
Doubles:-are floating-point numbers, like 3.24, 45.3 …
Booleans: have only two possible values either true or false
NULL: is a special type that only has one value: NULL
Strings: are sequences of characters, like 'PHP supports string
operations.‘ A string variable is used to store and manipulate a
piece of text
Arrays: are named and indexed collections of other values.
Objects: are instances of programmer defined classes,
which can package up both other kinds of values and functions
that are specific to the class.
Compiled by: Dawit U. (M. Tech.) 15

Variable types in PHP cont…
Resources: are special variables that hold references to
resources external to PHP (such as database
connections).
The first fivearesimpletypes, and the next two (arraysand
objects) are compound.
The compound types can package up other arbitrary values
of arbitrary type, whereas the simple types cannot.
There is no size limit for variables.
The correct way of setting a variable in PHP:
$var_name= value;
Compiled by: Dawit U. (M. Tech.) 16

Let's try creating a variable with a string, and a variable
with a number.
<?php
$txt = "Hello World!";
$number = 16;
?>
In the example above, you see that you do not have to tell
PHP which data type the variable is.
PHP automatically converts the variable to the correct data
type, depending on how they are set.
Compiled by: Dawit U. (M. Tech.) 17

Variable Scope
Scope can be defined as the range of availability a variable has
to the program in which it is declared.
PHP variables can have one of four scope types
Local variables
Function parameters
Global variables Reading assignment
Static variables
PHP -Predefined Variables
PHP provides a several predefined superglobalsvariables.
All the following variables are automatically available in every
scope.
Compiled by: Dawit U. (M. Tech.) 18

Sr.
No
Predefined Variables & their Descriptions
1$GLOBALS
Used to access global variable which is currently available within the global
scope of the php script. Also within functions & methods.
2 $_SERVER
This is an array containing information such as headers, paths, and script
locations.
3$_GET
An associative array of variables passed to the current script via the HTTP GET
method
4$_POST
An associative array of variables passed to the current script via the HTTP
POST method.
Compiled by: Dawit U. (M. Tech.) 19

Sr.
No
Variable & Description
5$_FILES
An associative array of items uploaded to the current script via the HTTP POST method.
6$_REQUEST
An associative array consisting of the contents of $_GET, $_POST, and
$_COOKIE.
7$_COOKIE
An associative array of variables passed to the current script via HTTP cookies.
8$_SESSION
An associative array containing session variables available to the current script.
9$_PHP_SELF
A string containing PHP script file name in which it is called.
Compiled by: Dawit U. (M. Tech.) 20

PHP constant
Constant is a name or an identifier for a simple value.
value cannotchange duringthe executionof the script.
Constants are accessed anywhere without regard to variable
scoping rules.
Constant name starts with a letter or underscore.
To define a constant you have to use define() function
To retrieve the value of a constant, you have to simply specify
its name
No need to have a constant with a $
You can also use the function constant() to read a constant's
value if you wish to obtain the constant's name dynamically.
Compiled by: Dawit U. (M. Tech.) 21

Example: How constants work
Valid and Invalid Constant Names
Valid
define("ONE", "first thing");
define("TWO2", "second thing");
define("THREE_3", "third thing");
Invalid
define("2TWO", "second thing");
define(“#one", "second thing");
Compiled by: Dawit U. (M. Tech.) 22
Output
50
50

PHP Operator Types
What is Operator? Simple answer can be given using expression 4 + 5
is equal to 9. Here 4 and 5 are called operands and + is called operator.
PHP supports following type of operators.
Arithmetic Operators (*,/,-,+,%,++,--)
Comparison Operators (==,!=,>,<,>=, <=)
Logical Operators ( and, or, &&, ||, !)
Assignment Operators( =, +=, -=, *=, /=, %=)
The Concatenation Operator or dot (.):-is used to put/merge two
string values together.
Exercise
Declare to variables ‘A’ and ‘B’ and apply the following operators and
see the effect:
%, ++, --
==, !=
%=, +=, -=
Compiled by: Dawit U. (M. Tech.) 23

PHP control structures
Conditional Statements
Very often when you write code, you want to perform different
actions for different decisions
1.if
2.if…else
3.if…elseif…else
4.switch
Compiled by: Dawit U. (M. Tech.) 24

Theif statement
Syntax
if(condition){
//code to be executed if condition is true
statement
}
conditionisevaluatedtoitsBooleanvalue.Ifit
evaluatestoTRUE,PHPwillexecutestatement,andif
conditionevaluatestoFALSE-it'llignoreit.
Example
<?php
$a=10; $b=8;
if ($a > $b)
print "a is bigger than b";
?>
Compiled by: Dawit U. (M. Tech.) 25
Output
a is bigger than b

if… else statement
Often you'd want to execute a statement if a certain
condition is met, and a different statement if the condition is
not met.
Syntax:
if (condition){
//some code here
}
else{
// run if condition is false
}
Compiled by: Dawit U. (M. Tech.) 26
Example
<?php
$a=10; $b=8;
if ($a < $b) {
print "a is bigger than b";
}
else {
print "a is NOT bigger than b";
}
?>
Output
a is NOT bigger than b

if..elseif…else
Execute a set of code if one of several condition are
true.
Syntax:
if (condition 1)
//if condition 1 is true this will run
elseif(condition 2)
//if condition 2 is true this will run
else
//if all of the above are not true this will run
Compiled by: Dawit U. (M. Tech.) 27

Example: How if…elseif…else works
<?php
$number = 12;
if($number < 0)
echo‘Number is negative’;
elseif($number == 0)
echo‘Number is zero’;
elseif($number > 0)
echo‘Number is positive ’;
?>
Compiled by: Dawit U. (M. Tech.) 28
Output
Number is positive

switch
If you want to select one of many blocks of code to be
executed, use the Switch statement
Syntax:
switch(expression){
caselabel1:
code to be executed if expression = label1;
break;
caselabel2:
code to be executed if expression = label2;
break;
default:
code to be executed
if expression is different from both label1 and label2; }
Compiled by: Dawit U. (M. Tech.) 29

how it works:
A single expression (most often a variable) is evaluated
once.
The value of the expression is compared with the values for
each case in the structure.
If there is a match, the code associated with that case is
executed.
After a code is executed, break is used to stop the code
from running into the next case.
The default statement is used if none of the cases are true.
Compiled by: Dawit U. (M. Tech.) 30

Example to show How switch works
<?php
$userAction="save";
switch ($userAction) {
case "open":
echo "Opening the file"; break;
case "save":
echo "Saving the file"; break;
case "close":
echo "Close the file"; break;
case "logout":
echo "Log the user out"; break;
default:
echo "Please choose an option"; } ?>
Compiled by: Dawit U. (M. Tech.) 31

PHP Loop Types
Looping statements in PHP are used to execute the
same block of code again and again until a certain
condition is met. The four types of loops are
1.while loop
2.do…while loop
3.for loop
4.foreachloop, which work specifically with arrays.
Compiled by: Dawit U. (M. Tech.) 32

while loop
executeablockofcodeifandaslongasatest
expressionistrue
Syntax:
while (condition)
{
//code to be executed;
}
Compiled by: Dawit U. (M. Tech.) 33

Example
Compiled by: Dawit U. (M. Tech.) 34
output

do…while loop
Executeablockofcodeatleastonce.
Itthenwillrepeattheloopaslongasaconditionis
true.
Syntax:
do
{
//codetobeexecuted;
}
while(condition);
Compiled by: Dawit U. (M. Tech.) 35

Example
<?php
$i = 0;
$num= 0;
do
{
$i++;
echo "The number is " . $i . "<br/>";
}
while( $i < 10 );
echo ("Loop stopped at i = $i" );
?>
Compiled by: Dawit U. (M. Tech.) 36
output

for loop
The for statement is used when you know how many times you
want to execute a statement or a list of statements.
Syntax
for(initialization; condition; increment/decrement)
{
code to be executed;
}
The for statement has three parameters. The first parameter
initializes variables, the second parameter holds the condition, and
the third parameter contains the increments required to implement
the loop.
If more than one variable is included in the initialization or the
increment parameter, they should be separated by commas. The
condition must evaluate to true or false.
Compiled by: Dawit U. (M. Tech.) 37

Example
<?php
$a = 0;
$b = 0;
for( $i=0; $i<5; $i++ )
{
$a += 10;
$b += 5;
}
echo "At the end of the loop a=$a and b=$b" ;
?>
Compiled by: Dawit U. (M. Tech.) 38
Output
At the end of the loop a=50 and b=25

foreach loop
Used to loop through arrays.
For each pass
value of the current array element is assigned to $value
the array pointer is moved by one
in the next pass next element will be processed
Syntax:
foreach(array as $value)
{
//code to be executed;
}
Compiled by: Dawit U. (M. Tech.) 39

Example
<?php
$arr= array( 1, 2, 3, 4, 5);
foreach( $arras$value )
{
echo "Value is” .$value. ”<br/>";
} output
?>
Compiled by: Dawit U. (M. Tech.) 40

Arrays in php
Array is a data structure that stores one or more similar
type of values in a single variable.
For example if you want to store 100 numbers then instead
of defining 100 variables its easy to define an array of 100
length.
Types of Array
1.Numeric
2.Associative
3.Multidimensional---Read
1. Numeric Arrays: is an array with a numeric index.
By default array index starts from zero.
$numbers = array( 1, 2, 3, 4, 5);
// Another method of creating array
$numbers[0] = “one”;
$numbers[1] = ‘two’;
Compiled by: Dawit U. (M. Tech.) 41

<?php
$numbers = array( 1, 2, 3, 4, 5);
foreach( $numbers as $value ) {
echo"Value is $value <br/>"; }
?>
Compiled by: Dawit U. (M. Tech.) 42

2.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.
Example:
<?php
$salaries = array(“Aman" => 2000, “kedir" => 1000,
"zara" => 500);
echo "Salary of Amanis ". $salaries[Aman'] . "<br/>";
echo "Salary of Kediris ". $salaries[‘kedir']. "<br/>";
echo "Salary of zarais ". $salaries['zara']. "<br/>";?>
Compiled by: Dawit U. (M. Tech.) 43

PHP Functions
A function is a block of code that can be executed whenever
we need it.
The real power of PHP comes from its functions.
In php there are more than 1000 built-in functions available.
Fore example
The date/time functions allow us to get the date and time
from the server where our php script runs.
We can use this functions to format the date and time in
several ways.
Note:These functions depend on the locale settings of your
server.
Compiled by: Dawit U. (M. Tech.) 44

phpfunction cont…
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) followed by () brackets.
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
Compiled by: Dawit U. (M. Tech.) 45

A simple function examples
<html>
<body>
<?php
function writeMyName()
{
echo “John kery";
}
writeMyName();
?>
</body>
</html>
The above function is a very
simple function. It only writes a
static string.
Compiled by: Dawit U. (M. Tech.) 46
Using the function in a PHP script:
<html><head></head>
<body>
<?php
function writeMyName()
{
echo "Kai Jim Robson";
}
echo "Hello world!<br/>";
echo "My name is ";
writeMyName();
echo ".<br/>That's right, ";
writeMyName();
echo " is my name.";
?>
</body>
</html>

To add more functionality to a function, we can add
parameters. A parameter is just like a variable.
Compiled by: Dawit U. (M. Tech.) 47
writeMyName(“John");
echo "My name is ";
writeMyName("Hagere");
echo "My name is ";
writeMyName(“Bruke");
?>
</body>
</html>
<html>
<body>
<?php
function
writeMyName($fname)
{
echo $fname. "
Robson.<br/>";
}
echo "My name is ";

PHP Functions -Return values
Compiled by: Dawit U. (M. Tech.) 48
<html>
<body>
<?php
function add($x, $y)
{
$total = $x + $y;
return $total;
}
echo “the sum of 1 + 16 is = " . add(1,16);
?>
</body>
</html>

PHP Form Handling
Now it ’ s time to start real world applications with PHP.
A key part of most PHP applications is the ability to accept
input from the person using the application.
One of the most common ways to receive input from the user
of a Web application is via an HTML form.
$_GET and $_POST Superglobalarray variables
$_GET and $_POSTvariables are used to collect form-data.
They are super global array variables , which means that they
are always accessible, regardless of scope and you can access
them from any function, class or file without declaring them
explicitly asglobal $variable;scripts to capture the data sent
from html forms.
They contains the field names from the sent form as array
keys, with the field values themselves as array values.
Compiled by: Dawit U. (M. Tech.) 49

GET method and $_GET variable
Information sent from html form with the GET method
is visible to everyone (all variable names and values
are displayed in the URL).
GET also has limits on the amount of data to send.
It is useful for sending small amounts of data and
makes it easy for the user to resubmit the data.
The page and the encoded information are separated
by the ?Character. Like below link
http://www.test.com/index.htm?name1=value1&name2
=value2
Compiled by: Dawit U. (M. Tech.) 50

GET cont…
Never use GET method if you have passwordor
other sensitive informationto be sent to the server.
Not recommended be used to send binary data, like
imagesor word documents
GETmay be used for sending non-sensitive data.
If you wish to collect data using GETinstead of POST,
you have to change the value of the method attribute
of the form as GET.
$_GET variable:-Holds the submitted data.
Compiled by: Dawit U. (M. Tech.) 51

How it works
The example below displays a simple HTML form with
two input fields and a submit button.
actionattribute tells the web browser where to send
the form data when the user fills & submits the form.
When the user fills out the form above and clicks the
submit button, the form data is sent to “test.php".
methodattribute tells the browser how to send the
form data.
The form data is sent with the HTTP GETmethod.
Compiled by: Dawit U. (M. Tech.) 52

Cont…
Create phpfile (test.phpfile look like this)
Compiled by: Dawit U. (M. Tech.) 53

POST method and $_POST variable
Information sent from a form with the POST
method is invisible to others (all names/values are
embedded within the body of the HTTP request).
Does not have any restriction on data size to be
sent.
Moreover POSTsupports advanced functionality
such as support for multi-part binary data while
uploading files to server, to send ASCII. The URL
look like this
http://www.w3schools.com/test.php
However, because the variables are not displayed in
the URL, it is not possible to bookmark the page.Compiled by: Dawit U. (M. Tech.) 54

$_POST:-is global variable that accepts the sent
data.
If you wish to collect data using POST instead of
GET, you have to change the value of the method
attribute of the form as POST.
Developers prefer POST for sending form data.
Compiled by: Dawit U. (M. Tech.) 55

How it works
When the user fills out the form above and clicks the
submit button, the form data is sent to “test.php".
The form data is sent with the HTTP POST method.
Compiled by: Dawit U. (M. Tech.) 56

Create phpfile (test.php)
Compiled by: Dawit U. (M. Tech.) 57

When user submits data by clicking on "Submit“
button, data typed on two fields of the form goes to
the file mentioned as a value of the actionattribute
called test.php.
For other case developers do use the file itself for
processing form data.
So, <?phpecho $_SERVER['PHP_SELF']; ?>points
to the file itself.
Compiled by: Dawit U. (M. Tech.) 58

The $_REQUEST Variable
The php$_REQUESTvariable contains the contents of
both $_GET, $_POST, and$_COOKIE.
The php$_REQUEST variable can be used to get the
result from form data sent with both the GET and
POST methods.
Example
Welcome <?phpecho$_REQUEST["name"]; ?>.<br/>
You are <?phpecho$_REQUEST["age"]; ?> years old!
Compiled by: Dawit U. (M. Tech.) 59

Database Programming using PHP
Overview on MySQL database
An applicationis a program or a group of programs designed for
use by an end user (for example, customers, members).
If the end user interacts with the application via a Web browser,
the application is a Web based or Web application.
If the Web application requires the long-term storage of
information using a database, it is a Web database application.
MySQLis developed, marketed, and supported by MySQLAB,
which is a Swedish company.
The company licenses it in two ways :
1.Open source software: MySQL is available through the GNU
GPL (General Public License). you can use MySQL for free
Compiled by: Dawit U. (M. Tech.) 60

Overview on MySQL database cont…
2. Commercial license: MySQL is available with a commercial license
for those who prefer it to the GPL. If a developer wants to use MySQL
as part of a new software product and wants to sell the new product
rather than release it under the GPL, the developer needs to purchase a
commercial license.
MySQL is RDBMSs (Relational Database Management Systems),
in which data is organized and stored in a set of related tables and
well suited for Web sites.
MySQLis the de-facto standard database system for web sites with
HUGE volumes of both data and end-users (like Facebook, Twitter,
and Wikipedia).
It is ideal for both small and large applications
It is very fast, reliable, inexpensive, secure, customizable, easy to
use, cross-platform and uses standard SQL.
With PHP, you can connect to and manipulate databases.Compiled by: Dawit U. (M. Tech.) 61

Understanding the MySQL Privilege System
You need to control access to the information in your database.
You need to decide who can see the data and who can change it.
MySQL provides a security system for protecting your data. No
one can access the data in your database without an account.
Each account is either allowed or not allowed to perform an
operation in your database, such as SELECT, DELETE, INSERT,
CREATE, or DROP.
The settings that specify what an account can do are privileges, or
permissions.
You can set up an account with all permissions, no permissions, or
anything in between. For instance, for an online product shop, you
want the customer to be able to see the information in the shop but
not be able to change it.
Compiled by: Dawit U. (M.Tech.) 62

MySQL account permission
Permissions can be granted or removed individually or all at once
Compiled by: Dawit U. (M.Tech.) 63

Using phpMyAdmin
phpMyAdminis a free software tool written in php intended to
handle the administration of MySQL database over the World Wide
Web through your web browser.
It’s integrated with MySQL database in XAMPP package.
It supports a wide range of operations with MySQL.
Browse and drop databases, tables, views, fields and indexes.
Create, copy, drop, rename and alter databases, tables, fields and
indexes.
Execute, edit and bookmark any SQL-statement, even batch-
queries.
Used to Manage MySQL users, privileges, procedures and triggers.
Import data from CSV and SQL.
Export data to various formats: CSV, SQL, XML, PDF and others
Compiled by: Dawit U. (M.Tech.) 64

PHPConnect to MySQL
Basic operation on data base using php
The basic steps of performing a query includes:
Connect to the database.
Select the database to use.
Build a SELECT statement.
Perform the query.
Display the results
Compiled by: Dawit U. (M.Tech.) 65

PHP 5 and later can work with a MySQL database using:
i.MySQLiextension (the "i" stands for improved)
ii.PDO(PHP Data Objects)
Earlier versions of PHP used the MySQL extension. However, this
extension was deprecated in 2012
Should I Use MySQLior PDO?
The short answer would be "Whatever you like".
Both MySQLiand PDO have their advantages:
PDO will work on 12 different database systems, whereas MySQLi
will only work with MySQLdatabases.
Both are object-oriented, but MySQLialso offers a procedural API.
Both support Prepared Statements. Prepared Statements protect
from SQL injection, and are very important for web application
security.
Compiled by: Dawit U. (M.Tech.) 66

Opening Database Connection
Before we can access data in the MySQL database, we need to be able to
connect to the server:
mysqli_connectfunction is used to open a database connection
This function returns TRUE on success, or FALSE on failure.
have 3 main parameters
mysqli_connect(“host”,”username”,”pwd”);
Parameter Description
Host: Optional. Specifies the server to connect to (can also
include a port number, e.g. "hostname:port").
Default value is "localhost:3306“Optional.
Username: Specifies the username to log in with. Default
value is the name of the user that owns the server process
Pwd: Optional. Specifies the password to log in with. Default is ""
Compiled by: Dawit U. (M. Tech.) 67
MySQLi(object-oriented), MySQLi(procedural), PDO

Compiled by: Dawit U. (M. Tech.) 68
<?php
$servername="localhost";
$username ="username";
$password ="password";
// Create connection
$conn = mysqli_connect($servername, $username, $password);
// Check connection
if(!$conn){
die("Connection failed: ". mysqli_connect_error());
}
echo"Connected successfully";
?>
Example (MySQLiProcedural)

Compiled by: Dawit U. (M. Tech.) 69
<?php
$servername="localhost";
$username ="username";
$password ="password";
// Create connection
$conn =newmysqli($servername, $username, $password);
// Check connection
if($conn->connect_error){
die("Connection failed: ". $conn->connect_error); }
echo"Connected successfully";
?>
Example (MySQLiObject-Oriented)

Compiled by: Dawit U. (M. Tech.) 70
Close the Connection
The connection will be closed automatically when the script ends.
To close the connection before, use the following
MySQLiObject-Oriented:
$conn->close();
MySQLiProcedural:
mysqli_close($conn);
PDO:
$conn = null;

Compiled by: Dawit U. (M.Tech.) 71
Example (MySQLiObject-oriented)
<?php
$servername="localhost";
$username ="username";
$password ="password";
// Create connection
$conn =newmysqli($servername, $username, $password);
// Check connection
if($conn->connect_error){
die("Connection failed: ". $conn->connect_error);
}
// Create database
$sql="CREATE DATABASE myDB";
if($conn->query($sql) === TRUE) {
echo"Database created successfully";
}else{
echo"Error creating database: ". $conn->error;
}
$conn->close();
?>

Creating Database in PHP
PHP usesmysql_queryfunction to create a MySQL
database.
takes two parameters and returns TRUE on success
or FALSE on failure
mysql_query( sql, connection );
Compiled by: Dawit U. (M.Tech.) 72

Deleting a Tables in PHP
mysqli_query()function used to drop
table from database.
DROP TABLE tablename;
Inserting Data to MySQL DB
Data can be entered into MySQL tables by
executing SQL INSERT statement through
PHP function mysqli_query.
Compiled by: Dawit U. (M.Tech.) 73

Getting Data From MySQL Database
by executing SQL SELECT statement through PHP
function mysqli_query.
mysqli_fetch_array() used to fetch.
Updating data in MySQL Database
UPDATEstatement through PHP function
mysqli_query.
Deleting Data from MySQL Database
SQL DELETE statement through PHP function
mysqli_query.
Compiled by: Dawit U. (M.Tech.) 74

Exercise
•Create a formwith nameand password
•Create a database named ‘Member’
•Create a table named ‘Admin’
•Insert the form data to ‘Admin’ table
when the user clicks submit.
Compiled by: Dawit U. (M.Tech.) 75

File inclusion in php
You can include the content of a PHP , HTML file into another
PHP file before the server executes it. There are two PHP
functions which can be used to included one PHP file into
another PHP file.
The include() Function
The require() Function
This is a strong point of PHP which helps in creating functions,
headers, footers, or elements that can be reused on multiple
pages. This will help developers to make it easy to change the
layout of complete website with minimal effort. If there is any
change required then instead of changing thousand of files just
change included file.
Compiled by: Dawit U. (M.Tech.) 76

Assume we have a standard footer file called "footer.php", that
looks like this:
<?php
echo "<p>Copyright &copy; 2022 </p>";
?>
To include the footer file in a page, use the include
statement:
<html>
<body>
<h1>Welcome to my home page!</h1>
<p>Some text.</p>
<?phpinclude 'footer.php';?>
</body>
</html>
Compiled by: Dawit U. (M.Tech.) 77

The include() Function
The include() function takes all the text in a specified file and copies
it into the file that uses the include function. If there is any problem
in loading a file then the this function generates a warningbut the
script will continue execution.
The require() Function
The require() function takes all the text in a specified file and copies
it into the file that uses the include function.
If there is any problem in loading a file then the this function
generates a fatal error messages oryou may get plain
warning messages or nothing at all and haltthe execution of the
script. This depends on your PHP Server configuration So there is no
difference in require() and include() except they handle error
conditions.
Userequirewhen the file is required by the application.
Useincludewhen the file is not required and application should
continue when file is not found.
Compiled by: Dawit U. (M.Tech.) 78

Compiled by: Dawit U. (M. Tech.) 79
The PHPdate()function is used to format a date and/or
a time.
PHPDate and Time
ParameterDescription
format Required. Specifies the format of the timestamp
timestampOptional. Specifies a timestamp. Default is the current
date and time
Syntax
date(format,timestamp)

Example
Compiled by: Dawit U. (M. Tech.) 80
<?php
echo "Today is " .date("Y/m/d") . "<br>";
echo "Today is " . date("Y.m.d") . "<br>";
echo "Today is " . date("Y-m-d") . "<br>";
echo "Today is " . date("l");
?>
The End!
Tags