10.7 Creates Dynamic Web Pages Using PHP and MySQL
10.7 Creates Dynamic Web Pages Using PHP and MySQL
7 CREATES DYNAMIC
WEB PAGES USING PHP
AND MYSQL
PRACTICAL BOOK
WHAT ARE STATIC AND DYNAMIC
WEB PAGES .
• Websites are separated into two different types: static and
dynamic.
• Static websites are ones that are fixed and display the
same content for every user, usually written exclusively in
HTML.
• A dynamic website, on the other hand, is one that can
display different content and provide user interaction, by
making use of advanced programming and databases in
addition to HTML. As you can tell, static websites are
easier to create, while dynamic websites require more
work.
WHAT IS A STATIC WEBSITE?
• Static
websites usually come with a fixed number of pages that have
a specific layout.
When the page runs on a browser, the content is literally static
and doesn’t change in response to user actions. A static
website is usually created with HTML and CSS in simple text
editors like Notepad.
WHAT IS A DYNAMIC WEBSITE?
• Web pages can be either static or dynamic. ... Other types of Web
pages, such as PHP, ASP, and JSP pages are dynamic Web pages.
These pages contain "server-side" code, which allows the server to
generate unique content each time the page is loaded
WHAT IS PHP?
• PHP is an acronym for "PHP: Hypertext Preprocessor"
• PHP is a widely-used, open-source scripting language
• PHP scripts are executed on the server
• PHP is free to download and use
WHAT IS A PHP FILE?
• PHP files can contain text, HTML, CSS, and PHP code
• PHP code is executed on the server, and the result is returned to the browser as plain HTML
• PHP files have extension ".php"
WHAT CAN PHP DO?
Google form
Name _________________ DB server
Age __________________
Address ______________
SUBMIT
WHY PHP?
<?php
// PHP code goes here
?>
A server-side script is processed on the web server when the user requests
information.
EX:- server-side languages include PHP, Python, Ruby and Java.
INSTALL PHP
• Install PHP - PHP
• Install a web server - Apache
• Install a database - MySQL
PHP COMMENTS
• A comment in PHP code is a line that is not executed as a part of the program.
• Its only purpose is to be read by someone who is looking at the code.
<?php
// This is a single-line comment
<?php
$x = 5;
$y = 4;
echo $x + $y;
?>
Output
9
WHAT IS A CONTROL STRUCTURE?
• In simple terms, a control structure allows you to control the
flow of code execution in your application.
• Generally, a program is executed sequentially, line by line, and a
control structure allows you to alter that flow, usually depending
on certain conditions.
• Control structures are core features of the PHP language that
allow your script to respond differently to different inputs or
situations.
• This could allow your script to give different responses based on
user input, file contents, or some other data.
PHP SUPPORTS A NUMBER OF DIFFERENT
CONTROL STRUCTURES:
• If
• If else
• If elseif
• while
• do-while
• for
PHP IF STATEMENT
• The if construct allows you to execute a piece of code if the expression provided
along with it evaluates to true.
<?php
$age = 50;
if ($age > 30)
{
echo "Your age is greater than 30!";
}
?>
PHP IF ELSE STATEMENT
• You always use the else statement in conjunction with an if statement.
<?php
$age = 50;
if ($age < 30)
{
echo "Your age is less than 30!";
}
else
{
echo "Your age is greater than or equal to 30!";
}
PHP IF ELSEIF STATEMENT
If you've got more than two choices to choose from, you can use
the elseif statement.
<?php
$age = 50;
if ($age < 30)
{echo "Your age is less than
30!";}
elseif ($age > 30 && $age < 40)
{echo "Your age is between 30
and 40!";}
elseif ($age > 40 && $age < 50)
{echo "Your age is between 40
and 50!";}
else
{echo "Your age is greater than
50!";}
?>
LOOPS IN PHP
• The while loop is used when you want to execute a piece of code repeatedly
while the condition is true. It will stop when the condition evaluates to false.
<?php
$x = 1;
while($x <= 5)
{ echo "The number is: $x <br>";
$x=$x+1;}
// $x=$x+1 also can be written like $x++
?>
EXAMPLE
<?php
$x = 1;
while($x <= 5)
{ echo "The number is: $x <br>";
$x=$x+1;}
// $x=$x+1 also can be written like $x++
?>
The number is: 1
The number is: 2
The number is: 3
The number is: 4
The number is: 5
DO-WHILE LOOP IN PHP
• The do-while loop is very similar to the while loop, with the only difference being
that the while condition is checked at the end of the first iteration.
• Thus, we can guarantee that the loop code is executed at least once, irrespective of
the result of the while expression.
EXAMPLE
<?php
$x = 1;
do {
echo "I like ICT <br>";
$x++;
} while ($x <= 5);
?>
//X = x+1 also (x++)
EXAMPLE 2
<?php
$x = 6;
do {
echo "I like ICT <br>";
$x++;
} while ($x <= 5);
?>
FOR LOOP IN PHP
• Generally, the for loop is used to execute a piece of code a specific number of times.
• In other words, if you already know the number of times you want to execute a block of
code, it's the for loop which is the best choice.
• Example Explained
• $x = 0; - Initialize the loop counter ($x), and set the start value to 0
• $x <= 10; - Continue the loop as long as $x is less than or equal to 10
EXAMPLE
<?php
for ($x = 0; $x <= 100; $x+=10) {
echo "The number is: $x <br>";
}
?>
ANSWER
The number is: 0
The number is: 10
The number is: 20
The number is: 30
The number is: 40
The number is: 50
The number is: 60
The number is: 70
The number is: 80
The number is: 90
The number is: 100
CONCATENATION
• There are string (String is a sequence of characters, like "Nice day") operators provided by
PHP.
• Concatenation Operator ("."):
This operator combines two string values and returns it as a new string.
<?php
//concatenate text
$text1="Dear Students";
$text2="Nice Day";
. .
echo $text1 "," $text2;
?>
Output
Dear Students,Nice Day
Concatenate string with comma(,)
• We can use Comma as a concatenation operator in php to multiple
parameters
Example :
echo 'Multiple Parameter ', 'Example With ', ' echo.’;
Output:
Multiple Parameter Example With echo.
PHP DATA TYPES
• 1. String
• 2. Integer
• 3. Float
• 4. Boolean
• 5. Array
01) PHP STRING
. .
echo $text1 ", " $text2;
echo "<br/>";
.
echo "No of words =" str_word_count($text2);
echo "<br/>";
//Character length
echo "No of characters in '$text2'
.
=" strlen($text2);
echo "<br/>";
//Reverse Order
echo strrev($text2);
echo "<br/>";
//Word replace
echo str_replace("Nice", "Good", $text2);
PHP INTEGER
• An integer data type is a non-decimal number between -2,147,483,648 and
2,147,483,647
Ex: 1.2
83.4
32
04) PHP BOOLEAN
• The PHP var_dump() function returns the data type and value:
Syntax:
array();
Ex:
<?php
$weekdays = array("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday",
"Friday", "Saturdey");
var_dump($weekdays);
?> OUTPUT
array(7) {
[0]=> string(6) "Sunday"
[1]=> string(6) "Monday"
[2]=> string(7) "Tuesday"
[3]=> string(9) "Wednesday"
[4]=> string(8) "Thursday"
[5]=> string(6) "Friday"
[6]=> string(8) "Saturday" }
EXERCISE
Ex03: Ex06: <?php
<?php $x = 5;
Ex01 $txt = “ICT"; $y = 4;
echo "I love $txt!"; echo $x + $y;
<?php ?> ?>
echo "Welcome ";
echo "ICT Students"; Ex07
Ex04: <?php
echo "<br/> This is a PHP text.";
<?php $x = 5;
?> $txt = “ICT”; $y = 4;
echo "I love " . $txt . "!"; $tot = $x+$y;
?> echo "Total is ", $tot;
Ex02:
?>
<?php Ex05:
$text="Nice Day"; <?php Ex08
$txt = “ICT"; <?php
$x=200;
echo "I love "."<br/>" . $txt . "!"; $x=10/*+30*/+5;
$y = 10.5; ?> echo 'Answer is '.$x;
?> ?>
SAVING PHP FILES…
• In PHP, keywords (e.g. if, else, while, echo, etc.), classes, functions, and user-
defined functions are not case-sensitive.
• In the example below, all three echo statements below are equal and legal:
Example
<!DOCTYPE html>
<html>
<body>
<?php
ECHO "Hello World!<br>";
echo "Hello World!<br>";
EcHo "Hello World!<br>";
?>
</body>
</html>
Note: However; all variable names are case-sensitive!
Example
<!DOCTYPE html>
<html>
<body>
<?php
$color = "red";
$COLOR = “blue”;
$coLOR = “white”;
/* Multiple line
comment here…
*/
<?php
$x=10/*+30*/+5; //middle of the line comment
echo 'Answer is '.$x;
?>
PHP FUNCTIONS
• The real power of PHP comes from its functions.
• PHP has more than 1000 built-in functions, and in addition you can create your own custom
functions.
Note that while creating a function its name should start with keyword function and all
the PHP code should be put inside { and } braces as shown in the following example
below −
Syntax
function functionName() {
code to be executed;
}
<?php
function writeMsg() {
echo "Hello world!";
}
?>
EXAMPLE 2
<?php
?>
BUILT-IN FUNCTIONS
Example :-
<?php
echo chr(52) . "<br>"; // Decimal value
echo chr(052) . "<br>"; // Octal value
echo chr(0x52) . "<br>"; // Hex value
?>
BUILT-IN FUNCTIONS
<?php
echo "Hello world!";
?>
BUILT-IN FUNCTIONS
Example :- Remove characters from both sides of a string ("He" in "Hello" and "d!" in "World"):
<?php
$str = "Hello World!";
echo $str . "<br>";
echo trim($str,"Hed!");
?>
BUILT-IN FUNCTIONS
• getFile() Returns the full path of the file in which the exception was thrown
Example :- Throw an exception and output the path of the file in which the exception occurred:
<?php
try {
throw new Exception("An error occurred");
} catch(Exception $e) {
echo "Error in this file: " . $e->getFile();
}
?>
BUILT-IN FUNCTIONS
Example :- Create an indexed array named $cars, assign three elements to it, and then print a text
containing the array values:
<?php
$cars=array("Volvo","BMW","Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
?>
PHP MYSQL DATABASE
• Employees
• Products
• Customers
• Orders
PHP + MYSQL DATABASE SYSTEM
PHP combined with MySQL are cross-platform
Database Queries
• A query is a question or a request.
• We can query a database for specific information and have a
recordset returned.
• Look at the following query (using standard SQL):
SELECT LastName FROM Employees
• The query above selects all the data in the "LastName" column
from the "Employees" table.
OPEN A CONNECTION TO MYSQL
• Before we can access data in the MySQL database, we need to be able to connect to
the server:
Example
• <?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";
?>
CLOSE THE CONNECTION
• $conn->close();
A database consists of one or more tables.
You will need special CREATE privileges to create or to delete a MySQL database.
// Create database
$sql = "CREATE DATABASE myDB";
if ($conn->query($sql) === TRUE) {
echo "Database created successfully";
} else {
echo "Error creating database: " . $conn->error;
}
$conn->close();
?>
CREATE A MYSQL TABLE USING
MYSQLI
• The CREATE TABLE statement is used to create a table in MySQL.
• We will create a table named "MyGuests", with five columns: "id",
"firstname", "lastname", "email“.
The INSERT INTO statement is used to add new records to a MySQL table:
INSERT INTO table_name (column1, column2, column3,...)
VALUES (value1, value2, value3,...)
EXAMPLE
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);}
//insert data into table
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', '[email protected]')";
THE FOLLOWING EXAMPLE SELECTS THE ID, FIRSTNAME AND LASTNAME COLUMNS FROM THE MYGUESTS
TABLE AND DISPLAYS IT ON THE PAGE:
<?php
$servername = "localhost";
$username = "username"; id firstyname lastname
$password = "password"; 1 John Doe
$dbname = "myDB"; 2 Mary Moe
// Create connection
3 Julie Dooley
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);}
$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";} }
else {
echo "0 results";}
$conn->close();
First, we set up an SQL query that selects the id, firstname and
lastname columns from the MyGuests table.
The next line of code runs the query and puts the resulting data
into a variable called $result.
Then, the function num_rows() checks if there are more than
zero rows returned.
If there are more than zero rows returned, the function
fetch_assoc() puts all the results into an associative array that
we can loop through. (dictinaray that can hold data (key,value))
The while() loop loops through the result set and outputs the
data from the id, firstname and lastname columns
$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = $conn->query($sql);
if ($result->num_rows > 0) {