Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
6 views

introduction to PHP

This document provides an introduction to PHP, a widely-used open-source scripting language that is executed on the server. It covers essential topics such as PHP file structure, capabilities, installation, basic syntax, variables, data types, and operators. Additionally, it highlights the improvements in PHP 7 and offers examples of PHP code and its output.

Uploaded by

c nagaraju
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

introduction to PHP

This document provides an introduction to PHP, a widely-used open-source scripting language that is executed on the server. It covers essential topics such as PHP file structure, capabilities, installation, basic syntax, variables, data types, and operators. Additionally, it highlights the improvements in PHP 7 and offers examples of PHP code and its output.

Uploaded by

c nagaraju
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 295

Unit - III

PHP
PHP Introduction
PHP code is executed on the server.
 What You Should Already Know
 Before you continue you should have a basic understanding of the following:
• HTML
• CSS
• JavaScript

 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, JavaScript, 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?


• PHP can generate dynamic page content
• PHP can create, open, read, write, delete, and close files on the server
• PHP can collect form data
• PHP can send and receive cookies
• PHP can add, delete, modify data in your database
• PHP can be used to control user-access
• PHP can encrypt data

With PHP you are not limited to output HTML. You can output images, PDF files, and
even Flash movies. You can also output any text, such as XHTML and XML.
Why PHP?
•PHP runs on various platforms (Windows, Linux, Unix, Mac OS X, etc.)
•PHP is compatible with almost all servers used today (Apache, IIS, etc.)
•PHP supports a wide range of databases
•PHP is free. Download it from the official PHP resource: www.php.net
•PHP is easy to learn and runs efficiently on the server side

What's new in PHP 7


•PHP 7 is much faster than the previous popular stable release (PHP 5.6)
•PHP 7 has improved Error Handling
•PHP 7 supports stricter Type Declarations for function arguments
•PHP 7 supports new operators (like the spaceship operator: <=>)
PHP Installation
What Do I Need?
To start using PHP, you can:

•Find a web host with PHP and MySQL support


•Install a web server on your own PC, and then install PHP and MySQL

Use a Web Host With PHP Support

If your server has activated support for PHP you do not need to do anything.
Just create some .php files, place them in your web directory, and the server
will automatically parse them for you.
You do not need to compile anything or install any extra tools.
Because PHP is free, most web hosts offer PHP support.
Set Up PHP on Your Own PC
However, if your server does not support PHP, you must:

•install a web server


•install PHP
•install a database, such as MySQL
The official PHP website (PHP.net) has installation instructions for PHP:
http://php.net/manual/en/install.php

PHP Online Compiler / Editor


With w3schools' online PHP compiler, you can edit PHP
code, and view the result in your browser.
Basic PHP Syntax

 <?php
 // PHP code goes here
 ?>
Basic program

<!DOCTYPE html>
<html>
<body>

<h1>My first PHP page</h1>

<?php
echo "Hello World!";
?>

</body>
</html>
OUTPUT:

My first PHP page


 Hello World!
PHP Case Sensitivity

 <!DOCTYPE html>
 <html>
 <body>

 <?php
 ECHO "Hello World!<br>";
 echo "Hello World!<br>";
 EcHo "Hello World!<br>";
 ?>

 </body>
 </html>
Output:

 Hello World!
 Hello World!
 Hello World!
Program:

 <!DOCTYPE html>
 <html>
 <body>

 <?php
 $color = "red";
 echo "My car is " . $color . "<br>";
 echo "My house is " . $COLOR . "<br>";
 echo "My boat is " . $coLOR . "<br>";
 ?>

 </body>
 </html>
Output:

 My car is red
 My house is
 My boat is
Comments in PHP
Single line comment :

 <!DOCTYPE html>
 <html>
 <body>

 <?php
 // This is a single-line comment

 # This is also a single-line comment


 ?>

 </body>

• Multi line comment:
 <!DOCTYPE html>
 <html>
 <body>

 <?php
 /*
 This is a multiple-lines comment block
 that spans over multiple
 lines
 */
 ?>

 </body>
 </html>
• comments to leave out parts of a code
line<!DOCTYPE html>

 <html>
 <body>

 <?php
 // You can also use comments to leave out parts of a code line
 $x = 5 /* + 15 */ + 5;
 echo $x;
 ?>

 </body>
 </html>
Output:

 10
PHP Variables
Creating (Declaring) PHP Variables
 <!DOCTYPE html>
 <html>
 <body>

 <?php
 $txt = "Hello world!";
 $x = 5;
 $y = 10.5;

 echo $txt;
 echo "<br>";
 echo $x;
 echo "<br>";
 echo $y;
 ?>
Output:

 Hey
 Hello world!
5
10.5
• Output variable:

 <!DOCTYPE html>
 <html>
 <body>

 <?php
 $txt = “yvu students.com";
 echo “I love " . $txt . "!";
 ?>

 </body>
 </html>
Output:

 I love yvu students.com!


PHP Variables Scope
Global and Local Scope

Global scope:
 <!DOCTYPE html>  echo "<p>Variable x inside
 <html> function is: $x</p>";
 <body>  }
 myTest();
 <?php
 $x = 5; // global scope  echo "<p>Variable x outside
 function is: $x</p>";
  ?>
function myTest() {
 // using x inside this function will
generate an error  </body>
 </html>
Output:

 Variable x inside function is:

 Variable x outside function is: 5


Local scope:
 <!DOCTYPE html>
 <html>
 <body>

 <?php
 function myTest() {
 $x = 5; // local scope
 echo "<p>Variable x inside function is: $x</p>";
 }
 myTest();

 // using x outside the function will generate an error


 echo "<p>Variable x outside function is: $x</p>";
 ?>

 </body>

Output:

 Variable x inside function is: 5

 Variable x outside function is:


PHP The global Keyword
 <!DOCTYPE html>
 <html>
 <body>

 <?php
 $x = 5;
 $y = 10;

 function myTest() {
 global $x, $y;
 $y = $x + $y;
 }

 myTest(); // run function


 echo $y; // output the new value for variable $y
 ?>

 </body>

Output:

 15
Globel keyword 2:
 <!DOCTYPE html>
 <html>
 <body>

 <?php
 $x = 5;
 $y = 10;

 function myTest() {
 $GLOBALS['y'] = $GLOBALS['x'] + $GLOBALS['y'];
 }

 myTest();
 echo $y;
 ?>

 </body>
 </html>
Output:

 15
PHP The static Keyword
 <!DOCTYPE html>
 <html>
 <body>

 <?php
 function myTest() {
 static $x = 0;
 echo $x;
 $x++;
 }

 myTest();
 echo "<br>";
 myTest();
 echo "<br>";
 myTest();
 ?>

 </body>
Output:

0
1
2
PHP echo and print Statements

 The PHP echo Statement


 Display text:
 <!DOCTYPE html>
 <html>
 <body>

 <?php
 echo "<h2>PHP is Fun!</h2>";
 echo "Hello world!<br>";
 echo "I'm about to learn PHP!<br>";
 echo "This ", "string ", "was ", "made ", "with multiple parameters.";
 ?>

 </body>

Output:

 PHP is Fun!
 Hello world!
I'm about to learn PHP!
This string was made with multiple parameters.
Display variable:
 <!DOCTYPE html>
 <html>
 <body>

 <?php
 $txt1 = "Learn PHP";
 $txt2 = "W3Schools.com";
 $x = 5;
 $y = 4;

 echo "<h2>" . $txt1 . "</h2>";


 echo "Study PHP at " . $txt2 . "<br>";
 echo $x + $y;
 ?>

 </body>
Output:

 Learn PHP
 Study PHP at W3Schools.com
9
The PHP print Statement

Display text:
<!DOCTYPE html>
<html>
<body>

<?php
print "<h2>PHP is Fun!</h2>";
print "Hello world!<br>";
print "I'm about to learn PHP!";
?>

</body>
</html>
Output:

 PHP is Fun!
 Hello world!
I'm about to learn PHP!
Display variable:
 <!DOCTYPE html>
 <html>
 <body>

 <?php
 $txt1 = "Learn PHP";
 $txt2 = "W3Schools.com";
 $x = 5;
 $y = 4;

 print "<h2>" . $txt1 . "</h2>";


 print "Study PHP at " . $txt2 . "<br>";
 print $x + $y;
 ?>

 </body>

Output:

 Learn PHP
 Study PHP at W3Schools.com
9
PHP Data Types
 PHP Data Types
 Variables can store data of different types, and different data types can do different
things.

 PHP supports the following data types:

 String
 Integer
 Float (floating point numbers - also called double)
 Boolean
 Array
 Object
 NULL
 Resource
PHP String
 <!DOCTYPE html>
 <html>
 <body>

 <?php
 $x = "Hello world!";
 $y = 'Hello world!';

 echo $x;
 echo "<br>";
 echo $y;
 ?>

 </body>
 </html>
Output:

 Hello world!
 Hello world!
PHP Integer
 <!DOCTYPE html>
 <html>
 <body>

 <?php
 $x = 5985;
 var_dump($x);
 ?>

 </body>
 </html>
Output:

 int(5985)
PHP Float
 <!DOCTYPE html>
 <html>
 <body>

 <?php
 $x = 10.365;
 var_dump($x);
 ?>

 </body>
 </html>
Output:

 float(10.365)
• PHP Boolean

 A Boolean represents two possible states: TRUE or FALSE.


 $x = true;
$y = false;
PHP Array
 <!DOCTYPE html>
 <html>
 <body>

 <?php
 $cars = array("Volvo","BMW","Toyota");
 var_dump($cars);
 ?>

 </body>
 </html>
Output:

 array(3) {
 [0]=>
 string(5) "Volvo"
 [1]=>
 string(3) "BMW"
 [2]=>
 string(6) "Toyota"
 }
PHP Object

 $myCar = new Car("black",
<!DOCTYPE html>
 <html> "Volvo");
 <body>  echo $myCar -> message();
 echo "<br>";
 <?php
 class Car {  $myCar = new Car("red",
 public $color; "Toyota");
 public $model;  echo $myCar -> message();
 public function __construct($color, $model) {
 ?>
 $this->color = $color;
 $this->model = $model;
 }
 </body>
 public function message() {
 return "My car is a " . $this->color . " " . $this-
 </html>
>model . "!";
 }
 }
Output:

 My car is a black Volvo!


 My car is a red Toyota!
PHP NULL Value
 <!DOCTYPE html>
 <html>
 <body>

 <?php
 $x = "Hello world!";
 $x = null;
 var_dump($x);
 ?>

 </body>
 </html>
Output:

 Null
PHP Resource
PHP Operators
 PHP Operators
 Operators are used to perform operations on variables and values.

 PHP divides the operators in the following groups:

 Arithmetic operators
 Assignment operators
 Comparison operators
 Increment/Decrement operators
 Logical operators
 String operators
 Array operators
 Conditional assignment operators
PHP Arithmetic Operators

Operator Name Example Result

+ Addition $x + $y Sum of $x and $y

- Subtraction $x - $y Difference of $x and $y

* Multiplication $x * $y Product of $x and $y

/ Division $x / $y Quotient of $x and $y

% Modulus $x % $y Remainder of $x divided by


$y

** Exponentiation $x ** $y Result of raising $x to the


$y'th power
Arithmetic Operators
 <!DOCTYPE html>
 <html>
 <body>

 <?php
 $x = 10;
 $y = 6;
 echo "<br>",$x + $y;
 echo "<br>",$x - $y;
 echo "<br>",$x * $y;
 echo "<br>",$x / $y;
 echo "<br>",$x % $y;
 echo "<br>",$x ** $y;
 ?>

 </body>
 </html>
Output:

 16
4
60
1.6666666666667
4
1000000
PHP Assignment Operators

Assignm Same as... Description


ent
x=y x=y The left operand gets set to the value
of the expression on the right

x += y x=x+y Addition
x -= y x=x-y Subtraction
x *= y x=x*y Multiplication
x /= y x=x/y Division
x %= y x=x%y Modulus
Assignment Operators
<?php
Output:
$x = 10;
$y = 20; 20
40
20
$res=$x = $y; 400
echo $res."<br>"; 20
0

$res= $x += $y;
echo $res."<br>";

$res= $x -= $y;
echo $res."<br>";

$res= $x *= $y;
echo $res."<br>";

$res= $x /= $y;
echo $res."<br>";

$res= $x %= $y;
echo $res."<br>";
PHP Comparison Operators
Operator Name Example Result

== Equal $x == $y Returns true if $x is equal to $y

=== Identical $x === $y Returns true if $x is equal to $y, and they are of the
same type

!= Not equal $x != $y Returns true if $x is not equal to $y

<> Not equal $x <> $y Returns true if $x is not equal to $y

!== Not identical $x !== $y Returns true if $x is not equal to $y, or they are not
of the same type

> Greater than $x > $y Returns true if $x is greater than $y

< Less than $x < $y Returns true if $x is less than $y

>= Greater than or equal to $x >= $y Returns true if $x is greater than or equal to $y

<= Less than or equal to $x <= $y Returns true if $x is less than or equal to $y

<=> Spaceship $x <=> $y Returns an integer less than, equal to, or greater
than zero, depending on if $x is less than, equal to,
or greater than $y. Introduced in PHP 7.
Program on comparision operators
 <html>  echo "TEST2 : a is neither greater than nor
 not greater than b<br/>"; equal to b<br/>";
  }  }
<head>
  if( $a < $b ) { 
<title>Comparison
Operators</title>  echo "TEST3 : a is  if( $a <= $b ) {
 </head> less than b<br/>";  echo "TEST6 : a is
  }else { either less than or equal
 <body>  echo "TEST3 : a is to b<br/>";
not less than b<br/>";  }else {

 }  echo "TEST6 : a is
 <?php

 neither less than nor
$a = 42;
 if( $a != $b ) { equal to b<br/>";
 $b = 20;  }
 echo "TEST4 : a is

 ?>

not equal to b<br/>";
if( $a == $b ) { 
 }else {
 echo "TEST1 : a is
  </body>
equal to b<br/>"; echo "TEST4 : a is
equal to b<br/>";  </html>
 }else {
 }
 echo "TEST1 : a is

not equal to b<br/>";
 if( $a >= $b ) {
 }
 echo "TEST5 : a is


either greater than or
if( $a > $b ) {
equal to b<br/>";
 echo "TEST2 : a is  }else {
greater than b<br/>";
output
TEST1 : a is not equal to b
TEST2 : a is greater than b
TEST3 : a is not less than b
TEST4 : a is not equal to b
TEST5 : a is either greater than or equal to b
TEST6 : a is neither less than nor equal to b
PHP Increment / Decrement Operators
The PHP increment operators are used to increment a variable's value.

The PHP decrement operators are used to decrement a variable's value.

Operato Name Description


r
++$x Pre- Increments $x by one, then
increment returns $x
$x++ Post- Returns $x, then increments $x by
increment one
--$x Pre- Decrements $x by one, then
decrement returns $x
$x-- Post- Returns $x, then decrements $x
decrement by one
Program on increment and
decrement operators
 <?php
 $x=5;
 $y=5;
 $x++; //postfix increment
 $y--; //postfix decrement
 echo "x = $x y = $y" . "\n";
 ++$y; //prefix increment
 --$x; //prefix decrement
 echo "x = $x y = $y" . "\n";;
 ?>
Output

 x=6y=4x=5y=5
PHP Logical Operators
The PHP logical operators are used to combine conditional statements.

Operator Name Example Result

and And $x and $y True if both $x and $y are


true

or Or $x or $y True if either $x or $y is
true

xor Xor $x xor $y True if either $x or $y is


true, but not both

&& And $x && $y True if both $x and $y are


true

|| Or $x || $y True if either $x or $y is
true

! Not !$x True if $x is not true


Program on logical operators
 <html>  if( $a and $b ) {  }else {  }
  echo "TEST2 :  echo "TEST4 : 

 Both a and b are Both a and b are 


<head> if( !$a ) {
true<br/>"; false<br/>";
 <title>Logical  echo "TEST7 :
 }else{  }
Operators</title> a is true <br/>";
 echo "TEST2 : 
 </head>  }else {
Either a or b is 
 $a = 10; 
false<br/>"; echo "TEST7 :
 $b = 20; a is false<br/>";
 <body>  }
  }
 
 if( $a ) { 
 <?php  if( $a || $b ) {
 echo "TEST5 :  if( !$b ) {
 $a = 42;  echo "TEST3 :
a is true <br/>"; 
 Either a or b is echo "TEST8 :
$b = 0; 
true<br/>"; }else { b is true <br/>";

 }else{  echo "TEST5 :  }else {
 if( $a && $b ) { a is false<br/>";
 echo "TEST3 :  echo "TEST8 :
 echo "TEST1 :  } b is false<br/>";
Both a and b are
Both a and b are false<br/>";   }
true<br/>";
 }  if( $b ) {  ?>
 }else{

 echo "TEST6 : 
 echo "TEST1 :
 if( $a or $b ) { b is true <br/>"; 
Either a or b is </body>
false<br/>";  echo "TEST4 :  }else {  </html>
 } Either a or b is  echo "TEST6 :
true<br/>"; b is false<br/>";

Output

 TEST1: Either a or b is false


TEST2 : Either a or b is false
TEST3 : Either a or b is true
TEST4 : Either a or b is true
TEST5 : a is true
TEST6 : b is true
TEST7 : a is false
TEST8 : b is false
PHP String Operators

PHP has two operators that are specially designed for strings.

Operator Name Example Result

. Concatenation $txt1 . $txt2 Concatenation of


$txt1 and $txt2

.= Concatenation $txt1 .= $txt2 Appends $txt2 to


assignment $txt1
Program on string operators

 <!DOCTYPE html>
 <html>
 <body>

 <?php
 $txt1 = "Hello";
 $txt2 = " world!";
 echo $txt1 . $txt2 . "<br>";
 $txt1 .= $txt2;
 echo $txt1;
 ?>

 </body>
 </html>
Output

 Hello world!
Hello world!
PHP Array Operators

The PHP array operators are used to compare arrays.

Operator Name Example Result

+ Union $x + $y Union of $x and $y


== Equality $x == $y Returns true if $x and $y have the
same key/value pairs

=== Identity $x === $y Returns true if $x and $y have the


same key/value pairs in the same
order and of the same types

!= Inequality $x != $y Returns true if $x is not equal to $y

<> Inequality $x <> $y Returns true if $x is not equal to $y

!== Non-identity $x !== $y Returns true if $x is not identical to $y


Program on array operators

 <!DOCTYPE html> of $x and $y


 <html>  var_dump($x == $y) ."<br>";
 <body>  var_dump($x === $y)."<br>";
 var_dump($x != $y)."<br>";
 <?php  var_dump($x <> $y)."<br>";
 $x = array("a" => "red", "b" =>  var_dump($x !== $y)."<br>";
"green");  ?>
 $y = array("c" => "blue", "d"
=> "yellow");
 </body>
 </html>
 print_r($x + $y) ."<br>"; // union
Output

 Array ( [a] => red [b] => green [c] => blue [d] => yellow )
 bool(false)
 bool(false)
 bool(true)
 bool(true)
 bool(true)
PHP Conditional Assignment Operators
The PHP conditional assignment operators are used to set a value depending
on conditions:

Operator Name Example Result

?: Ternary $x Returns the value of $x.


= expr1 ? exp The value of $x is expr2 if expr1 =
r2 : expr3 TRUE.
The value of $x is expr3 if expr1 =
FALSE

?? Null coalescing $x Returns the value of $x.


= expr1 ?? ex The value of $x
pr2 is expr1 if expr1 exists, and is not
NULL.
If expr1 does not exist, or is NULL,
the value of $x is expr2.
Introduced in PHP 7
Program on conditional assignment
operators
 <!DOCTYPE html>
 <html>
 <body>

 <?php
 // if empty($user) = TRUE, set $status = "anonymous"
 echo $status = (empty($user)) ? "anonymous" : "logged in";
 echo("<br>");

 $user = "John Doe";


 // if empty($user) = FALSE, set $status = "logged in"
 echo $status = (empty($user)) ? "anonymous" : "logged in";
 ?>

 </body>
 </html>
Output

 anonymous
logged in
PHP Constants

Create a PHP Constant


 To create a constant, use the define() function.

 Syntax
 define(name, value, case-insensitive)
 Parameters:

 name: Specifies the name of the constant


 value: Specifies the value of the constant
 case-insensitive: Specifies whether the constant name should be case-insensitive.
Default is false
case-sensitive

 <!DOCTYPE html>
 <html>
 <body>

 <?php
 // case-sensitive constant name
 define("GREETING", "Welcome to yogi venama university.com!");
 echo GREETING;
 ?>

 </body>
 </html>
Output:

 Welcome to yogi venama university.com!


case-insensitive
 <!DOCTYPE html>
 <html>
 <body>

 <?php
 // case-insensitive constant name
 define("GREETING", "Welcome to proddatur.com!", true);
 echo greeting;
 ?>

 </body>
 </html>
Output:

 Welcome to proddatur.com!
PHP Constant Arrays
 <!DOCTYPE html>
 <html>
 <body>

 <?php
 define("cars", [
 "Alfa Romeo",
 "BMW",
 "Toyota"
 ]);
 echo cars[0];
 ?>

 </body>
 </html>
Output:

 Alfa Romeo
Constants are Global
 <!DOCTYPE html>
 <html>
 <body>

 <?php
 define("GREETING", "Welcome to yvu of ysr engineering college.com!");

 function myTest() {
 echo GREETING;
 }

 myTest();
 ?>

 </body>
 </html>
Output:

 Welcome to yvu of ysr engineering college.com!


PHP if...else...elseif Statements
 PHP Conditional Statements

 Very often when you write code, you want to perform different actions for
different conditions. You can use conditional statements in your code to do
this.

 In PHP we have the following conditional statements:

 if statement - executes some code if one condition is true


 if...else statement - executes some code if a condition is true and another code
if that condition is false
 if...elseif...else statement - executes different codes for more than two
conditions
 switch statement - selects one of many blocks of code to be executed
PHP - The if Statement
 The if statement executes some code if one condition is true.
 Syntax
 if (condition) {
 code to be executed if condition is true;
 }
 Program:
 <!DOCTYPE html>
 <html>
 <body>

 <?php
 $t = date("H");

 if ($t < "20") {


 echo "Have a good day!";
 }
 ?>

 </body>
Output:
 Have a good day!
PHP - The if...else Statement
 The if...else statement executes some code if a condition is true and another code if that condition is false.
 Syntax
 if (condition) {
 code to be executed if condition is true;
 } else {
 code to be executed if condition is false;
 }

 Program:
 <!DOCTYPE html>
 <html>
 <body>

 <?php
 $t = date("H");

 if ($t < "20") {


 echo "Have a good day!";
 } else {
 echo "Have a good night!";
 }
 ?>

Output:
 Have a good day!
PHP - The if...elseif...else Statement
 The if...elseif...else statement executes different codes for more than two conditions.

 Syntax
 if (condition) {
 code to be executed if this condition is true;
 } elseif (condition) {
 code to be executed if first condition is false and this condition is true;
 } else {
 code to be executed if all conditions are false;
 }
Program:
 <!DOCTYPE html>
 <html>
 <body>

 <?php
 $t = date("H");
 echo "<p>The hour (of the server) is " . $t;
 echo ", and will give the following message:</p>";

 if ($t < "10") {


 echo "Have a good morning!";
 } elseif ($t < "20") {
 echo "Have a good day!";
 } else {
 echo "Have a good night!";
 }
 ?>

 </body>
Output:
 The hour (of the server) is 10, and will give the following message:
Have a good day!
PHP switch Statement
 Use the switch statement to select one of many blocks of code to be executed.

Syntax

 switch (n) {
 case label1:
 code to be executed if n=label1;
 break;
 case label2:
 code to be executed if n=label2;
 break;
 case label3:
 code to be executed if n=label3;
 break;
 ...
 default:
 code to be executed if n is different from all labels;
 }
Program:
 <!DOCTYPE html>  echo "Your favorite color is blue!";
 <html>  break;
 <body>  case "green":
 echo "Your favorite color is
 <?php green!";
 break;
 $favcolor = "red";
 default:
 echo "Your favorite color is
 switch ($favcolor) {
neither red, blue, nor green!";
 case "red":  }
 echo "Your favorite color is  ?>
red!";

 break;
 </body>
 case "blue":
 </html>
Output:
 Your favorite color is red!
PHP Loops
 Often when you write code, you want the same block of code to run over and
over again a certain number of times. So, instead of adding several almost
equal code-lines in a script, we can use loops.

 Loops are used to execute the same block of code again and again, as long as
a certain condition is true.

 In PHP, we have the following loop types:

 while - loops through a block of code as long as the specified condition is true
 do...while - loops through a block of code once, and then repeats the loop as
long as the specified condition is true
 for - loops through a block of code a specified number of times
 foreach - loops through a block of code for each element in an array
The PHP while Loop
 The while loop executes a block of code as long as the specified condition is true.
 Syntax
 while (condition is true) {
 code to be executed;
 }

 Program:
 <!DOCTYPE html>
 <html>
 <body>

 <?php
 $x = 1;

 while($x <= 10) {


 echo "The number is: $x <br>";
 $x++;
 }
 ?>

 </body>
Output:
 The number is: 1
The number is: 2
The number is: 3
The number is: 4
The number is: 5
The number is: 6
The number is: 7
The number is: 8
The number is: 9
The number is: 10
Program 2:
 <!DOCTYPE html>
 <html>
 <body>

 <?php
 $x = 0;

 while($x <= 100) {


 echo "The number is: $x <br>";
 $x+=10;
 }
 ?>

 </body>
 </html>
Output:
 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
PHP do while Loop
 The do...while loop will always execute the block of code once, it will then check the condition, and repeat
the loop while the specified condition is true.
 Syntax
 do {
 code to be executed;
 } while (condition is true);

 Program:
 <!DOCTYPE html>
 <html>
 <body>

 <?php
 $x = 1;

 do {
 echo "The number is: $x <br>";
 $x++;
 } while ($x <= 5);
 ?>

 </body>
Output:
 The number is: 1
The number is: 2
The number is: 3
The number is: 4
The number is: 5
Program 2:
 <!DOCTYPE html>
 <html>
 <body>

 <?php
 $x = 6;

 do {
 echo "The number is: $x <br>";
 $x++;
 } while ($x <= 5);
 ?>

 </body>
 </html>
Output:
 The number is: 6
PHP for Loop
 The for loop is used when you know in advance how many times the script should run.
 Syntax
 for (init counter; test counter; increment counter) {
 code to be executed for each iteration;
 }
 Program:
 <!DOCTYPE html>
 <html>
 <body>

 <?php
 for ($x = 0; $x <= 10; $x++) {
 echo "The number is: $x <br>";
 }
 ?>

 </body>
Output:
 The number is: 0
The number is: 1
The number is: 2
The number is: 3
The number is: 4
The number is: 5
The number is: 6
The number is: 7
The number is: 8
The number is: 9
The number is: 10
Program 2 :
 <!DOCTYPE html>
 <html>
 <body>

 <?php
 for ($x = 0; $x <= 100; $x+=10) {
 echo "The number is: $x <br>";
 }
 ?>

 </body>
 </html>
Output:
 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
PHP foreach Loop
 The foreach loop works only on arrays, and is used to loop through each key/value pair in an array.
 Syntax
 foreach ($array as $value) {
 code to be executed;
 }

 Program:
 <!DOCTYPE html>
 <html>
 <body>

 <?php
 $colors = array("red", "green", "blue", "yellow");

 foreach ($colors as $value) {


 echo "$value <br>";
 }
 ?>

 </body>
Output:
 red
green
blue
yellow
Program 2 :
 <!DOCTYPE html>
 <html>
 <body>

 <?php
 $age = array("sreedhar"=>"35", "Madhu"=>"37", "krishna"=>"43");

 foreach($age as $x => $val) {


 echo "$x = $val<br>";
 }
 ?>

 </body>
 </html>
Output:
 sreedhar = 35
Madhu = 37
krishna = 43
PHP Break and Continue
 PHP Break
 You have already seen the break statement used in an earlier chapter of this tutorial. It was
used to "jump out" of a switch statement.
 The break statement can also be used to jump out of a loop.
 Program:
 <!DOCTYPE html>
 <html>
 <body>

 <?php
 for ($x = 0; $x < 10; $x++) {
 if ($x == 4) {
 break;
 }
 echo "The number is: $x <br>";
 }
 ?>
Output:
 The number is: 0
The number is: 1
The number is: 2
The number is: 3
PHP Continue
 The continue statement breaks one iteration (in the loop), if a specified
condition occurs, and continues with the next iteration in the loop.
 Program:
 <!DOCTYPE html>
 <html>
 <body>

 <?php
 for ($x = 0; $x < 10; $x++) {
 if ($x == 4) {
 continue;
 }
 echo "The number is: $x <br>";
 }
 ?>

 </body>
 </html>
Output:
 The number is: 0
The number is: 1
The number is: 2
The number is: 3
The number is: 5
The number is: 6
The number is: 7
The number is: 8
The number is: 9
Break and Continue in While Loop
You can also use break and continue in while loops:

 Break Example
 <!DOCTYPE html>
 <html>
 <body>

 <?php
 $x = 0;

 while($x < 10) {


 if ($x == 4) {
 break;
 }
 echo "The number is: $x <br>";
 $x++;
 }
 ?>

 </body>
Output:
 The number is: 0
The number is: 1
The number is: 2
The number is: 3
Continue Example
 <!DOCTYPE html>
 <html>
 <body>

 <?php
 $x = 0;

 while($x < 10) {


 if ($x == 4) {
 $x++;
 continue;
 }
 echo "The number is: $x <br>";
 $x++;
 }
 ?>

 </body>
Output:
 The number is: 0
The number is: 1
The number is: 2
The number is: 3
The number is: 5
The number is: 6
The number is: 7
The number is: 8
The number is: 9
UNIT - IV

ARRAYS
What is an Array?
 An array is a special variable, which can hold more than one value at a
time.

 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 = "Volvo";
 $cars2 = "BMW";
 $cars3 = "Toyota";
 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 solution is to create an array!

 An array can hold many values under a single name, and you can
access the values by referring to an index number.
PHP Arrays
 <!DOCTYPE html>
 <html>
 <body>

 <?php
 $mobiles = array("Redme", "APPLE", "vivo");
 echo "I like " . $mobiles[0] . ", " . $mobiles[1] . " and " . $mobiles[2] . ".";
 ?>

 </body>
 </html>
Output:

 I like Redme, APPLE and vivo.


Create an Array in PHP

In PHP, the array() function is used to create an array:

array();

In PHP, there are three types of arrays:

Indexed arrays - Arrays with a numeric index


Associative arrays - Arrays with named keys
Multidimensional arrays - Arrays containing one or more arrays
The Length of an Array - The count() Function

 <!DOCTYPE html>
 <html>
 <body>

 <?php
 $things = array("pen", "pencil", "marker");
 echo count($things);
 ?>

 </body>
 </html>
Output:

 3
PHP Indexed Arrays

 PHP Indexed Arrays


 There are two ways to create indexed arrays:

 The index can be assigned automatically (index always starts at 0), like this:

 $cars = array("Volvo", "BMW", "Toyota");


 or the index can be assigned manually:

 $cars[0] = "Volvo";
 $cars[1] = "BMW";
 $cars[2] = "Toyota";
Indexed Arrays

 <!DOCTYPE html>
 <html>
 <body>

 <?php
 $cars = array("Volvo", "BMW", "Toyota");
 echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
 ?>

 </body>
 </html>
Output:

 I like Volvo, BMW and Toyota.


Loop Through an Indexed Array
 <!DOCTYPE html>
 <html>
 <body>

 <?php
 $cars = array("Volvo", "BMW", "Toyota");
 $arrlength = count($cars);

 for($x = 0; $x < $arrlength; $x++) {


 echo $cars[$x];
 echo "<br>";
 }
 ?>

 </body>

Output:

 Volvo
BMW
Toyota
PHP Associative Arrays

 PHP Associative Arrays


 Associative arrays are arrays that use named keys that you assign to them.

 There are two ways to create an associative array:

 $age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");


 or:

 $age['Peter'] = "35";
 $age['Ben'] = "37";
 $age['Joe'] = "43";
Associative Arrays

 <!DOCTYPE html>
 <html>
 <body>

 <?php
 $age = array("kumar"=>"35", "sree"=>"37", "krishna"=>"43");
 echo "kumar is " . $age['kumar'] . " years old.";
 ?>

 </body>
 </html>
Output:

 kumar is 35 years old.


Loop Through an Associative Array
 <!DOCTYPE html>
 <html>
 <body>

 <?php
 $age = array("kumar"=>"35", "sree"=>"37", "krishna"=>"43");

 foreach($age as $x => $x_value) {


 echo "Key=" . $x . ", Value=" . $x_value;
 echo "<br>";
 }
 ?>

 </body>
 </html>
Output:

 Key=kumar, Value=35
Key=sree, Value=37
Key=krishna, Value=43
PHP Multidimensional Arrays
 In the previous pages, we have described arrays that are a single list of key/value pairs.

 However, sometimes you want to store values with more than one key. For this, we have
multidimensional arrays.

 PHP - Multidimensional Arrays


 A multidimensional array is an array containing one or more arrays.

 PHP supports multidimensional arrays that are two, three, four, five, or more levels deep.
However, arrays more than three levels deep are hard to manage for most people.

 The dimension of an array indicates the number of indices you need to select an
element.

 For a two-dimensional array you need two indices to select an element


 For a three-dimensional array you need three indices to select an element
PHP - Two-dimensional Arrays
 A two-dimensional array is an array of arrays (a three-dimensional array is an
array of arrays of arrays).

 First, take a look at the following table:

 Name Stock Sold


 Volvo 22 18
 BMW 15 13
 Saab 5 2
 Land Rover 17 15
 We can store the data from the table above in a two-dimensional array, like this:

 $cars = array (
 array("Volvo",22,18),
 array("BMW",15,13),
 array("Saab",5,2),
 array("Land Rover",17,15)
 );
Two dimensional array
 <!DOCTYPE html>
 <html>
 <body>

 <?php
 $cars = array (
 array("Volvo",22,18),
 array("BMW",15,13),
 array("Saab",5,2),
 array("Land Rover",17,15)
 );

 echo $cars[0][0].": In stock: ".$cars[0][1].", sold: ".$cars[0][2].".<br>";


 echo $cars[1][0].": In stock: ".$cars[1][1].", sold: ".$cars[1][2].".<br>";
 echo $cars[2][0].": In stock: ".$cars[2][1].", sold: ".$cars[2][2].".<br>";
 echo $cars[3][0].": In stock: ".$cars[3][1].", sold: ".$cars[3][2].".<br>";
 ?>

 </body>
Output:

 Volvo: In stock: 22, sold: 18.


 BMW: In stock: 15, sold: 13.
 Saab: In stock: 5, sold: 2.
 Land Rover: In stock: 17, sold: 15.
Two dimensional array 2
 <!DOCTYPE html>
 <html>
 <body>

 <?php
 $cars = array (
 array("Volvo",22,18),
 array("BMW",15,13),
 array("Saab",5,2),
 array("Land Rover",17,15)
 );

 for ($row = 0; $row < 4; $row++) {


 echo "<p><b>Row number $row</b></p>";
 echo "<ul>";
 for ($col = 0; $col < 3; $col++) {
 echo "<li>".$cars[$row][$col]."</li>";
 }
 echo "</ul>";
 }
 ?>

 </body>

Output:
 Row number 0
• Volvo
• 22
• 18
 Row number 1
• BMW
• 15
• 13
 Row number 2
• Saab
• 5
• 2
 Row number 3
• Land Rover
• 17

PHP Sorting Arrays
 The elements in an array can be sorted in alphabetical or numerical order,
descending or ascending.

 PHP - Sort Functions For Arrays


 In this chapter, we will go through the following PHP array sort functions:

 sort() - sort arrays in ascending order


 rsort() - sort arrays in descending order
 asort() - sort associative arrays in ascending order, according to the value
 ksort() - sort associative arrays in ascending order, according to the key
 arsort() - sort associative arrays in descending order, according to the
value
 krsort() - sort associative arrays in descending order, according to the key
Sort Array in Ascending Order -
sort()
 Ascending alphabetical order:
 <!DOCTYPE html>
 <html>
 <body>

 <?php
 $cars = array("Volvo", "BMW", "Toyota");
 sort($cars);

 $clength = count($cars);
 for($x = 0; $x < $clength; $x++) {
 echo $cars[$x];
 echo "<br>";
 }
 ?>

 </body>
Output:

 BMW
Toyota
Volvo
Ascending numerical order:
 <!DOCTYPE html>
 <html>
 <body>

 <?php
 $numbers = array(4, 6, 2, 22, 11);
 sort($numbers);

 $arrlength = count($numbers);
 for($x = 0; $x < $arrlength; $x++) {
 echo $numbers[$x];
 echo "<br>";
 }
 ?>

 </body>
Output:
 2
4
6
11
22
Sort Array in Descending Order -
rsort()
 Descending alphabetical order:
 <!DOCTYPE html>
 <html>
 <body>

 <?php
 $cars = array("Volvo", "BMW", "Toyota");
 rsort($cars);

 $clength = count($cars);
 for($x = 0; $x < $clength; $x++) {
 echo $cars[$x];
 echo "<br>";
 }
 ?>
Output:
 Volvo
Toyota
BMW
Descending numerical order:
 <!DOCTYPE html>
 <html>
 <body>

 <?php
 $numbers = array(4, 6, 2, 22, 11);
 rsort($numbers);

 $arrlength = count($numbers);
 for($x = 0; $x < $arrlength; $x++) {
 echo $numbers[$x];
 echo "<br>";
 }
 ?>

 </body>
Output:

 22
11
6
4
2
Sort Array (Ascending Order), According to Value -
asort()
 <!DOCTYPE html>
 <html>
 <body>

 <?php
 $age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
 asort($age);

 foreach($age as $x => $x_value) {


 echo "Key=" . $x . ", Value=" . $x_value;
 echo "<br>";
 }
 ?>

 </body>
Output:
 Key=Peter, Value=35
Key=Ben, Value=37
Key=Joe, Value=43
Sort Array (Ascending Order), According to Key
- ksort()
 <!DOCTYPE html>
 <html>
 <body>

 <?php
 $age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
 ksort($age);

 foreach($age as $x => $x_value) {


 echo "Key=" . $x . ", Value=" . $x_value;
 echo "<br>";
 }
 ?>

 </body>
Output:
 Key=Ben, Value=37
Key=Joe, Value=43
Key=Peter, Value=35
Sort Array (Descending Order), According to
Value - arsort()
 <!DOCTYPE html>
 <html>
 <body>

 <?php
 $age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
 arsort($age);

 foreach($age as $x => $x_value) {


 echo "Key=" . $x . ", Value=" . $x_value;
 echo "<br>";
 }
 ?>

 </body>
Output:
 Key=Joe, Value=43
Key=Ben, Value=37
Key=Peter, Value=35
Sort Array (Descending Order), According to
Key - krsort()
 <!DOCTYPE html>
 <html>
 <body>

 <?php
 $age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
 krsort($age);

 foreach($age as $x => $x_value) {


 echo "Key=" . $x . ", Value=" . $x_value;
 echo "<br>";
 }
 ?>

 </body>
Output:
 Key=Peter, Value=35
Key=Joe, Value=43
Key=Ben, Value=37
PHP Form Handling
 A Simple HTML Form
 <!DOCTYPE HTML>
<html>
<body>

<form action="welcome.php" method="post">


Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>

</body>
</html>
 Output:
GET vs. POST
 Both GET and POST create an array (e.g. array( key1 => value1, key2
=> value2, key3 => value3, ...)). This array holds key/value pairs,
where keys are the names of the form controls and values are the input
data from the user.

 Both GET and POST are treated as $_GET and $_POST. These are
superglobals, which means that they are always accessible, regardless
of scope - and you can access them from any function, class or file
without having to do anything special.

 $_GET is an array of variables passed to the current script via the URL
parameters.

 $_POST is an array of variables passed to the current script via the HTTP
POST method.
When to use GET?
 Information sent from a 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 information to send. The limitation is about
2000 characters. However, because the variables are displayed in the URL,
it is possible to bookmark the page. This can be useful in some cases.

 GET may be used for sending non-sensitive data.

 Note: GET should NEVER be used for sending passwords or other sensitive
information!
When to use POST?
 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) and has no limits on the amount of information to send.

 Moreover POST supports advanced functionality such as support for multi-


part binary input while uploading files to server.

 However, because the variables are not displayed in the URL, it is not
possible to bookmark the page.
PHP Form Validation

 The HTML form we will be working at in these chapters, contains various


input fields: required and optional text fields, radio buttons, and a submit
button:
HI

The validation rules for the form above are as follows:

Field Validation Rules

Name Required. + Must only contain letters and whitespace

E-mail Required. + Must contain a valid email address (with @


and .)

Website Optional. If present, it must contain a valid URL

Comment Optional. Multi-line input field (textarea)

Gender Required. Must select one


Text Fields

 The name, email, and website fields are text input elements, and the
comment field is a textarea. The HTML code looks like this:
 Name: <input type="text" name="name">
E-mail: <input type="text" name="email">
Website: <input type="text" name="website">
Comment: <textarea name="comment" rows="5" cols="40"></
textarea>

Radio Buttons
 The gender fields are radio buttons and the HTML code looks like this:

Gender:
<input type="radio" name="gender" value="female">Female
<input type="radio" name="gender" value="male">Male
<input type="radio" name="gender" value="other">Other
The Form Element
 The HTML code of the form looks like this:
 <form method="post" action="<?
php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
 When the form is submitted, the form data is sent with method="post".
 What is the $_SERVER["PHP_SELF"] variable?

The $_SERVER["PHP_SELF"] is a super global variable that returns the filename of


the currently executing script.
 So, the $_SERVER["PHP_SELF"] sends the submitted form data to the page itself,
instead of jumping to a different page. This way, the user will get error messages on
the same page as the form.
 What is the htmlspecialchars() function?

The htmlspecialchars() function converts special characters to HTML entities. This


means that it will replace HTML characters like < and > with &lt; and &gt;. This
prevents attackers from exploiting the code by injecting HTML or Javascript code
(Cross-site Scripting attacks) in forms.
Big Note on PHP Form Security
 The $_SERVER["PHP_SELF"] variable can be used by hackers!
 If PHP_SELF is used in your page then a user can enter a slash (/) and then some Cross
Site Scripting (XSS) commands to execute.
 Cross-site scripting (XSS) is a type of computer security vulnerability typically
found in Web applications. XSS enables attackers to inject client-side script
into Web pages viewed by other users.
 Assume we have the following form in a page named "test_form.php":
 <form method="post" action="<?php echo $_SERVER["PHP_SELF"];?>">
 Now, if a user enters the normal URL in the address bar like
"http://www.example.com/test_form.php", the above code will be translated to:
 <form method="post" action="test_form.php">
 So far, so good.
 However, consider that a user enters the following URL in the address bar:
 http://www.example.com/test_form.php/%22%3E%3Cscript%3Ealert('hacked')
%3C/script%3E
 In this case, the above code will be translated to:
 <form method="post" action="test_form.php/"><script>alert('hacked')</
How To Avoid $_SERVER["PHP_SELF"]
Exploits?
 $_SERVER["PHP_SELF"] exploits can be avoided by using the htmlspecialchars() function.
 The form code should look like this:
 <form method="post" action="<?
php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
 The htmlspecialchars() function converts special characters to HTML entities. Now if the
user tries to exploit the PHP_SELF variable, it will result in the following output:
 <form method="post" action="test_form.php/
&quot;&gt;&lt;script&gt;alert('hacked')&lt;/script&gt;">
 The exploit attempt fails, and no harm is done!
Validate Form Data With PHP
 The first thing we will do is to pass all variables through PHP's htmlspecialchars()
function.
 When we use the htmlspecialchars() function; then if a user tries to submit the
following in a text field:
 <script>location.href('http://www.hacked.com')</script>
 - this would not be executed, because it would be saved as HTML escaped code,
like this:
 &lt;script&gt;location.href('http://www.hacked.com')&lt;/script&gt;
 The code is now safe to be displayed on a page or inside an e-mail.
 We will also do two more things when the user submits the form:
1. Strip unnecessary characters (extra space, tab, newline) from the user input
data (with the PHP trim() function)
2. Remove backslashes (\) from the user input data (with the PHP stripslashes()
function)
 The next step is to create a function that will do all the checking for us (which is
much more convenient than writing the same code over and over again).
 We will name the function test_input().
 Now, we can check each $_POST variable with the test_input() function, and the
PROGRAM:
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>

<?php
// define variables and set to empty values
$name = $email = $gender = $comment = $website = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = test_input($_POST["name"]);
$email = test_input($_POST["email"]);
$website = test_input($_POST["website"]);
$comment = test_input($_POST["comment"]);
$gender = test_input($_POST["gender"]);
}

function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
HI

 <h2>PHP Form Validation Example</h2>  <?php


<form method="post" action="<? echo "<h2>Your Input:</h2>";
php echo htmlspecialchars($_SERVER["PHP echo $name;
_SELF"]);?>"> echo "<br>";
Name: <input type="text" name="name"> echo $email;
<br><br> echo "<br>";
E- echo $website;
mail: <input type="text" name="email"> echo "<br>";
<br><br> echo $comment;
Website: <input type="text" name="web
echo "<br>";
site">
echo $gender;
<br><br>
?>
Comment: <textarea name="comment" row
s="5" cols="40"></textarea>
<br><br> </body>
Gender: </html>
<input type="radio" name="gender" val
ue="female">Female
<input type="radio" name="gender" val
ue="male">Male
<input type="radio" name="gender" val
ue="other">Other
<br><br>
<input type="submit" name="submit" va
lue="Submit">
Output:
PHP Forms - Required Fields
From the validation rules table on the previous page, we see that the "Name", "E-mail", and
"Gender" fields are required. These fields cannot be empty and must be filled out in the HTML
form.

Field Validation Rules

Name Required. + Must only contain letters and whitespace

E-mail Required. + Must contain a valid email address (with @


and .)

Website Optional. If present, it must contain a valid URL

Comment Optional. Multi-line input field (textarea)

Gender Required. Must select one


In the following code we have added some new variables: $nameErr, $emailErr, $genderErr, and
$websiteErr. These error variables will hold error messages for the required fields. We have also added an if
else statement for each $_POST variable. This checks if the $_POST variable is empty (with the PHP empty()
function). If it is empty, an error message is stored in the different error variables, and if it is not empty, it
sends the user input data through the test_input() function:
 <?php  if (empty($_POST["website"])) {
// define variables and set to $website = "";
empty values } else {
$nameErr = $emailErr = $website =
$genderErr = $websiteErr = ""; test_input($_POST["website"]);
$name = $email = $gender = }
$comment = $website = "";
if (empty($_POST["comment"])) {
if ($_SERVER["REQUEST_METHOD"]
$comment = "";
== "POST") {
} else {
if (empty($_POST["name"])) {
$comment =
$nameErr = "Name is
required";
test_input($_POST["comment"]);
} else { }
$name =
test_input($_POST["name"]); if (empty($_POST["gender"])) {
} $genderErr = "Gender is
required";
if (empty($_POST["email"])) { } else {
$emailErr = "Email is $gender =
required"; test_input($_POST["gender"]);
} else { }
$email = }
test_input($_POST["email"]); ?>
PHP - Display The Error Messages
Then in the HTML form, we add a little script after each required field, which
generates the correct error message if needed (that is if the user tries to submit the
form without filling out the required fields):
 <!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>

<?php
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $gender = $comment = $website = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
}

if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
}

if (empty($_POST["website"])) {
$website = "";
} else {
$website = test_input($_POST["website"]);
h i

 if (empty($_POST["comment"])) {  Comment: <textarea name="comment" ro


$comment = "";
ws="5" cols="40"></textarea>
} else {
$comment = test_input($_POST["comment"]); <br><br>
} Gender:
<input type="radio" name="gender" v
if (empty($_POST["gender"])) { alue="female">Female
$genderErr = "Gender is required"; <input type="radio" name="gender" v
} else { alue="male">Male
$gender = test_input($_POST["gender"]);
<input type="radio" name="gender" v
}
} alue="other">Other
<span class="error">* <?
function test_input($data) { php echo $genderErr;?></span>
$data = trim($data); <br><br>
$data = stripslashes($data); <input type="submit" name="submit"
$data = htmlspecialchars($data); value="Submit">
return $data;
</form>
}
?>
<?php
<h2>PHP Form Validation Example</h2> echo "<h2>Your Input:</h2>";
<p><span class="error">* required echo $name;
field</span></p> echo "<br>";
<form method="post" action="<? echo $email;
php echo htmlspecialchars($_SERVER["PHP_SELF"
echo "<br>";
]);?>">
Name: <input type="text" name="name"> echo $website;
<span class="error">* <?php echo $nameErr;? echo "<br>";
></span> echo $comment;
<br><br> echo "<br>";
E-mail: <input type="text" name="email"> echo $gender;
<span class="error">* <? ?>
php echo $emailErr;?></span>
<br><br>
</body>
Output:
PHP Forms - Validate E-mail and URL
PHP - Validate Name
The code below shows a simple way to check if the name field only contains
letters, dashes, apostrophes and whitespaces. If the value of the name field is not valid,
then store an error message:

$name = test_input($_POST["name"]);
if (!preg_match("/^[a-zA-Z-' ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}

PHP - Validate E-mail


The easiest and safest way to check whether an email address is well-formed is to
use PHP's filter_var() function.
In the code below, if the e-mail address is not well-formed, then store an error message:

$email = test_input($_POST["email"]);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
PHP - Validate URL

The code below shows a way to check if a URL address syntax is valid (this regular
expression also allows dashes in the URL). If the URL address syntax is not valid, then
store an error message:

$website = test_input($_POST["website"]);
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?
=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website)) {
$websiteErr = "Invalid URL";
}
PHP - Validate Name, E-mail, and URL
 <!DOCTYPE HTML>  // check if name only contains letters and
<html> whitespace
if (!preg_match("/^[a-zA-Z-' ]*$/",
<head>
$name)) {
<style> $nameErr = "Only letters and white
.error {color: #FF0000;} space allowed";
</style> }
</head> }
<body>
if (empty($_POST["email"])) {
$emailErr = "Email is required";
<?php } else {
// define variables and set to empty $email = test_input($_POST["email"]);
values // check if e-mail address is well-
$nameErr = $emailErr = $genderErr = formed
$websiteErr = ""; if (!filter_var($email,
FILTER_VALIDATE_EMAIL)) {
$name = $email = $gender = $comment =
$emailErr = "Invalid email format";
$website = ""; }
}
if ($_SERVER["REQUEST_METHOD"]
== "POST") { if (empty($_POST["website"])) {
if (empty($_POST["name"])) { $website = "";
} else {
$nameErr = "Name is required";
$website =
} else { test_input($_POST["website"]);
$name = test_input($_POST["name"]);
h i

 E-mail: <input type="text" name="email">


 // check if URL address syntax is valid
if (!preg_match("/\b(?:(?:https?| <span class="error">* <?php echo $emailErr;?
ftp):\/\/|www\.)[-a-z0-9+&@#\/%? ></span>
=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i", <br><br>
$website)) { Website: <input type="text" name="website">
$websiteErr = "Invalid URL"; <span class="error"><?php echo $websiteErr;?
} ></span>
} <br><br>
Comment: <textarea name="comment" rows="5" c
if (empty($_POST["comment"])) { ols="40"></textarea>
$comment = ""; <br><br>
} else { Gender:
$comment = <input type="radio" name="gender" value="fem
test_input($_POST["comment"]); ale">Female
} <input type="radio" name="gender" value="mal
e">Male
if (empty($_POST["gender"])) { <input type="radio" name="gender" value="oth
$genderErr = "Gender is required"; er">Other
} else { <span class="error">* <?
$gender = test_input($_POST["gender"]); php echo $genderErr;?></span>
} <br><br>
} <input type="submit" name="submit" value="Su
bmit">
function test_input($data) { </form>
$data = trim($data);
$data = stripslashes($data); <?php
$data = htmlspecialchars($data); echo "<h2>Your Input:</h2>";
return $data; echo $name;
} echo "<br>";
?> echo $email;
echo "<br>";
<h2>PHP Form Validation Example</h2> echo $website;
<p><span class="error">* required echo "<br>";
field</span></p> echo $comment;
<form method="post" action="<? echo "<br>";
php echo htmlspecialchars($_SERVER["PHP_SELF echo $gender;
"]);?>"> ?>
Name: <input type="text" name="name">
Output:
PHP Complete Form Example
 PHP - Keep The Values in The Form
Name: <input type="text" name="name" value="<?php echo $name;?>">

E-mail: <input type="text" name="email" value="<?php echo $email;?


>">

Website: <input type="text" name="website" value="<?


php echo $website;?>">

Comment: <textarea name="comment" rows="5" cols="40"><?


php echo $comment;?></textarea>

Gender:
<input type="radio" name="gender"
<?php if (isset($gender) && $gender=="female") echo "checked";?>
value="female">Female
<input type="radio" name="gender"
<?php if (isset($gender) && $gender=="male") echo "checked";?>
value="male">Male
<input type="radio" name="gender"
<?php if (isset($gender) && $gender=="other") echo "checked";?>
PHP - Complete Form Example
 // check if name only contains
 <!DOCTYPE HTML>
letters and whitespace
<html>
if (!preg_match("/^[a-zA-
<head> Z-' ]*$/",$name)) {
<style> $nameErr = "Only letters and
.error {color: #FF0000;} white space allowed";
</style> }
</head> }
<body>
if (empty($_POST["email"])) {
<?php $emailErr = "Email is required";
// define variables and set to } else {
empty values $email =
$nameErr = $emailErr = $genderErr test_input($_POST["email"]);
// check if e-mail address is
= $websiteErr = "";
well-formed
$name = $email = $gender =
if (!filter_var($email,
$comment = $website = ""; FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email
if ($_SERVER["REQUEST_METHOD"] format";
== "POST") { }
if (empty($_POST["name"])) { }
$nameErr = "Name is
required"; if (empty($_POST["website"])) {
} else { $website = "";
$name = } else {
hi

 // check if URL address syntax is valid  E-mail: <input type="text" name="email">


if (!preg_match("/\b(?:(?:https?| <span class="error">* <?php echo $emailErr;?></
ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[- span>
a-z0-9+&@#\/%=~_|]/i",$website)) { <br><br>
$websiteErr = "Invalid URL"; Website: <input type="text" name="website">
} <span class="error"><?php echo $websiteErr;?></
} span>
<br><br>
if (empty($_POST["comment"])) { Comment: <textarea name="comment" rows="5" cols="
$comment = ""; 40"></textarea>
} else { <br><br>
$comment = test_input($_POST["comment"]); Gender:
} <input type="radio" name="gender" value="female">
Female
if (empty($_POST["gender"])) { <input type="radio" name="gender" value="male">Ma
$genderErr = "Gender is required"; le
} else { <input type="radio" name="gender" value="other">O
$gender = test_input($_POST["gender"]); ther
} <span class="error">* <?php echo $genderErr;?></
} span>
<br><br>
function test_input($data) { <input type="submit" name="submit" value="Submit"
$data = trim($data); >
$data = stripslashes($data); </form>
$data = htmlspecialchars($data);
return $data; <?php
} echo "<h2>Your Input:</h2>";
?> echo $name;
echo "<br>";
<h2>PHP Form Validation Example</h2> echo $email;
<p><span class="error">* required echo "<br>";
field</span></p> echo $website;
<form method="post" action="<? echo "<br>";
php echo htmlspecialchars($_SERVER["PHP_SELF"] echo $comment;
);?>"> echo "<br>";
echo $gender;
Name: <input type="text" name="name">
?>
<span class="error">* <?php echo $nameErr;?
></span>
</body>
Output:
 Strings in php
PHP String Functions
In this chapter we will look at some common functions to manipulate
strings.

strlen() - Return the Length


of a String
 str_word_count() - Count Words in a String
 The PHP str_word_count() function counts the number of words in a
string.
 strpos() - Search For a Text Within a String

 The PHP strpos() function searches for a specific text within a string.
If a match is found, the function returns the character position of the
first match. If no match is found, it will return FALSE.
 Tip: The first character position in a string is 0 (not 1).
 Tip: The first character position in a string is 0 (not 1).
 str_replace() - Replace Text Within a String
 The PHP str_replace() function replaces some characters with some
other characters in a string.
Program on string functions
 <!DOCTYPE html>
 <html>
 <body>

 <?php
 echo strlen("Hello world!") . "<br/>";
 echo str_word_count("Hello world!") . "<br/>";
 echo strrev("Hello world!") . "<br/>";
 echo strpos("Hello world!", "world") . "<br/>";
 echo str_replace("world", "Dolly", "Hello world!") . "<br/>";
 echo strtolower("GeeksForGeeks") . "<br/>";
 echo strtoupper("hello world") . "<br/>";
 echo strstr( "hello world","hello") . "<br/>";

 ?>

 </body>
 </html>
output

12
2
!dlrow olleH
6
Hello Dolly!
Geeksforgeeks
HELLO WORLD
hello world
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.

 PHP Built-in Functions


 PHP has over 1000 built-in functions that can be called directly, from within a script, to perform a
specific task.
 Please check out our PHP reference for a complete overview of the PHP built-in functions.

 PHP User Defined Functions


 Besides the built-in PHP functions, it is possible to create your own functions.
 A function is a block of statements that can be used repeatedly in a program.
 A function will not execute automatically when a page loads.
 A function will be executed by a call to the function.
create a user defined function in php

 A user-defined function declaration starts with the word function:


 Syntax
function functionName() {
code to be executed;
}
Php program using function

 <!DOCTYPE html>
 <html>
 <body>

 <?php
 function writeMsg() {
 echo "Hello world!";
 }

 writeMsg();
 ?>

 </body>
 </html>
 output:

Hello world!
PHP Function Arguments
Program by passing single argument into t function
<!DOCTYPE html>
<html>
<body>
<?php
function familyName($fname) {
echo "$fname Refsnes.<br>";
}
familyName("Jani");
familyName("Hege");
familyName("Stale");
familyName("Kai Jim");
familyName("Borge");
?>
output

 Jani Refsnes.
Hege Refsnes.
Stale Refsnes.
Kai Jim Refsnes.
Borge Refsnes.
Program passing two
arguments into the function
<!DOCTYPE html>
<html>
<body>

<?php
function familyName($fname, $year) {
echo "$fname Refsnes. Born in $year <br>";
}

familyName("Hege","1975");
familyName("Stale","1978");
familyName("Kai Jim","1983");
?>

</body>
</html>
output

 Hege Refsnes. Born in 1975


Stale Refsnes. Born in 1978
Kai Jim Refsnes. Born in 1983
PHP is a Loosely Typed
Language

 we did not have to tell PHP which data type the variable is.
 PHP automatically associates a data type to the variable, depending
on its value. Since the data types are not set in a strict sense, you
can do things like adding a string to an integer without causing an
error.
 In PHP 7, type declarations were added. This gives us an option to
specify the expected data type when declaring a function, and by
adding the strict declaration, it will throw a "Fatal Error" if the data
type mismatches.
Program without declaring type of
data
<?php
function addNumbers(int $a, int $b) {
return $a + $b;
}
echo addNumbers(5, "5 days");
// since strict is NOT enabled "5 days" ischanged to int(5), and it will
return 10
?>
PHP Default Argument Value
program
<?php declare(strict_types=1); // strict requirement ?>
<!DOCTYPE html>
<html>
<body>
<?php
function setHeight(int $minheight = 50) {
echo "The height is : $minheight <br>";}
setHeight(350);
setHeight();
setHeight(135);
setHeight(80);
?>
</body>
</html>
output

 The height is : 350


The height is : 50
The height is : 135
The height is : 80
PHP Functions - Returning values program

 <?php declare(strict_types=1); // strict requirement ?>


 <!DOCTYPE html>
 <html>
 <body>

 <?php
 function sum(int $x, int $y) {
 $z = $x + $y;
 return $z;
 }

 echo "5 + 10 = " . sum(5,10) . "<br>";


 echo "7 + 13 = " . sum(7,13) . "<br>";
 echo "2 + 4 = " . sum(2,4);
 ?>

 </body>
 </html>
output

 5 + 10 = 15
7 + 13 = 20
2+4=6
PHP Return Type Declarations program

 <?php declare(strict_types=1); // strict requirement


 function addNumbers(float $a, float $b) : float {
 return $a + $b;
 }
 echo addNumbers(1.2, 5.2);
 ?>
output

 6.4
Program with return datatype

 <?php declare(strict_types=1); // strict requirement


 function addNumbers(float $a, float $b) : int {
 return (int)($a + $b);
 }
 echo addNumbers(1.2, 5.2);
 ?>
output

 6
Passing Arguments by Reference
<!DOCTYPE html>
<html>
<body>

<?php
function add_five(&$value) {
$value += 5;
}

$num = 2;
add_five($num);
echo $num;
?>

</body>
</html>
output

 7
Working with files

 Getting information on files


 Opening and closing files
 Reading and writing of files
 Copying
 Renaming
 Deleting
Getting information on files
PHP file_get_contents() Function

Definition and Usage


 The file_get_contents() reads a file into a string.
 This function is the preferred way to read the contents of a file into a
string. It will use memory mapping techniques, if this is supported by
the server, to enhance performance.

Syntax
 file_get_contents(path, include_path, context, start, max_length)
 program on file_get_contents()

 <!DOCTYPE html>
<html>
<body>

<?php
echo file_get_contents("test.txt");
?>

</body>
</html>
0utput

Hello, this is a test file. There are three lines here. This is the last line
 Definition
PHP filesize() Function
and Usage
 The filesize() function returns the size of a file.
 Note: The result of this function is cached.
Use clearstatcache() to clear the cache.

Syntax
 filesize(filename)
Program on filesize()
 <!DOCTYPE html>
<html>
<body>
<?php
echo filesize("test.txt");
?>
</body>
</html>

Output
80
PHP filesize() Function
Program on filesize() function

 <!DOCTYPE html>
<html>
<body>
<?php
echo filesize("test.txt");
?>
</body>
</html>

Output:
 8O
PHP fileowner() Function
Program using fileowner()
function
 <!DOCTYPE html>
<html>
<body>
<?php
echo fileowner("test.txt");
?>
</body>
</html>

Output
0
PHP fileatime() Function
Program on fileatime()
 <!DOCTYPE html>
<html>
<body>
<?php
echo fileatime("webdictionary.txt");
echo "<br>";
echo "Last access: ".date("F d Y H:i:s.",
fileatime("webdictionary.txt"));
?>
</body>
</html>
Output
 1628462283
Last access: August 08 2021 22:38:03.
PHP filetype() Function
Program on filetype()
 <!DOCTYPE html>
<html>
<body>
<?php
echo filetype("test.txt");
?>
</body>
</html>

Output
file
PHP stat() Function
Program on stat()
 <!DOCTYPE html>
<html>
<body>
<?php
$stat = stat("test.txt");
echo "Access time: " .$stat["atime"];
echo "<br>Modification time: " .$stat["mtime"];
echo "<br>Device number: " .$stat["dev"];
?>
</body>
</html>
output

 Access time: 1628033394


Modification time: 1598611896
Device number: 2049
PHP realpath() Function
Program on realpath()

 <?php
echo realpath("test.txt");
?>

 The output of the code above will be:

C:\Inetpub\testweb\test.txt
PHP basename() Function

 Definition and Usage


 The basename() function returns the filename from a path.
 Syntax
 basename(path, suffix)
Program on basename()

 <?php
$path = "/testweb/home.php";
//Show filename
echo basename($path) ."<br/>";
//Show filename, but cut off file extension for ".php" files
echo basename($path,".php");
?>

 The output of the code above


will be:
home.php
home
 php file() function
Definition and Usage
The file() reads a file into an array.
Each array element contains a line from thefile,with the newline
character still attached.

Syntax
file(filename, flag, context)
Program on file()

 <!DOCTYPE html>
<html>
<body>
<?php
print_r(file("test.txt"));
?>
</body>
</html>

Output
Array ( [0] => Hello, this is a test file. [1] => There are three lines here. [2]
=> This is the last line. )
Opening and closing of files

 fopen()-it is used for opening of files.

 fclose()-it is used for closing of files.

 PHP Open File - fopen()


 A better method to open files is with the fopen() function. This function gives you more options
than the readfile().
All modes file opened:
Example on fopen()
 We will use the text file, "webdictionary.txt", during the lessons:
 AJAX = Asynchronous JavaScript and XML
CSS = Cascading Style Sheets
HTML = Hyper Text Markup Language
PHP = PHP Hypertext Preprocessor
SQL = Structured Query Language
SVG = Scalable Vector Graphics
XML = EXtensible Markup Language

 <!DOCTYPE html>
<html>
<body>
<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
echo fread($myfile,filesize("webdictionary.txt"));
fclose($myfile);
?>
</body>
</html>
Output
 AJAX = Asynchronous JavaScript and XML CSS = Cascading Style Sheets
HTML = Hyper Text Markup Language PHP = PHP Hypertext
Preprocessor SQL = Structured Query Language SVG = Scalable Vector
Graphics XML = EXtensible Markup Language
PHP Close File - fclose()

 The fclose() function is used to close an open file.


 It's a good programming practice to close all files after you have finished with
them. You don't want an open file running around on your server taking up
resources!
 The fclose() requires the name of the file (or a variable that holds the
filename) we want to close:
 <?php
$myfile = fopen("webdictionary.txt", "r");
// some code to be executed....
fclose($myfile);
?>
 PHP Check End-Of-File - feof()
 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.
 The example below reads the "webdictionary.txt" file line by line, until end-of-file is reached:

Example
<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to ope
file!");
// Output one line until end-of-file
while(!feof($myfile))
echo fgets($myfile) . "<br>";
}
fclose($myfile);
?>
READ nde write of files

PHP Read File - fread()


 The fread() function reads from an open file.
 The first parameter of fread() contains the name of the file to read
from and the second parameter specifies the maximum number of
bytes to read.
 The following PHP code reads the "webdictionary.txt" file to the end:
 fread($myfile,filesize("webdictionary.txt"));

PHP Read Single Line -
fgets()
 The fgets() function is used to read a single line from a file.
 The example below outputs the first line of the "webdictionary.txt"
file:

Example
 <?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open
file!");
echo fgets($myfile);
fclose($myfile);
?>
Output :

 AJAX = Asynchronous JavaScript and XML


PHP Read Single Character -
fgetc()
 The fgetc() function is used to read a single character from a file.
 The example below reads the "webdictionary.txt" file character by character, until end-of-file is reached:

Example
 <?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
// Output one character until end-of-file
while(!feof($myfile)) {
echo fgetc($myfile);
}
fclose($myfile);
?>

Output
 AJAX = Asynchronous JavaScript and XML CSS = Cascading Style Sheets HTML = Hyper Text Markup
Language PHP = PHP Hypertext Preprocessor SQL = Structured Query Language SVG = Scalable Vector
Graphics XML = EXtensible Markup Language
 PHP Write to File - fwrite()
 The fwrite() function is used to write to a file.
 The first parameter of fwrite() contains the name of the file to write to and the second parameter is the string to be written.
 The example below writes a couple of names into a new file called "newfile.txt":

 Example
 <?php
$myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
$txt = "John Doe\n";
fwrite($myfile, $txt);
$txt = "Jane Doe\n";
fwrite($myfile, $txt);
fclose($myfile);
?>

 Notice that we wrote to the file "newfile.txt" twice. Each time we wrote to the file we sent the string $txt that first contained "John Doe" and second
contained "Jane Doe". After we finished writing, we closed the file using the fclose() function.
 If we open the "newfile.txt" file it would look like this:

 John Doe
Jane Doe
PHP copy() Function
 Definition and Usage
 The copy() function copies a file.
 Note: If the to_file file already exists, it will be overwritten.
 Syntax
 copy(from_file, to_file, context)
 Example
 Copy "source.txt" to "target.txt":
 <?php
echo copy("source.txt","target.txt");
?>
PHP rename() function

Example
Rename a directory + a file:
<?php
rename("images","pictures");
rename("/test/file1.txt","/home/docs/my_file.txt");
?>
 PHP unlink() Function

Example
Delete a file:
<?php
$file = fopen("test.txt","w");
echo fwrite($file,"Hello World. Testing!");
fclose($file);

unlink("test.txt");
?>
 https://medium.com/oceanize-geeks/concepts-of-database-
architecture-dfdc558a93e4
MySQL INSERT INTO
Statement

 The INSERT INTO statement is used to insert new records in a table.

INSERT INTO Syntax


 It is possible to write the INSERT INTO statement in two ways:
 1. Specify both the column names and the values to be inserted:
 INSERT INTO table_name (column1, column2, column3, ...)
VALUES (value1, value2, value3, ...);
 2. If you are adding values for all the columns of the table, you do not need
to specify the column names in the SQL query. However, make sure the
order of the values is in the same order as the columns in the table. Here,
the INSERT INTO syntax would be as follows:
 INSERT INTO table_name
VALUES (value1, value2, value3, ...);
MySQL UPDATE Statemen
t
 The UPDATE statement is used to modify the existing records in a
table.
UPDATE Syntax
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;
mysql DELETE Statement
 The DELETE statement is used to delete existing records in a table.

DELETE Syntax
DELETE FROM table_name WHERE condition;

Note: Be careful when deleting records in a table!

Notice the WHERE clause in DELETE statement.


The WHERE clause specifies which record(s)
should be deleted. If you omit the WHERE clause,
all records in the table will be deleted!
Delete All Records
• It is possible to delete all rows in a table without deleting the table.
This means that the table structure, attributes, and indexes will be
intact:

DELETE FROM table_name;

The following SQL statement deletes all rows in the "Customers"
table, without deleting the table:

Example
DELETE FROM Customers;
PHP Error Handling

 When creating scripts and web applications, error handling is an


important part. If your code lacks error checking code, your program
may look very unprofessional and you may be open to security risks.
 This tutorial contains some of the most common error checking
methods in PHP.

 We will show different error handling methods:


1. Simple "die()" statements
2. Custom errors and error triggers
3. Error reporting
Basic Error Handling: Using the
die() function

Example
 <?php
if(file_exists("mytestfile.txt")) {
$file = fopen("mytestfile.txt", "r");
} else {
die("Error: The file does not exist.");
}
?>

 Now if the file does not exist you get an error like this:

Error: The file does not exist.


Creating a Custom Error Handler

 Creating a Custom Error Handler


 Creating a custom error handler is quite simple. We simply create a
special function that can be called when an error occurs in PHP.
 This function must be able to handle a minimum of two parameters
(error level and error message) but can accept up to five parameters
(optionally: file, line-number, and the error context):
 Syntax
 error_function(error_level,error_message,
error_file,error_line,error_context)
 Now lets create a function to handle errors:
 function customError($errno, $errstr) {
echo "<b>Error:</b> [$errno] $errstr<br>";
echo "Ending Script";
die();
}

 The code above is a simple error handling function. When it is


triggered, it gets the error level and an error message. It then outputs
the error level and message and terminates the script.
 Now that we have created an error handling function we need to
decide when it should be triggered.
Set Error Handler

 The default error handler for PHP is the built in error handler. We are
going to make the function above the default error handler for the
duration of the script.
 It is possible to change the error handler to apply for only some
errors, that way the script can handle different errors in different
ways. However, in this example we are going to use our custom error
handler for all errors:
 set_error_handler("customError");
 Since we want our custom function to handle all errors,
the set_error_handler() only needed one parameter, a second
parameter could be added to specify an error level.
Example
 Testing the error handler by trying to output variable that does not exist:
 <?php
//error handler function
function customError($errno, $errstr) {
echo "<b>Error:</b> [$errno] $errstr";
}

//set error handler


set_error_handler("customError");

//trigger error
echo($test);
?>
 The output of the code above should be something like this:

 Error: [8] Undefined variable: test


Trigger an Error

 In a script where users can input data it is useful to trigger errors when an illegal input
occurs. In PHP, this is done by the trigger_error() function.
 Example
 In this example an error occurs if the "test" variable is bigger than "1":
 <?php
$test=2;
if ($test>=1) {
trigger_error("Value must be 1 or below");
}
?>
 The output of the code above should be something like this:
 Notice: Value must be 1 or below
in C:\webfolder\test.php on line 6
Error Logging

 By default, PHP sends an error log to the server's logging system or a


file, depending on how the error_log configuration is set in the php.ini
file. By using the error_log() function you can send error logs to a
specified file or a remote destination.
 Sending error messages to yourself by e-mail can be a good way of
getting notified of specific errors.
 Send an Error Message by E-Mail
 In the example below we will send an e-mail with an error message and end the script, if a specific
error occurs:

 <?php
//error handler function
function customError($errno, $errstr) {
echo "<b>Error:</b> [$errno] $errstr<br>";
echo "Webmaster has been notified";
error_log("Error: [$errno] $errstr",1,
"someone@example.com","From: webmaster@example.com");|}
//set error handler
set_error_handler("customError",E_USER_WARNING);

//trigger error
$test=2;
if ($test>=1) {
trigger_error("Value must be 1 or below",E_USER_WARNING);}
?>

 The output of the code above should be something like this:

 Error: [512] Value must be 1 or below


Webmaster has been notified

 And the mail received from the code above looks like this:

 Error: [512] Value must be 1 or below

 This should not be used with all errors. Regular errors should be logged on the server using the default
PHP logging system.
PHP MySQL Database
With PHP, you can connect to and manipulate databases.
MySQL is the most popular database system used with PHP.

What is MySQL?
• MySQL is a database system used on the web
• MySQL is a database system that runs on a server
• MySQL is ideal for both small and large applications
• MySQL is very fast, reliable, and easy to use
• MySQL uses standard SQL
• MySQL compiles on a number of platforms
• MySQL is free to download and use
• MySQL is developed, distributed, and supported by Oracle Corporation
• MySQL is named after co-founder Monty Widenius's daughter: My

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.

Databases are useful for storing information categorically. A company may have a database with the
following tables:
• Employees
• Products
• Customers
PHP + MySQL Database System
PHP combined with MySQL are cross-platform (you can develop in Windows and serve on a Unix
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.
To learn more about SQL, please visit our SQL tutorial.

Download MySQL Database


If you don't have a PHP server with a MySQL Database, you can download it for free here:
http://www.mysql.com
hi

Facts About MySQL Database


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).
Another great thing about MySQL is that it can be scaled down to support embedded database
applications.
Look at http://www.mysql.com/customers/ for an overview of companies using MySQL.

PHP Connect to MySQL


PHP 5 and later can work with a MySQL database using:

•MySQLi extension (the "i" stands for improved)


•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?
If you need a short answer, it 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.

So, if you have to switch your project to use another database, PDO makes the
process easy. You only have to change the connection string and a few queries. With
MySQLi, you will need to rewrite the entire code - queries included.

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.
MySQL Examples in Both MySQLi and PDO Syntax

In this, and in the following chapters we demonstrate three ways of working with PHP and
MySQL:

 MySQLi (object-oriented)
 MySQLi (procedural)
 PDO
MySQLi Installation
 For Linux and Windows: The MySQLi extension is automatically installed in most cases, when
php5 mysql package is installed.
 For installation details, go to: http://php.net/manual/en/mysqli.installation.php

PDO Installation
For installation details, go to: http://php.net/manual/en/pdo.installation.php
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);
}
echo "Connected successfully";
?>
Example (MySQLi Procedural)
<?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 (PDO)
<?php
$servername = "localhost";
$username = "username";
$password = "password";

try {
$conn = new PDO("mysql:host=$servername;dbname=myDB", $username,
$password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
?>
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;
HP Create a MySQL Database
o A database consists of one or more tables.
o You will need special CREATE privileges to create or to delete a MySQL database.

Create a MySQL Database Using MySQLi and PDO


 The CREATE DATABASE statement is used to create a database in MySQL.
 The following examples create a database named "myDB":
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();
?>
Example (MySQLi Procedural)
<?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());
}

// 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);
Example (PDO)
<?php
$servername = "localhost";
$username = "username";
$password = "password";

try {
$conn = new PDO("mysql:host=$servername", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "CREATE DATABASE myDBPDO";
// use exec() because no results are returned
$conn->exec($sql);
echo "Database created successfully<br>";
} catch(PDOException $e) {
echo $sql . "<br>" . $e->getMessage();
}

$conn = null;
?>
PHP MySQL Create Table
A database table has its own unique name and consists of columns and rows.

Create a MySQL Table Using MySQLi and PDO

 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" and "reg_date":

 CREATE TABLE MyGuests (


id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
)
Example (MySQLi Object-oriented)
  // SQL TO CREATE TABLE
<?php
$SQL = "CREATE TABLE MYGUESTS (
$servername = "localhost";
ID INT(6) UNSIGNED AUTO_INCREMENT PRIMARY
$username = "username"; KEY,
$password = "password"; FIRSTNAME VARCHAR(30) NOT NULL,
$dbname = "myDB"; LASTNAME VARCHAR(30) NOT NULL,
EMAIL VARCHAR(50),
// Create connection REG_DATE TIMESTAMP DEFAULT
$conn = new mysqli($servername, CURRENT_TIMESTAMP ON UPDATE
$username, $password, $dbname); CURRENT_TIMESTAMP
)";
// Check connection
if ($conn->connect_error) { IF ($CONN->QUERY($SQL) === TRUE) {
die("Connection failed: " . ECHO "TABLE MYGUESTS CREATED
$conn->connect_error); SUCCESSFULLY";
} } ELSE {
ECHO "ERROR CREATING TABLE: " . $CONN-
>ERROR;
}

$CONN->CLOSE();
?>
Example (MySQLi Procedural)
 <?php  // sql to create table
$servername = "localhost"; $sql = "CREATE TABLE MyGuests (
$username = "username"; id INT(6) UNSIGNED AUTO_INCREMENT
$password = "password"; PRIMARY KEY,
$dbname = "myDB"; firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
// Create connection email VARCHAR(50),
$conn = mysqli_connect($servername, reg_date TIMESTAMP DEFAULT
$username, $password, $dbname); CURRENT_TIMESTAMP ON UPDATE
// Check connection CURRENT_TIMESTAMP
if (!$conn) { )";
die("Connection failed: " .
mysqli_connect_error()); if (mysqli_query($conn, $sql)) {
} echo "Table MyGuests created
successfully";
} else {
echo "Error creating table: " .
mysqli_error($conn);
}

mysqli_close($conn);
Example (PDO)
 <?php  // use exec() because no results are
$servername = "localhost"; returned
$username = "username"; $conn->exec($sql);
$password = "password"; echo "Table MyGuests created
$dbname = "myDBPDO"; successfully";
} catch(PDOException $e) {
try { echo $sql . "<br>" . $e->getMessage();
$conn }
= new PDO("mysql:host=$servername;dbname=$dbname",
$username, $password); $conn = null;
// set the PDO error mode to exception ?>
$conn->setAttribute(PDO::ATTR_ERRMODE,
PDO::ERRMODE_EXCEPTION);

// 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),
reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON
UPDATE CURRENT_TIMESTAMP
)";

You might also like