Chapter 5
Chapter 5
By: Behayilu M.
Faculty of Computing and Software Eng.,
Arba Minch Institute of Technology(AMiT),
Arba Minch University 1
Web design and Programming
Contents
• Introduction to server-side programming
• Server-side Languages
• PHP Basics
• What is PHP?
• Common uses of PHP
• PHP Pros and Cons
• Elements of PHP
• Installing
• Patterns for processing HTML forms
• Understanding $_GET, $_POST, $_SESSION and other PHP super-arrays
• Dynamically generating HTML
• Manipulating MySQL Databases with PHP
Web design and Programming 2
Introduction to Server-Side Scripting
• Is a technique used in web development which involves employing scripts on a web server
which produce a response customized for each user's (client's) request to the website.
• Is the general name for the kinds of programs which are run on the Server.
• Uses
• Process user input.
• Display pages.
• Structure web applications.
• Interact with permanent storage (SQL, files).
Server-side Languages
PHP
ASP
Ruby
Python
Java …
• It’s mainly due to its faster rate of loading over slow internet speed than another
programming language.
• It has less learning curve - easy
• Supports OOP
• Built-in database support minimizes dev time
• Very popular and huge community for support
• Flexible – can be combined with different languages
7
PHP Disadvantages
• It is not that secure due to its open-source, because the ASCII text file are often easily
available.
• Using more features of PHP framework and tools cause poor performance of online
applications.
• The PHP frameworks aren’t equivalent in behavior so does their performance and features.
• While PHP may be a powerful tool supported by an outsized community and plentiful
reference documentation, there are easier programming languages for web apps.
8
Installing PHP
• To install PHP, AMP (Apache, MySQL, PHP) software stack is suggested.
• XAMPP (Cross, Apache, MySQL, PHP, Perl) for Cross Platform: It includes some other
components too such as FileZilla, OpenSSL, Webalizer, Mercury Mail etc.
Web design and Programming 9
Web servers- xampp control panel
• Can be embedded anywhere in the html code, head ,body or inline with html tags depending on the need
of the programmer
• All PHP statements end with a semi-colon
<?php
if($condition){
?>
<b> This is True </b> Comments in PHP
// C++ and Java-style comment
<?php
# Shell-style comments
} else {
?> /* C-style comments
These can span multiple lines */
<b> This is False </b>
<?php
}
?> 12
Elements of PHP : Variables and Datatypes
• Variables in php are start with a dollar($) symbol followed by valid identifier name
• we did not have to tell PHP which data type the variable is.
• PHP automatically converts the variable to the correct data type, depending on its value.
$x = 5;
$y = 4; var_dump($x);//int(5) returns the data type of a variable
echo $x + $y;
?> 14
PHP Variables Scope
• Local Variables: Any variable used inside a user-defined function, however, has its scope
limited to the local function.
• Global variables are not available inside local functions unless declared with
the global keyword: <?php
<?php $x = 5;
$x = 5; // global scope $y = 10;
• 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 (although such usage is rare) while print can take one
argument. echo is marginally faster than print.
• The echo and print statement can be used with or without parentheses: echo or echo().
<?php
<?php
echo "<h2>PHP is Fun!</h2>";
print "<h2>PHP is Fun!</h2>";
echo "Hello world!<br>";
print "Hello world!<br>“;
echo("Hello world!”);
echo "This ", "string ", "was ", "made ", "with multiple parameters."; Print("I'm about to learn PHP!“);
$txt1 = "Learn PHP";
$txt1 = "Learn PHP";
echo "<h2>" . $txt1 . "</h2>";
echo "<h2>" . $txt1 . "</h2>";
?>
?> 16
PHP Constants
• Constants are like variables except that once they are defined they cannot be changed or undefined.
• The count() function is used to return the length (the number of elements) of an array:
18
• echo count($cars); // 3 echo $cars[1]; // BMW
…cont’d
• Loop Through an Indexed Array • Loop Through an Associative Array
<?php <?php
$cars = array("Volvo", "BMW", "Toyota"); $age = array("Peter"=>"35", "Ben"=>"37",
$arrlength = count($cars); "Joe"=>"43");
for($x = 0; $x < $arrlength; $x++) { foreach($age as $x => $x_value) {
echo $cars[$x]; echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>"; echo "<br>";
} }
?> ?>
• do...while:
do { statements; } while (expr);
• foreach:
• On each iteration, the value of the current element is assigned to $value and the internal
array pointerforeach
is advanced byasone.
($array $value) {
code to be executed;
}
• break
21
• continue
Loops - example
$value=array(“html", “css", “js", “php"", “mysql");
for ($j = 0; $j < 5; $j++) {
echo "Value is $array[$j] <br>"; for ($x = 0; $x < 10; $x++) {
} if ($x == 4) {
break;
$i = 1; }
do {
echo "The number is: $x
echo "This will execute at least once.";
$i++; <br>";
} while ($i < 10); }
$i = 0;
Elements of PHP
<?php
function familyName($fname, $year) {
echo "$fname . Born in $year <br>";
} Abebe kebede. Born in 1975
familyName(“Abebe kebede", "1975"); Selam Dawit. Born in 1978
familyName(“Selam Dawit", "1978"); Belay Syum. Born in 1983
familyName(“Belay Syum", "1983");
?>
23
PHP Include Files
• The include (or require) statement takes all the text/code/markup that exists in the specified file and copies it into the
e .html
om
welc welc
om e.ph
p
25
Patterns for processing HTML forms
• The PHP super-globals $_GET and $_POST are used to collect form-data.
• $_GET is used to collect form data sent with Get method
• $_POST is used to collect form data via Post method
• $_SESSION is used to perform session tracking in php
• $_FILES is an associate double dimension array and keeps all the information related
to uploaded file
• NB: - we should use PHP super-globals in capital letters only
• E.g : for a form control with a name attribute value of name we can write php code to
retrieve value entered as follows:
$_POST[‘name’] or $_GET[‘name’]
• When we have the following code in html
<input type=“text” name=“name” >
26
How to check form submission in PHP ?
• <input type = "submit" name = "submit" value = "Submit">
Syntax:
• if (!empty($_POST)) <form method="post">
• if (isset($_POST['submit']))
Enter value1 :<input type="text" name="str1"><br/>
• Use these two statements to check whether the form
Enter value2 :<input type="text" name="str2"><br/>
submitted successfully or not. <input type="submit" value="Sum"
• PHP isset() function is used to check if a variable has name="Submit1"><br/><br/>
been set or not.
<?php
if(isset($_POST["Submit1"]))
{
$sum=$_POST["str1"] + $_POST["str2"];
echo "The sum = ". $sum;
}
?>
27
Difference between GET and POST
GET vs POST Method in PHP
GET is a method that sends information by appending POST is a method that transfers information via HTTP
them to the page request. header.
URL
The form information is visible in the URL The form information is not visible in the URL
Information Amount
Limited amount of information is sent. It is less than
Unlimited amount of information is sent.
1500 characters.
Usage
Security
Not very secure. More secure.
Bookmarking the Page
Possible to bookmark the page Not possible to bookmark the page 28
Form
The data in a MySQL database are stored in tables. A table is a collection of related data, and it consists of
columns and rows.
• Earlier versions of PHP used the MySQL extension. However, this extension was deprecated
in 2012.
MySQLi (procedural)
// Create connection
$conn = mysqli_connect($servername, $username, $password);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
Web design and Programming 33
?>
PHP Create a MySQL Database
• PHP mysqli_query() function performs a query against database.
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$conn = mysqli_connect($servername, $username, $password);
// Check connection
f (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// Create database
$sql = "CREATE DATABASE myDB";
if (mysqli_query($conn, $sql)) {
echo "Database created successfully";
} else {
echo "Error creating database: " . mysqli_error($conn);
}
mysqli_close($conn);
?> Web design and Programming 34
PHP Create MySQL Tables
• A database table has its own unique name and consists of columns and rows.
<?php $conn = mysqli_connect($servername, $username, $password,”myDB”);
include “Connection.php”;
Connection.php
// sql to create table
$sql = "CREATE TABLE MyGuests (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
)";
if (mysqli_query($conn, $sql)) {
echo "Table MyGuests created successfully";
} else {
echo "Error creating table: " . mysqli_error($conn);
}
mysqli_close($conn);
?> Web design and Programming 35
PHP insert data into MySQL
• After a database and a table have been created, we can start adding data in them.
<?php
include “Connection.php”;
$sql = "INSERT INTO MyGuests (firstname, lastname, email) VALUES ('John', 'Doe', '[email protected]')";
if (mysqli_query($conn, $sql))
{
echo "New record created successfully";
}
else
{
echo "Error inserting data” . mysqli_error($conn);
}
mysqli_close($conn);
?> Web design and Programming 36
PHP insert multiple records into MySQL
• Multiple SQL statements must be executed with the mysqli_multi_query() function.
<?php
include “Connection.php”;
$sql = "INSERT INTO MyGuests (firstname, lastname, email) VALUES ('John', 'Doe', '[email protected]');";
$sql .= "INSERT INTO MyGuests (firstname, lastname, email) VALUES ('Mary', 'Moe', '[email protected]');";
$sql .= "INSERT INTO MyGuests (firstname, lastname, email) VALUES ('Julie', 'Dooley', '[email protected]')";
if (mysqli_multi_query($conn, $sql))
{
echo "New records created successfully";
} else {
echo "Error inserting data”. mysqli_error($conn);
}
mysqli_close($conn);
Web design and Programming 37
?>
PHP prepared statements
• A prepared statement is a feature used to execute the same (or similar) SQL statements repeatedly
with high efficiency.
• Prepare: An SQL statement template is created and sent to the database. Certain values are left
unspecified, called parameters (labeled "?"). Example: INSERT INTO MyGuests VALUES(?, ?, ?)
• The database parses, compiles, and performs query optimization on the SQL statement template,
and stores the result without executing it.
• Execute: At a later time, the application binds the values to the parameters, and the database
executes the statement. The application may execute the statement as many times as it wants with
different values.
Web design and Programming 38
PHP prepared statements
<?php
include "Connection.php";
$sql="insert into student(fname,lname,sex) values (?,?,?)"; sss(string,string,string)
$stmt=mysqli_prepare($con,$sql); (fname,lname,sex)
mysqli_stmt_bind_param($stmt,"sss",$fname,$lname,$sex);
$fname="Berihu";
$lname="Adane";
$sex="male";
if(mysqli_stmt_execute($stmt))
{
echo "Another student is inserted";
}
else
{
echo "error inserting table student".mysqli_error($con);
}
mysqli_stmt_close($stmt);
mysqli_close($con);
?> Web design and Programming 39
PHP select data from MySQL
• The SELECT statement is used to select data from one or more tables:
<?php
include "Connection.php";
$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
}
} else {
echo "0 results";
}mysqli_close($conn);
Web design and Programming 40
?>
PHP update data in MySQL
• The UPDATE statement is used to update existing records in a table:
<?php
include "Connection.php";
$sql = "UPDATE MyGuests SET lastname='Doe' WHERE id=2";
if (mysqli_query($conn, $sql)) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . mysqli_error($conn);
}
mysqli_close($conn);
?> Web design and Programming 41
PHP delete data from MySQL
• The DELETE statement is used to delete records from a table:
<?php
include "Connection.php"; How to delete a table
// sql to delete a record DROP MyGuests;
$sql = "DELETE FROM MyGuests WHERE id=3"; How to delete a database
DROP DATABASE mydb;
if (mysqli_query($conn, $sql)) {
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . mysqli_error($conn);
}mysqli_close($conn);
?> Web design and Programming 42
Selecting the database
• The mysqli_select_db() function is used to select a database.
<?php
$con=mysqli_connect("localhost","root","");
$db=mysqli_select_db($con,"dbstudent");
if(!$con)
{
die("Connection failed").mysqli_connect_errno();
}
else
{
echo "dbDB is selected";
}
?>
Web design and Programming 43
Practical Examples
• Assume that database is created with name: my_personal_contacts having a table named:
my_contacts which contain attributes (ID, Full Names, Gender, Contact No, Email, City,
Country)
<?php
$dbh = mysqli_connect("localhost", "root'') or
die("Unable to connect to MySQL: " . mysqli_error($dbh));
if (!mysqli_select_db($dbh, ‘my_personal_contacts'))
die("Unable to select database: " . mysqli_error($dbh));
?>
10/26/2024
practical examples
2. Inserting new records
<?php
include “dbconnection.php”;
$sql_stmt = "INSERT INTO `my_contacts`(`full_names`,`gender`,`contact_no`,`email`,`city`,`country`)";
$sql_stmt .= " VALUES('Peter','Male','541',' peter @ gmail.com ','AA','Ethiopia')";
$result = mysqli_query($dbh,$sql_stmt); //execute SQL statement
if (!$result)
die("Adding record failed: " . mysqli_error($dbh));
else
echo "Peter has been successfully added to your contacts list";
mysqli_close($dbh);
?>
10/26/2024
PHP Cookies
What is a Cookie?
• A cookie is a small file that the server embeds on the user's computer.
• Each time the same computer requests a page with a browser, it will send the cookie too.
• With PHP, you can both create and retrieve cookie values.
Syntax
<?php
if(!isset($_COOKIE[$cookie_name])) {
echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
echo "Cookie '" . $cookie_name . "' is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];
}
?>
</body>
48
</html>
Delete a Cookie Check if Cookies are Enabled
• To delete a cookie, use the setcookie() • The following example creates a small script that
checks whether cookies are enabled. First, try to create
function with an expiration date in the past:
a test cookie with the setcookie() function, then count
<?php
the $_COOKIE array variable:
// set the expiration date to one hour ago <?php
setcookie("user", "", time() - 3600); setcookie("test_cookie", "test", time() + 3600, '/');
?> ?>
<html> <html>
<body> <body>
<?php <?php
echo "Cookie 'user' is deleted."; if(count($_COOKIE) > 0) {
?> echo "Cookies are enabled.";
} else {
</body> echo "Cookies are disabled.";
</html> }
?> 49
PHP Sessions
• A session is a way to store information (in variables) to be used across multiple pages.
• Session variables hold information about one single user, and are available to all pages in
one application.
50
Start a PHP Session
• Creating, accessing, or deleting a session begins with the session_start( ) function.
• This function will attempt to send a cookie the first time a session is started, so it absolutely
must be called prior to any HTML or white space being sent to the Web browser.
• Therefore, on pages that use sessions, you should call the session_start() function as one of
the very first lines in your script.
• Session variables are set with the PHP global variable: $_SESSION.
• In this page, we start a new PHP session and set some session variables:
51
Start a PHP Session
<?php
// Start the session saves as
session_start(); demo_session1.php
?>
<!DOCTYPE html>
<html>
<body>
<?php
// Set session variables
$_SESSION["favcolor"] = "green";
$_SESSION["favanimal"] = "cat"; Session variables are set.
echo "Session variables are set.";
?>
</body>
</html>
52
Get PHP Session Variable Values
• Next, we create another page called "demo_session2.php". From this page, we will access the session information
we set on the first page ("demo_session1.php").
<?php
session_start(); saves as
?> demo_session2.php
<!DOCTYPE html>
<html>
<body>
<?php
// Echo session variables that were set on previous page Favorite color is green
Favorite animal is cat
echo "Favorite color is " . $_SESSION["favcolor"] . ".<br>";
echo "Favorite animal is " . $_SESSION["favanimal"] . ".";
?>
</body>
53
</html>
Modify a PHP Session Variable Destroy a PHP Session
• To change a session variable, just overwrite it: • To remove all global session variables and destroy the session,
use session_unset() and session_destroy():
<?php
<?php
session_start();
session_start();
?>
?>
<!DOCTYPE html> <!DOCTYPE html>
<html> <html>
<body> <body>
<?php
<?php
// remove all session variables
// to change a session variable, just overwrite it session_unset();
$_SESSION["favcolor"] = "yellow";
print_r($_SESSION); // destroy the session
session_destroy();
?>
?>
</body>
</body> 54
</html>
Exercise : create a signup page – with backend
55
56