SlideShare a Scribd company logo
1 of 80
Download to read offline
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 (Hypertext Preprocessor)
 It is a server side scripting language that can be embedded
in HTML.
 PHP is a programming language that allows web developers
to create dynamic content that interacts with databases.
 It is basically used for developing web based software
applications, session tracking, for building entire e-
commerce sites.
 PHP code runs on the server and is stored in php scripts that
usually have a .php file extension.
 PHP started out as a small open source project that evolved
as more and more people found out how useful it was.
 PHP was created by Rasmus Lerdorf in 1994 but appeared
in the market in 1995. PHP 8.1 is new version with major
update and many new features.
Compiled by: Dawit U. (M. Tech.) 3
 PHP supports a major protocols such as POP3, IMAP, and LDAP.
 When the server runs a PHP script the end result is always
pure HTML and CSS.
 So every PHP script ultimately gets turned into HTML and CSS
once it’s finished running on the server.
 It is integrated with a number of popular databases, including
ᴥ MySQL
ᴥ Oracle
ᴥ PostgreSQL
ᴥ Informix
ᴥ Microsoft SQL Server
ᴥ MS Access
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
XAMPP webserver 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 server and
MySQL database
 Its Open source
 Other option is also using WAMP server
Compiled by: Dawit U. (M. Tech.) 11
PHP Syntax
<?php …your php code goes here…?>
 PHP code is always enclosed by <?php and ?>.
 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.
<?php echo ‘Hello World’;
print “Hello world”; ?>
Compiled by: Dawit U. (M. Tech.) 13
Php variables
 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.
 Php automatically 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 five are simple types, and the next two (arrays and
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 superglobals variables.
 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 cannot change during the execution of 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
The if statement
Syntax
if (condition){
//code to be executed if condition is true
statement
}
 condition is evaluated to its Boolean value. If it
evaluates to TRUE, PHP will execute statement, and if
condition evaluates to FALSE - it'll ignore it.
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){
case label1:
code to be executed if expression = label1;
break;
case label2:
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. foreach loop, which work specifically with arrays.
Compiled by: Dawit U. (M. Tech.) 32
while loop
 execute a block of code if and as long as a test
expression is true
 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
 Execute a block of code at least once.
 It then will repeat the loop as long as a condition is
true.
 Syntax:
do
{
//code to be executed;
}
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( $arr as $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 Aman is ". $salaries[Aman'] . "<br />";
echo "Salary of Kedir is ". $salaries[‘kedir']. "<br />";
echo "Salary of zara is ". $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
php function 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 Superglobal array variables
 $_GET and $_POST variables 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 as global $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 password or
other sensitive information to be sent to the server.
 Not recommended be used to send binary data, like
images or word documents
 GET may be used for sending non-sensitive data.
 If you wish to collect data using GET instead 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.
 action attribute 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".
 method attribute tells the browser how to send the
form data.
 The form data is sent with the HTTP GET method.
Compiled by: Dawit U. (M. Tech.) 52
Cont…
 Create php file (test.php file 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 POST supports 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 php file (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 action attribute
called test.php.
 For other case developers do use the file itself for
processing form data.
So, <?php echo $_SERVER['PHP_SELF']; ?> points
to the file itself.
Compiled by: Dawit U. (M. Tech.) 58
The $_REQUEST Variable
 The php $_REQUEST variable 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 <?php echo $_REQUEST["name"]; ?>.<br />
You are <?php echo $_REQUEST["age"]; ?> years old!
Compiled by: Dawit U. (M. Tech.) 59
Database Programming using PHP
Overview on MySQL database
 An application is 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.
 MySQL is 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.
 MySQL is 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
 phpMyAdmin is 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
PHP Connect 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. MySQLi extension (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 MySQLi or PDO?
 The short answer would be "Whatever you like".
 Both MySQLi and PDO have their advantages:
 PDO will work on 12 different database systems, whereas MySQLi
will only work with MySQL databases.
 Both are object-oriented, but MySQLi also 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_connect function 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 (MySQLi Procedural)
Compiled by: Dawit U. (M. Tech.) 69
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error); }
echo "Connected successfully";
?>
Example (MySQLi Object-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
MySQLi Object-Oriented:
$conn->close();
MySQLi Procedural:
mysqli_close($conn);
PDO:
$conn = null;
Compiled by: Dawit U. (M.Tech.) 71
Example (MySQLi Object-oriented)
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$conn = new mysqli($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 uses mysql_query function 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
 UPDATE statement 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 form with name and 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>
<?php include '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 warning but 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 or you may get plain
 warning messages or nothing at all and halt the 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.
 Use require when the file is required by the application.
 Use include when 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 PHP date() function is used to format a date and/or
a time.
PHP Date and Time
Parameter Description
format Required. Specifies the format of the timestamp
timestamp Optional. 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!

More Related Content

Similar to chapter 5 Server-Side Scripting (PHP).pdf

Similar to chapter 5 Server-Side Scripting (PHP).pdf (20)

chapter Two Server-side Script lang.pptx
chapter  Two Server-side Script lang.pptxchapter  Two Server-side Script lang.pptx
chapter Two Server-side Script lang.pptx
 
Php tutorial
Php tutorialPhp tutorial
Php tutorial
 
Programming language
Programming languageProgramming language
Programming language
 
PHP
 PHP PHP
PHP
 
PHP
PHPPHP
PHP
 
PHP LICTURES ..........
PHP LICTURES ..........PHP LICTURES ..........
PHP LICTURES ..........
 
Php intro
Php introPhp intro
Php intro
 
PhP Training Institute In Delhi
PhP Training Institute In DelhiPhP Training Institute In Delhi
PhP Training Institute In Delhi
 
PHP Basics
PHP BasicsPHP Basics
PHP Basics
 
Php unit i
Php unit i Php unit i
Php unit i
 
PHP.docx
PHP.docxPHP.docx
PHP.docx
 
Introduction to-php
Introduction to-phpIntroduction to-php
Introduction to-php
 
Report.docx
Report.docxReport.docx
Report.docx
 
Unit 1
Unit 1Unit 1
Unit 1
 
PHP ITCS 323
PHP ITCS 323PHP ITCS 323
PHP ITCS 323
 
Php Ppt
Php PptPhp Ppt
Php Ppt
 
PHP Basic & Variables
PHP Basic & VariablesPHP Basic & Variables
PHP Basic & Variables
 
Php tutorial(w3schools)
Php tutorial(w3schools)Php tutorial(w3schools)
Php tutorial(w3schools)
 
Php tutorialw3schools
Php tutorialw3schoolsPhp tutorialw3schools
Php tutorialw3schools
 
PHP Training In Chandigarh.docx
PHP Training In Chandigarh.docxPHP Training In Chandigarh.docx
PHP Training In Chandigarh.docx
 

Recently uploaded

Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2Hyundai Motor Group
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraDeakin University
 

Recently uploaded (20)

Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning era
 

chapter 5 Server-Side Scripting (PHP).pdf

  • 1. Chapter Five Server-Side Scripting (PHP) 1 Compiled by Dawit Uta. (M. Tech.) Computer Science Department, WSU website address: www.davidtechnotips.com
  • 2. 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
  • 3. What is PHP? Introduction  PHP (Hypertext Preprocessor)  It is a server side scripting language that can be embedded in HTML.  PHP is a programming language that allows web developers to create dynamic content that interacts with databases.  It is basically used for developing web based software applications, session tracking, for building entire e- commerce sites.  PHP code runs on the server and is stored in php scripts that usually have a .php file extension.  PHP started out as a small open source project that evolved as more and more people found out how useful it was.  PHP was created by Rasmus Lerdorf in 1994 but appeared in the market in 1995. PHP 8.1 is new version with major update and many new features. Compiled by: Dawit U. (M. Tech.) 3
  • 4.  PHP supports a major protocols such as POP3, IMAP, and LDAP.  When the server runs a PHP script the end result is always pure HTML and CSS.  So every PHP script ultimately gets turned into HTML and CSS once it’s finished running on the server.  It is integrated with a number of popular databases, including ᴥ MySQL ᴥ Oracle ᴥ PostgreSQL ᴥ Informix ᴥ Microsoft SQL Server ᴥ MS Access Compiled by: Dawit U. (M. Tech.) 4
  • 5. 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
  • 6. 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
  • 7. 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
  • 8. 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
  • 9. 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
  • 10.  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…
  • 11. For simplicity and efficient way we will use an integrated module XAMPP webserver 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 server and MySQL database  Its Open source  Other option is also using WAMP server Compiled by: Dawit U. (M. Tech.) 11
  • 12. PHP Syntax <?php …your php code goes here…?>  PHP code is always enclosed by <?php and ?>.  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
  • 13. 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. <?php echo ‘Hello World’; print “Hello world”; ?> Compiled by: Dawit U. (M. Tech.) 13
  • 14. Php variables  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.  Php automatically converting types from one to another when necessary Compiled by: Dawit U. (M. Tech.) 14
  • 15. 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
  • 16. Variable types in PHP cont…  Resources: are special variables that hold references to resources external to PHP (such as database connections).  The first five are simple types, and the next two (arrays and 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
  • 17.  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
  • 18. 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 superglobals variables.  All the following variables are automatically available in every scope. Compiled by: Dawit U. (M. Tech.) 18
  • 19. 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
  • 20. 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
  • 21. PHP constant  Constant is a name or an identifier for a simple value.  value cannot change during the execution of 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
  • 22. 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
  • 23. 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
  • 24. 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
  • 25. The if statement Syntax if (condition){ //code to be executed if condition is true statement }  condition is evaluated to its Boolean value. If it evaluates to TRUE, PHP will execute statement, and if condition evaluates to FALSE - it'll ignore it. 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
  • 26. 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
  • 27. 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
  • 28. 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
  • 29. switch  If you want to select one of many blocks of code to be executed, use the Switch statement Syntax: switch (expression){ case label1: code to be executed if expression = label1; break; case label2: 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
  • 30. 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
  • 31. 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
  • 32. 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. foreach loop, which work specifically with arrays. Compiled by: Dawit U. (M. Tech.) 32
  • 33. while loop  execute a block of code if and as long as a test expression is true  Syntax: while (condition) { //code to be executed; } Compiled by: Dawit U. (M. Tech.) 33
  • 34. Example Compiled by: Dawit U. (M. Tech.) 34 output
  • 35. do…while loop  Execute a block of code at least once.  It then will repeat the loop as long as a condition is true.  Syntax: do { //code to be executed; } while (condition); Compiled by: Dawit U. (M. Tech.) 35
  • 36. 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
  • 37. 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
  • 38. 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
  • 39. 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
  • 40. Example <?php $arr = array( 1, 2, 3, 4, 5); foreach( $arr as $value ) { echo "Value is” .$value. ”<br />"; } output ?> Compiled by: Dawit U. (M. Tech.) 40
  • 41. 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
  • 42. <?php $numbers = array( 1, 2, 3, 4, 5); foreach( $numbers as $value ) { echo "Value is $value <br />"; } ?> Compiled by: Dawit U. (M. Tech.) 42
  • 43. 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 Aman is ". $salaries[Aman'] . "<br />"; echo "Salary of Kedir is ". $salaries[‘kedir']. "<br />"; echo "Salary of zara is ". $salaries['zara']. "<br />";?> Compiled by: Dawit U. (M. Tech.) 43
  • 44. 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
  • 45. php function 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
  • 46. 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>
  • 47. 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 ";
  • 48. 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>
  • 49. 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 Superglobal array variables  $_GET and $_POST variables 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 as global $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
  • 50. 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
  • 51. GET cont…  Never use GET method if you have password or other sensitive information to be sent to the server.  Not recommended be used to send binary data, like images or word documents  GET may be used for sending non-sensitive data.  If you wish to collect data using GET instead 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
  • 52. How it works  The example below displays a simple HTML form with two input fields and a submit button.  action attribute 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".  method attribute tells the browser how to send the form data.  The form data is sent with the HTTP GET method. Compiled by: Dawit U. (M. Tech.) 52
  • 53. Cont…  Create php file (test.php file look like this) Compiled by: Dawit U. (M. Tech.) 53
  • 54. 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 POST supports 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
  • 55.  $_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
  • 56. 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
  • 57. Create php file (test.php) Compiled by: Dawit U. (M. Tech.) 57
  • 58.  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 action attribute called test.php.  For other case developers do use the file itself for processing form data. So, <?php echo $_SERVER['PHP_SELF']; ?> points to the file itself. Compiled by: Dawit U. (M. Tech.) 58
  • 59. The $_REQUEST Variable  The php $_REQUEST variable 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 <?php echo $_REQUEST["name"]; ?>.<br /> You are <?php echo $_REQUEST["age"]; ?> years old! Compiled by: Dawit U. (M. Tech.) 59
  • 60. Database Programming using PHP Overview on MySQL database  An application is 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.  MySQL is 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
  • 61. 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.  MySQL is 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
  • 62. 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
  • 63. MySQL account permission Permissions can be granted or removed individually or all at once Compiled by: Dawit U. (M.Tech.) 63
  • 64. Using phpMyAdmin  phpMyAdmin is 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
  • 65. PHP Connect 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
  • 66.  PHP 5 and later can work with a MySQL database using: i. MySQLi extension (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 MySQLi or PDO?  The short answer would be "Whatever you like".  Both MySQLi and PDO have their advantages:  PDO will work on 12 different database systems, whereas MySQLi will only work with MySQL databases.  Both are object-oriented, but MySQLi also 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
  • 67. Opening Database Connection  Before we can access data in the MySQL database, we need to be able to connect to the server:  mysqli_connect function 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
  • 68. 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 (MySQLi Procedural)
  • 69. Compiled by: Dawit U. (M. Tech.) 69 <?php $servername = "localhost"; $username = "username"; $password = "password"; // Create connection $conn = new mysqli($servername, $username, $password); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } echo "Connected successfully"; ?> Example (MySQLi Object-Oriented)
  • 70. 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 MySQLi Object-Oriented: $conn->close(); MySQLi Procedural: mysqli_close($conn); PDO: $conn = null;
  • 71. Compiled by: Dawit U. (M.Tech.) 71 Example (MySQLi Object-oriented) <?php $servername = "localhost"; $username = "username"; $password = "password"; // Create connection $conn = new mysqli($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(); ?>
  • 72. Creating Database in PHP  PHP uses mysql_query function 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
  • 73. 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
  • 74. 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  UPDATE statement 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
  • 75. Exercise • Create a form with name and 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
  • 76. 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
  • 77. 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> <?php include 'footer.php';?> </body> </html> Compiled by: Dawit U. (M.Tech.) 77
  • 78. 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 warning but 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 or you may get plain  warning messages or nothing at all and halt the 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.  Use require when the file is required by the application.  Use include when the file is not required and application should continue when file is not found. Compiled by: Dawit U. (M.Tech.) 78
  • 79. Compiled by: Dawit U. (M. Tech.) 79 The PHP date() function is used to format a date and/or a time. PHP Date and Time Parameter Description format Required. Specifies the format of the timestamp timestamp Optional. Specifies a timestamp. Default is the current date and time Syntax date(format,timestamp)
  • 80. 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!