Server Side Scripting PHP
Server Side Scripting PHP
PHP
What is PHP?
Interpreted language
•scripts are parsed at run-time
rather than compiled beforehand
•Executed on the server-side
•Source-code not visible by client
‘View Source’ in browsers does
not display the PHP code
•Various built-in functions allow
for fast development
•Compatible with many popular
databases
PHP Introduction
 The PHP code is enclosed in special start and end processing instructions
 <?php and ?> that allow you to jump into and out of “PHP mode”.
PHP Introduction…
 PHP code is executed on the server, generating HTML which is then sent to
 the client.
 The client would receive the results of running that script, but would not
 know what the underlying code was.
PHP Hello World
<html>
 <head>
 <title>PHP Test</title>
 </head>
 <body>
 <?php echo ‘<p>Hello World</p>’; ?>
 </body>
</html>
PHP Hello World…
<html>
 <head>
 <title>PHP Test</title>
 </head>
 <body>
 <p>Hello World</p>
 </body>
</html>
PHP Hello World…
 Think of this as a normal HTML file which happens to have a set of special
 tags available to you that do a lot of interesting things.
PHP hello world…
> Script Tag
<html>
 <head>
 <title>PHP Test</title>
 </head>
 <body>
 <script language=“php”> print ‘<p>Hello World</p>’;
</script>
 </body>
</html>
PHP Comments
 In PHP, we use // or # to make a single-line comment or /* and */ to make a large
 (multiline) comment block.
<html>
<body>
<?php
//This is a comment
/*
This is
a comment
block
 */
VARIABLES $VAR
PHP
PHP Variables
 Variables are used for storing values, like text strings, numbers or arrays.
 When a variable is declared, it can be used over and over again in your
 script.
 All variables in PHP start with a $ sign symbol.
 The correct way of declaring a variable in PHP:
 $var_name = value;
PHP Variables…
<?php
 $txt = “Hello World!”;
 $x = 16;
?>
 PHP is a Loosely Typed Language
 In PHP, a variable does not need to be declared before adding a value to it.
 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 its value.
PHP Variables…
 <?php
 $greeting = “Hello World!”;
 echo $greeting;
 php?>
 String
  $str = “I am a string :)”;
 Integer
  $int = 22;
 Boolean
  $bool = TRUE; // with echo, displayed as 1 and empty value for 0.
 Float
  $float = 1.234;
  $float2 = 3.1415927;
  $float3 = 5.3e7;
PHP Basic Types
 <? php
 $foo = “I am set!”;
 $foo2 = “I am also set!”;
 $int = 22;
 $bool = TRUE;
 ?>
PHP Basics
> isset(), empty(), and unset…
 Example:
 Example:
  define(“UPPER_LIMIT”, 1000); // Recommended to write using uppercase
  echo UPPER_LIMIT;
PHP
PHP Operators
 || or x=6
 y=3
 (x == 5 || y == 5) returns
 false
 ! not x=6
 y=3
 Very often when you write code, you want to perform different actions for
 different decisions.
 You can use conditional statements in your code to do this.
 In PHP we have the following conditional statements…
PHP Conditional Statements…
 The following example will output “Have a nice weekend!” if the current day
 is Friday:
<html>
 <body>
 <?php
 $d=date(“D”);
 if ($d==“Fri”) echo “Have a nice weekend!”;
 ?>
 </body>
</html>
PHP Conditional Statements…
 Use the if…else statement to execute some code if a condition is true and another
 code if a condition is false.
<html>
 <body>
 <?php
 $d=date(“D”);
 if ($d==“Fri”)
 echo “Have a nice weekend!”;
 else
 echo “Have a nice day!”;
 ?>
 </body>
</html>
PHP Conditional Statements…
 If more than one line should be executed if a condition is true/false, the lines should be enclosed
 within curly braces {}
<html>
 <body>
 <?php
 $d=date(“D”);
 if ($d==“Fri”)
 {
 echo “Hello!<br />”;
 echo “Have a nice weekend!”;
 echo “See you on Monday!”;
 }
 ?>
 </body>
</html>
 PHP Conditional Statements…
 The following example will output “Have a nice weekend!” if the current day is Friday, and “Have
 a nice Sunday!” if the current day is Sunday. Otherwise it will output “Have a nice day!”
<html>
 <body>
 <?php
 $d=date(“D”);
 if ($d==“Fri”)
 echo “Have a nice weekend!”;
 elseif ($d==“Sun”)
 echo “Have a nice Sunday!”;
 else
 echo “Have a nice day!”;
 ?>
 </body>
</html>
 PHP Conditional Statements…
 > Example
 Use the switch statement to select one of many blocks of code to be executed.
switch (n)
{
 case value1:
 code to be executed if n== value1;
 break;
 case value2:
 code to be executed if value2;
 break;
 default:
 code to be executed if n is different from both value1 and value2;
}
PHP Conditional Statements…
<html>
<body>
 <?php
 switch ($x)
 {
 case 1:
 echo “Number 1”;
 break;
 case 2:
 echo “Number 2”;
 break;
 PHP Conditional Statements…
 case 3:
 echo “Number 3”;
 break;
 default:
 echo “No number between 1 and 3”;
 }
 ?>
</body>
</html>
PHP Loops
 Often when you write code, you want the same block of code to run over
 and over again in a row.
 Instead of adding several almost equal lines in a script we can use loops to
 perform a task like this.
PHP Loops…
<?php
 $x = 0;
 while ($x < 5) {
 echo ‘.’;
 $x++;
 }
?>
PHP Loops…
> While
<?php
 $x = 0;
 while ($x < 5) :
 echo ‘.’;
 $x++;
 endwhile;
?>
PHP Loops
> Do … While
<?php
 $x = 1;
 do
 {
 $x++;
 echo “The number is ” . $x . “<br />”;
 }
 while ($i<=5);
?>
PHP Loops…
> For
<?php
 for ($x = 0; $x < 5; $x++) {
 echo ‘.’;
 }
?>
PHP Loops…
> Foreach
<?php
 $x = array(0, 1, 2, 3, 4);
 foreach ($x as $y) {
 echo $y;
 }
?>
PHP Loops…
> Foreach (Key/Value Pairs)
<?php
 $talks = array(
 ‘php’ => ‘Intro to PHP’,
 ‘ruby’ => ‘Intro to Ruby’
 );
 foreach ($talks as $id => $name) {
 echo “$name is talk ID $id.”;
 echo “<br />”;
 }
?>
PHP Loops…
> Infinite Loops
 With an infinite loop you have to hit stop on the browser, or add some
 syntactically error on your php file and save it to stop the loop.
ARRAYS $NAMES=ARRAY();
PHP
PHP Arrays
 If you have a list of items (a list of car names, for example), storing the cars
 in single variables could look like this:
 $cars1=“Saab”;
 $cars2=“Volvo”;
 $cars3=“BMW”;
PHP Arrays…
 However, what if you want to loop through the cars and find a specific one?
 And what if you had not 3 cars, but 300?
 The best solution here is to use an array.
 An array can hold all your variable values under a single name. And you can
 access the values by referring to the array name.
 Each element in the array has its own index so that it can be easily
 accessed.
PHP Arrays…
 In the following example you access the variable values by referring to the
 array name and index:
<?php
 $cars[0] = “Saab”;
 $cars[1] = “Volvo”;
 $cars[2] = “BMW”;
 $cars[3] = “Toyota”;
 echo $cars[0] . “ and “ . $cars[1] . “ are Swedish cars.”;
?>
Output: Saab and Volvo are Swedish cars.
Getting the length of an array
 <?php
 $cars = array("Volvo", "BMW", "Toyota");
 echo count($cars);
 ?>
 <?php
 $cars = array("Volvo", "BMW", "Toyota");
 echo sizeof($cars);
 ?>
 <?php
 $cars = array("Volvo", "BMW", "Toyota");
 print_r($cars); // Array ( [0] => Volvo [1] => BMW [2] => Toyota )
 ?>
PHP Associative Arrays…
 $ages[‘Peter’] = “32”;
 $ages[‘Quagmire’] = “30”;
 $ages[‘Joe’] = “34”;
PHP Associative Arrays…
<?php
 $ages[‘Peter’] = “32”;
 $ages[‘Quagmire’] = “30”;
 $ages[‘Joe’] = “34”;
 Calculate the average expense for each expenses in each term from the
 following array?
 $expenses=array(30,44,55,11,24);
 Hint:-use count(expense) for the number of expenses.
PHP String Concatenation
 The concatenation operator (.) is used to put two string values together.
 <?php
 $txt1 = “Hello World!”;
 $txt2 = “What a nice day!”;
 echo $txt1 . “ ” . $txt2;
 ?>
 OUTPUT
 Hello World! What a nice day!
PHP String Char Index
 <?php
 $str = “0123456789”;
 $str2 = $str;
 $str2[4] = “X”;
 $str2[6] = “Y”;
 ?>
 PHP String Char Index
 <?php
 $str3 = “The string ends in escape:”;
 $str3 .= chr(32).chr(55); // add a space and the number 7 as
two ascii characters
 echo $str3;
 <?php
 echo strlen(“Hello world!”);
 ?>
PHP Strings…
> Important String Functions
 Comparison
  strcmp(str1, str2); // returns 0, <0, >0
 String Position
  strpos(haystack, needle, offset[optional); //returns index (or FALSE)
  Needle is the string you want to find; haystack is the string to be searched.
  Offset: optional. Offset from the left. Starting position
 String Replace
  str_replace(“%name%”, $name, $template);
  str_replace($arr, $repwith, $originalstring); // can also take array and return new string
PHP Strings…
> Important String Functions…
 Sub String
  substr($str, 1, 5); // the last parameter is optional, returns a string
  Also takes negative values.
 Case Functions
  strupper($str); // returns a string (upper case)
  strlower($str); // returns a string (lower case)
  ucfirst($str); // capitalize first letter of first word
  ucwords($str); // capitalize first letter of every word
PHP Strings…
> Important String Functions…
 Cleaning up strings
  ltrim($str); // removes spaces on the left of a string
  rtrim($str); // removes spaces on the right of a string
  chop($str); // removes spaces on the right of a string (alias for rtrim)
  trim($str); // removes spaces on the left and right of a string
PHP Strings…
> Literal Single Quotes
 <?php
 $x = 2;
 Echo ‘I ate $x cookies.’;
 // I ate $x cookies.
 ?>
PHP Strings…
> Double Quotes
 <?php
 $x = 2;
 Echo “I ate $x cookies.”;
 // I ate 2 cookies.
 ?>
PHP Strings…
> Literal Double Quotes
 <?php
 $x = 2;
 Echo “I ate \$x cookies.”;
 // I ate $x cookies.
 ?>
PHP Strings…
> Curly Brace – Double Quotes
 <?php
 $x = 2;
 Echo “I ate {$x} cookies.”;
 // I ate 2 cookies.
 ?>
 The PHP Date() Function
 Wednesday/04/2024
  <?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");
 ?> Day of d 01
 Month
 Day of J 1
M Jan Month
F January Day of l Monday
 Week
m 01
 Day of D Mon
n 1 Week
 created by zelalem Abera-HilCoe-Web - Technology 82
Exercise
Wednesday/04/2019
 To keep the script from being executed when the page loads, you can put it
 into a function.
 A function will be executed by a call to the function.
 You may call a function from anywhere within a page.
 function functionName()
 {
 code to be executed;
 }
 Give the function a name that reflects what the function does
 The function name can start with a letter or underscore (not a number)
PHP Functions…
 <html>
 <body>
 <?php
 function wirteName()
 {
 echo “Tadios N. Demma”;
 }
 echo “My name is “;
 writeName();
 ?>
 </body>
 </html>
PHP Functions…
 Adding parameters…
 To add more functionality to a function, we can add parameters.
 A parameter is just like a variable.
 Parameters are specified after the function name, inside the
 parentheses.
PHP Functions…
 A function that write different first names, but equal last name:
 <html>
 <body>
 <?php
 function writeName($fname)
 {
 echo $fname . “ Demma. <br />”;
 }
 A function that write different first names, but equal last name…
 …
 echo “My sister’s name is ”;
 writeName(“Martha”);
 echo “My brother’s name is ”;
 writeName(“Ezra”);
 ?>
 </body>
 </html>
Passing by reference
 Use the & sign on the function so that variables can be passed by a
 reference.
 function my_function(&$myparameter)
 {
 // your function definition
 }
Variable Scope
 Variables that are not defined inside a function are visible at the page level.
 Variables inside a function are only visible inside the function definition.
 Page level variables are not global variables in PHP.
 To set a variable as global use the global variable.
  global $myVariable;
  $GLOBALS[‘str’] = “sample data”;
  echo $str;
PHP Include File
 Server Side Includes (SSI) are used to create functions, headers, footers, or
 elements that will be reused on multiple pages.
 You can insert the content of a file into a PHP file before the server executes
 it, with the include() or require() function.
 The two functions are identical in every way, except how they handle
 errors.
 The include() function generates a warning (but the script will continue
 execution) while the require() function generates a fatal error (and the
 script execution will stop after the error).
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.
 Assume that you have a standard header file, called “header.php”. To
 include the header file in a page, use the include() function, like this:
<html> <body>
<?php include("header.php"); ?>
<h1>Welcome to my home page</h1>
<p>Some text</p>
</body> </html>
//lets assume the “header.php” file <?php echo “from the header file”; ?>
 The include() Function…
 menu.php
<html><head>
<title>Default Page</title> </head>
<body>
<?php include("menu.php"); ?>
<h1>Welcome to my homepage</h1>
<p>Some text</p>
The require() Function
 The PHP $_GET and $_POST variables are used to retrieve information from
 forms, like user input.
 PHP Form Handling
  The most important thing to notice when dealing with HTML forms and PHP is that any
 form element in an HTML page will automatically be available to your PHP scripts.
PHP $_GET
When the user clicks the “Submit” button, the URL sent could look something
like this:
http://www.somewebsite.com/welcome.php?fname=Peter&age=37
 $_GET Variable…
 > welcome.php
<html><body>
Welcome
<?php
 echo $_GET[“fname”];
?>
<br/>
You are
<?php
 echo $_GET[“age”];
?>
years old.
PHP $_POST
When the user clicks the “Submit” button, the URL sent could look something
like this:
http://www.somewebsite.com/welcome.php
So where is the data, the data is hidden in the request object.
 $_POST Variable…
 > welcome.php
<html><body>
Welcome
<?php
 echo htmlspecialchars($_POST[“name”]);
?>
<br/>
You are
<?php
 echo (int)$_ POST[“age”];
?>
years old.
$_POST Variable…
 htmlspecialchars() – makes sure any characters that are special in html are
 properly encoded so people can’t inject HTML tags or JavaScript into your
 page.
 (int) – For the age field, since we know it is a number, we can just convert it
 to an integer which will automatically get rid of any stray characters. The
 $_POST[‘name’] and $[‘age’] variables are automatically set for you by PHP.
Why use $_POST?
 Variables sent with HTTP POST are not shown in the URL
 Variables have no length limit
 However, because the variables are not displayed in the URL, it is not
 possible to bookmark the page.
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
 Opening a File
  The fopen() function is used to open files in PHP.
  The first parameter of this function contains the name of the file to be opened and the
 second parameter specifies in which mode the file should be opened:
 <html>
 <body>
 <?php
 $file=fopen(“welcome.txt”, “r”);
 ?>
 </body>
 </html>
 Note: If the fopen() function is unable to open the specified file, it
 returns 0 (false)
PHP File Handling…
Modes Description
r Read only. Starts at the beginning of the file
r+ Read/Write. Starts at the beginning of the file
w Write only. Opens and clears the contents of file; or creates a new file if
 it doesn’t exist.
w+ Read/Write. Opens and clears the contents of file; or creates a new file if
 it doesn’t exist.
a Append. Opens and writes to the end of the file or creates a new file if it
 doesn’t exist.
a+ Read/Append. Preserves file content by writing to the end of the file
x Write only. Creates a new file. Returns FALSE and an error if file already
 exists
x+ Read/Write. Creates a new file. Returns FALSE and an error if file already
Closing a file
 <?php
 $file = fopen(“text.txt”, “r”);
 //some code to be executed
 fclose($file);
 ?>
Check end-of-file
 The feof() function checks if the “end-of-file” (EOF) has been reached.
  The feof() function is useful for looping through data of unknown length.
 Note: After a call to this function the file pointer has moved to the next line.
 Example: The example below reads a file line by line, until the end of file is
 reached:
<?php
 $file = fopen(“welcome.txt”, “r”) or exit(“Unable to open file!”);
 //Output a line of the file until the end is reached
 while(!feof($file))
 {
 echo fgets($file) . “<br />”;
 }
 fclose($file);
?>
Reading a file character by character
 <?php
 $file = fopen(“welcome.txt”, “w”) or exit(“Unable to open
file!”);
 if ($file)
 fwrite($file, “Some Text”);
 fclose($file);
 ?>
 PHP file upload
<html>
 </body>
 <form action=“upload_file.php” method=“post” enctype=“multipart/form-
data”>
 <label for=“file”>Filename:</label>
 <input type=“file” name=“file” id=“file” /> <br/>
 <input type=“submit” name=“submit” value=“Submit” />
 </form>
 </body>
</html>
 PHP file upload…
 > Things to notice on the previous slide
<?php
 if ($_FILES[“file”][“error”] > 0) {
 echo “Error: ” . $_FILES[“file”][“error”] . “<br />”;
 }
 else {
 echo “Upload: ” . $_FILES[“file”][“name”] . “<br />”;
 echo “Type: ” . $_FILES[“file”][“type”] . “<br />”;
 echo “Size: ” . ($_FILES[“file”][“size”] / 1024) . “Kb<br />”;
 echo “Stored in: ” . $_FILES[“file”][“tmp_name”] . “<br />”;
 }
?>
 By using the global PHP $_FILES array you can upload files from a client computer
Creating the upload script…
 The first parameter is the form’s input name and the second index can be
 either “name”, “type”, “size”, “tmp_name” or “error”. Like this:
  $_FILES[“file”][“name”] – the name of the uploaded file
  $_FILES[“file”][“type”] – the type of the uploaded file
  $_FILES[“file”][“size”] – the size in bytes of the uploaded file
  $_FILES[“file”][“tmp_name”] – the name of the temporary copy of the file stored on the
 server
  $_FILES[“file”][“error”] – the error code resulting from the file upload
 Saving the uploaded file
 The temporary copied files disappears when the script ends. To store the uploaded file we need to
 copy it to a different location:
<?php
 if ((($_FILES["file"]["type"] == "image/gif") || ($_FILES["file"]["type"] == "image/jpeg") ||
($_FILES["file"]["type"] == "image/pjpeg") ) && ($_FILES["file"]["size"] < 20000))
 {
 if ($_FILES["file"]["error"] > 0)
 {
 echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
 }
 else
 {
 echo "Upload: " . $_FILES["file"]["name"] . "<br />";
 echo "Type: " . $_FILES["file"]["type"] . "<br />";
 echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
 Saving the uploaded file…
 if (file_exists("upload/" . $_FILES["file"]["name"]))
 {
 echo $_FILES["file"]["name"] . " already exists. ";
 }
 else
 {
 move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $_FILES["file"]["name"]);
 echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
 }
 }
}
else
{
 echo "Invalid file";
}
Saving the uploaded file…
 The script above checks if the file already exists, if it does not, it copies the
 file to the specified folder.
 Note: This example saves the file to a folder called “upload”
PHP Sessions
 Save the user’s name in the session so that you don’t have to query the
 database every time you need
 Setting font preferences for users.
 And others…
 Sessions work by creating a unique id (UID) for each visitor and store
 variables based on this UID.
How to of a Session
> Starting a PHP Session
 Before you can store user information in you PHP session, you must first
 start up the session.
 Note: The session_start() function must appear BEFORE the <html> tag:
<?php
 session_start();
?>
<html></body>
</body></html>
 The code above will register the user’s session with the server, allow you to
 start saving user information, and assign a UID for the user’s session.
 How to of a Session
 > Storing a Session Variable
 The correct way to store and retrieve session variables is to use the PHP $_SESSION
 variable:
<?php
 session_start();
 // store session data
 $_SESSION['views']=1;
?>
<html> <body>
<?php
 //retrieve session data
 echo "Pageviews=". $_SESSION['views']; ?>
</body> </html>
 A simple page view counter
 The isset() function checks if the “views” variable has already been set.
 If “views” has been set, we can increment our counter. If “views” doesn’t
 exist, we create a “views” variable, and set it to 1:
<?php
 session_start();
 if(isset($_SESSION['views']))
 $_SESSION['views']=$_SESSION['views']+1;
 else
 $_SESSION['views']=1;
 echo "Views=". $_SESSION['views'];
MySQL
 Before you can access and work with data in a database, you must create a
 connection to the database.
 In PHP, this is done with the mysqli_connect() function.
 Syntax
 Parameter Description
 servername Optional. Specifies the server to connect to.
 Default value is “localhost:3306”
 username Optional. Specifies the username to login with.
 Default value is the name of the user that owns
 the server process
 password Optional. Specifies the password to log in with.
 Default is “”
Connecting to MySQL Database…
 Example:
  In the following example we store the connection in a variable ($con) for later use in the
 script. The “die” part will be executed if the connection fails:
 <?php
 $con = mysqli_connect("localhost", "root", "P@ssw0rd");
 if (!$con)
 {
 die('Could not connect: ' . mysqli_connect_error());
 }//some code
 ?>
Closing a connection
 The connection will be closed as soon as the script ends. To close the
 connection before, use the mysqli_close() function.
 <?php
 $con = mysqli_connect("localhost", "root", "P@ssw0rd");
 if (!$con)
 {
 die('Could not connect: ' . mysqli_connect_error());
 }//some code
 mysqli_close($con);
 ?>
Create Database and Tables
 Create a Database
  The CREATE DATABASE statement is used to create a database in MySQL.
 Syntax
  CREATE DATABASE database_name
 To get PHP to execute the statement above we must use the mysqli_query()
 function. This function is used to send a query or command to a MySQL
 connection.
 Create Database Example
<?php
 $con = mysqli_connect("localhost", "root", "P@ssw0rd");
 if (!$con)
 {
 die('Could not connect: ' . mysqli_connect_error());
 }
 if (mysqli_query($con, "CREATE DATABASE my_db"))
 {
 echo "Database created";
 Create Database Example…
 else
 {
 echo "Error creating database: " .mysqli_error($con);
 }
 mysqli_close($con);
?>
Creating Table
 The following example shows how you can create a table named “person”, with
 three columns. The column names will be “FirstName”, “LastName” and “Age”:
<?php
 $con = mysqli_connect("localhost","root","P@ssw0rd");
 if (!$con)
 {
 die('Could not connect: ' . mysqli_connect_error());
 }
 // Create database
 if (mysqli_query($con, "CREATE DATABASE my_db"))
 {
 Creating Table…
<?php
 $con = mysqli_connect("localhost","root","P@ssw0rd", "my_db");
 if (!$con) { die('Could not connect: ' . mysqli_connect_error()); }
 mysqli_query($con, "INSERT INTO person (FirstName, LastName,
Age) VALUES
 ('Tadios', 'Demma', '35')");
 mysqli_query($con, "INSERT INTO person (FirstName, LastName,
Age) VALUES
 ('Ezra', 'Demma', '33')");
 mysqli_close($con);
?>
Insert a Data From a Form into a Database
 //register.htm
<html><body>
 <form action="insert.php" method="post">
 Firstname: <input type="text" name="firstname" />
 Lastname: <input type="text" name="lastname" />
 Age: <input type="text" name="age" />
 <input type="submit" value= "register" />
 </form>
</body> </html>
 Insert a Data From a Form into a Database…
 //Insert.php
<?php
 $con = mysqli_connect("localhost","root","P@ssw0rd", "my_db");
 if (!$con) { die('Could not connect: ' . mysqli_connect_error()); }
 $sql="INSERT INTO person (FirstName, LastName, Age) VALUES
('$_POST[firstname]','$_POST[lastname]','$_POST[age]')";
 if (!mysqli_query($con, $sql))
 {
 die('Error: ' . mysqli_error($con));
 }
 echo "1 record added";
 mysqli_close($con);
 Update Data in a Database
<?php
 $con = mysqli_connect("localhost","root","P@ssw0rd",
"my_db");
 if (!$con)
 {
 die('Could not connect: ' . mysqli_connect_error());
 }
 mysqli_query($con , "UPDATE Person SET Age = '36' WHERE
FirstName = 'Tadios' AND LastName = 'Demma'");
 mysqli_close($con);
?>
Delete Data in a Database
<?php
 $con = mysqli_connect("localhost","root","P@ssw0rd", "my_db");
 if (!$con)
 {
 die('Could not connect: ' . mysqli_connect_error());
 }
 mysqli_query($con, "DELETE FROM Person WHERE
LastName='Demma'");
 mysqli_close($con);
?>
 Selecting Data From Database and Displaying it in
 HTML Table
<?php
 $con = mysqli_connect("localhost", "root", "P@ssw0rd",
"my_db");
 if (!$con)
 {
 die('Could not connect: ' . mysqli_connect_error());
 }
 $result = mysqli_query($con, "SELECT * FROM person");
 echo "<table border='1'> <tr> <th>Firstname</th>
 <th>Lastname</th> </tr>";
 Selecting Data From Database and Displaying it in
 HTML Table…
 while($row = mysqli_fetch_array($result))
 {
 echo "<tr>";
 echo "<td>" . $row['FirstName'] . "</td>";
 echo "<td>" . $row['LastName'] . "</td>";
 echo "</tr>";
 }
 echo "</table>";
 mysqli_close($con);
?>
NOTE: //Use mysqli_fetch_object method for single value (single column, single row)
 The Where Clause
<?php
 $con = mysqli_connect("localhost","root","P@ssw0rd", "my_db");
 if (!$con)
 {
 die('Could not connect: ' . mysqli_connect_error());
 }
 $result = mysqli_query($con, "SELECT * FROM person WHERE FirstName='Tadios'");
 while($row = mysqli_fetch_array($result))
 {
 echo $row['FirstName'] . " " . $row['LastName'];
 echo "<br />";
 }
?>
 The Order By Keyword
<?php
 $con = mysqli_connect("localhost","root","P@ssw0rd", "my_db");
 if (!$con)
 {
 die('Could not connect: ' . mysqli_connect_error());
 }
 $result = mysqli_query($con, "SELECT * FROM person ORDER BY age");
 while($row = mysqli_fetch_array($result))
 {
 echo $row['FirstName'];
 echo " " . $row['LastName'];
 echo " " . $row['Age']; echo "<br />";
 }
 mysqli_close($con);
 PHP Case Sensitivity
 Case Sensitive
  Variables
  Constants
  Array Keys
  Class Properties
  Class Constants
 Case Insensitive
  Functions
  Class Constructors
  Class Methods
  Keywords and constructs (If, else, null, foreach, echo etc.)