WEB BASED APPLICATION DEVELOPMENT WITH PHP By:Mr. Zameshkumar J. Balhare Lecturer in Computer Department Government Polytechnic, Gondia 1 Unit – 01 Expression and Control Statements in PHP 2 PHP Definition:• The PHP Hypertext Preprocessor (PHP) is a programming language that allows web developers to create dynamic content that interacts with databases. PHP is basically used for developing web based software applications • It is integrated with a number of popular databases, including MySQL, PostgreSQL, Oracle, Sybase, Informix, and Microsoft SQL Server. • PHP supports a large number of major protocols such as POP3, IMAP, and LDAP. PHP4 added support for Java and distributed object architectures. • PHP Syntax is C-Like. Server side interpreted, non-compiled and scripting language • Written with HTML as code is executed by the server, but the result is displayed to the user as plain HTML • It is used to manage dynamic content, databases, session tracking, even build entire e-commerce sites. 3 Science Calculations System System C uses curly braces { } for code blocks. Scripting/ Interpreted PHP Advantages:• Simplicity • Efficiency • Security • Flexibility • Familiarity • Open Source • Database • Support • Maintenance • Scripting Langauge 5 Syntax of PHP :• Syntax A PHP script starts with <?php and ends with ?> <?php echo “Welcome to Online class”; ?> The default file extension for PHP files is ".php" • Example <html> <body> <h1>My first PHP page</h1> <?php echo “Welcome to Online class”; ?> </body> </html> 6 Embedding PHP within HTML :• Inside a PHP file you can write • Example <!DOCTYPE html> HTML like you do in regular HTML <html lang=“en”> pages as well as embed PHP code <head> for server side execution. <meta charset=“UTF-8”> • When it comes to integrating PHP <title>How to put PHP in HTML - Simple code with HTML content, you need to Example</title> enclose the PHP code with the PHP </head> start tag <?php and the PHP end tag ?>. <body> <h1><?php echo " Welcome to Online • The important thing in the above class.“; ?></h1> example is that the PHP code is </body> wrapped by the PHP tags. </html> 7 PHP Comments:• A comment in PHP code is a line that is • Example <!DOCTYPE html> not executed as a part of the program. <html> Its only purpose is to be read by <body> someone who is looking at the code. <?php • Purpose of comment is to make code // This is a single-line comment more readable. It may help other # This is also a single-line comment developer to understand the code. • PHP support single line as well as /* This is multiline comment block that multiline comments. span across more than. • To start a single line comment either */ start with two slash (//) or hash (#). ?> • Multiline comments start with /* and </body> end with */ </html> 8 PHP echo and Print:• In PHP, there are 2 way to get output or • Example print output: echo and print. <?php • The echo statement is used with or echo "Hello world!<br/>"; // display string without parentheses: echo or echo(). echo "This ", "string ", "was ", "made ", "with • The echo statement can display multiple parameters.<br/>"; // strings as multiple anything that can be displayed to the $a= “Hello, PHP”; browser: string, number, variable value $b= 5; $c=10; and result of expression . echo “$a<br/>”; • The PHP print statement is similar to the echo statement and use as a alternative. echo $b.”+”.$c.”=“; //Display variable • echo has no return value while print has a echo $b+$c; return value of 1 so it can be used in ?> expressions </body> </html> 9 PHP Print:• In PHP, echo can take multiple • Example parameters (although such usage is <?php rare) while print can take one print "Hello world!<br/>"; argument. $a= “Hello, PHP”; • echo is marginally faster than print. $b= 5; Output :$c=10; Hello world! print “$a<br/>”; Hello, PHP print $b.”+”.$c.”=“; //Display variable 5+10=15 print $b+$c; ?> 10 PHP Variable Scope:• Local Variable:• The variable declared within a function called Local variable. • So Local Variable scope is within function only. • Local Variable can not accessed outside that function. • And outside function such a variable treat as different variable. • Example <?php $num=10; function local_var() { $num=50; echo “local num=$num<br/>”; } local_var(); echo “Variable num outside local_var()=$num<br/>”; ?> 11 PHP Variable Scope:• Global Variable:• The variable declared outside a function called Local variable. • So Global Variable scope is all function. • Global Variable can accessed outside that function. • To get access within a function we need to use “global” keyword before the variable . • Example <?php $num=10; function local_var() { global $num; echo “Access global variable within function=$num<br/>”; } local_var(); echo “Global Variable num outside of local_var()=$num<br/>”; ?> 12 PHP $ and $$ Variable:• The $var is normal variable that • Example store any value. <?php • The $$var is reference variable that $a=“Hi”; store the value of $variable inside it. $$a=“GPG”; • $a represent variable but $$a represent a variable with the echo $a.“<br/>”; content of $a. echo $$a.“<br/>”; // echo “$$a<br/>;” $$a=$($a) echo $Hi; Output:?> Hi GPG GPG 13 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 14 PHP Arithmetic Operators:- 15 PHP Assignment Operators:- 16 PHP Comparison Operators:- 17 PHP Increment / Decrement Operators:- 18 PHP Logical Operators:- 19 PHP String Operators:- 20 PHP Array Operators:- 21 PHP Conditional Assignment Operators:- 22 PHP Data Types:• Variables can store data of different • PHP String types, and different data types can do different things. • A string is a sequence of characters, like • PHP supports the following data types: "Hello world!". 1) String • A string can be any text inside quotes. You can use single or double quotes: 2) Integer 3) Float (floating point numbers - also <?php called double) $x = "Hello world!"; 4) Boolean $y = 'Hello GPG!'; 5) Array 6) Object echo $x; 7) NULL echo "<br>"; 8) Resource echo $y; ?> 23 PHP Integer:• An integer data type is a non-decimal • In the following example $x is an integer. The number between -2,147,483,648 and PHP var_dump() function returns the data 2,147,483,647 type and value: • Rules for integers: <html> 1) An integer must have at least one <body> digit <?php 2) An integer must not have a decimal $x = 5985; point var_dump($x); 3) An integer can be either positive or negative ?> 4) Integers can be specified in: decimal </body> (base 10), hexadecimal (base 16), </html> octal (base 8), or binary (base 2) notation 24 PHP Float:• A float (floating point number) is a • In the following example $x is an integer. The number with a decimal point or a PHP var_dump() function returns the data type and value: number in exponential form. • Output:float(10.68) <html> <body> <?php $x = 10.68; var_dump($x); ?> </body> </html> 25 PHP Boolean:• A Boolean represents two possible • Example:states: TRUE or FALSE. <?php • Booleans are often used in $a = 11; conditional testing. You will learn $b = 11.22; more about conditional testing in a $c=“Hello”; later chapter of this tutorial. $d= True; • Output:var_dump($a); int(11) var_dump($b); var_dump($c); float(11.22) var_dump($d); string(5) “Hello” ?> bool(true) 26 PHP Array:• An array stores multiple values in • Example:one single variable. • In the following example $cars is an array. • Output:array(3) { [0]=> string(5) "Volvo" [1]=> string(3) "BMW" [2]=> string(6) "Toyota" } The PHP var_dump() function returns the data type and value: <html> <body> <?php $cars = array("Volvo","BMW","Toyota"); var_dump($cars); ?> </body> </html> 27 PHP Object:• Classes and objects are the two • Example:main aspects of object-oriented • <?php class Car { programming. public $color; public $model; • A class is a template for objects, public function __construct($color, $model) { $this->color = $color; and an object is an instance of a $this->model = $model; class. } public function message() { • When the individual objects are return "My car is a " . $this->color . " " . $this->model . "!"; created, they inherit all the } } properties and behaviors from the = new Car("black", "Volvo"); class, but each object will have $myCar echo $myCar -> message(); echo "<br>"; different values for the properties. $myCar = new Car("red", "Toyota"); echo $myCar -> message(); ?> 28 PHP NULL Value:• Null is a special data type which can • Example:have only one value: NULL. • A variable of data type NULL is a <html> variable that has no value assigned <body> to it. <?php • If a variable is created without a $x = "Hello world!"; value, it is automatically assigned a $x = null; value of NULL. var_dump($x); • If a variable is created without a ?> value, it is automatically assigned a </body> value of NULL. </html> 29 PHP Resource:• The special resource type is not an • Example:actual data type. It is the storing of <html> a reference to functions and <body> resources external to PHP. <?php • A common example of using the $f1 = fopen(“note.txt“,”r”); resource data type is a database var_dump($f1); call. echo”<br>”; $link=mysql_connect(“localhost”,”root”,””); var_dump($link); ?> </body> </html> 30 PHP Type Juggling:• Means dealing with variable type. • Example:• In PHP a variable type is determined <html> <body> by the context in which it is used. <?php • If an Integer value is assign to a $var1= 1; variable, it become a integer. $var2=“20”; • If an String value is assign to a variable, it become a String. $var3=$var1+$var2; $var1=$var1+1.3 • PHP does not required explicit type definition in a variable declaration. $var1=5*”10 small birds”; ?> • The conversion process whether explicit or implicit known as…….. </body> </html> 31 PHP Type Casting:• Typecasting is a way to convert one • Example:data type variable into different <html> data type. <body> • A type can be cast by inserting one <?php of the cast in front of variable. $count=“5”; • Output:echo gettype($count); string $count is a string settype($count,’int’); integer echo gettype($count); $count is a integer ?> </body> </html> 32 PHP Decision Making Control Statements:• If Statement:- • Example:• The if statement is used to execute <html> block of code only if the specified <body> <?php condition is true. $a=10; • Syntax:if($a>0) if(condition) { { echo “The number $a is Positive”; // code to be execute } } ?> </body> </html> 33 PHP Decision Making Control Statements:• If-else Statement:- • Example:• The if...else statement executes some <?php code if a condition is true and another $t = date("H"); 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; } if ($t < "10") { echo "Have a good morning!"; } else { echo "Have a good day!"; } ?> 34 PHP Decision Making Control Statements:• Nested-If Statement:- • Example:<?php • Means an if block inside another if block. We use it when we have more than 2 $t = date("H"); condition and also called as if-else-if statement if ($t < "10") { echo "Have a good morning!"; • Syntax:} if (condition) elseif ($t < "20") { { // code to be executed1 if condition is true; echo "Have a good day!"; } elseif (condition) } { // code to be executed2 if condition is true; else { } else echo "Have a good night!"; { // code to be executed1 if both condition1 and condition2 are false } ?> } 35 PHP Decision Making Control Statements:• Switch Statement:• The switch statement is used to perform different actions based on different conditions. • 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; } • Example:<?php $favcolor = "red"; switch ($favcolor) { case "red": echo "Your favorite color is red!"; break; case "blue": echo "Your favorite color is blue!"; break; case "green": echo "Your favorite color is green!"; break; default: echo "Your favorite color is neither red, blue, nor green!"; } ?> 36 PHP Break and Continue Statements:• Break Statement:- • Example:• The keyword break ends execution <?php of the current for, for each, while, for($i=1; $i<=5; $i++) do while or switch structure. { • When break executed inside loop echo”$i<br/>”; the control automatically passes to if($i==3) the first statement outside loop. { • Output:break; 1 } 2 } ?> 3 37 PHP Break and Continue Statements:• Continue Statement:- • Example:• It is used to stop processing the <?php current block of code in the loop for($i=1; $i<=5; $i++) and goes to the next iteration. { • It is used to skip a part of the body if($i==3) of loop under certain condition. { • Output:continue; } 1 echo”$i<br/>”; 2 } 4 ?> 5 38 PHP Loop Control Statements:• while Statement:- • Example:- • It is execute block of code if and as <?php $i=0; long as a test condition is true. • While is an entry controlled loop while($i<=10) statement. • Syntax:while(if the condition is true) { // code is executed } { echo”$i<br/>”; $i+=2; } ?> 39 PHP Loop Control Statements:• Do- while Statement:- • Example:- • It is exit control loop which means <?php that it first enter the loop, execute $i=1; the statements and then check condition. do • Statements is executed at least once . • Syntax:do { // code is executed } while(if the condition is true); { echo”$i<br/>”; $i+=2; } while($i<10); ?> 40 PHP Loop Control Statements:• For Statement:- • Example:- • It is used when you know how many <?php time you want to execute a $sum=0; statement or a block of statement. for($i=0;$i<=10;$i+=2) • Also known as entry controlled loops. • Syntax:for(initialization expression; test condition; update exp.) { // code is executed } { echo”$i<br/>”; $sum+=$i; } echo “Sum=$sum”; ?> 41 PHP Loop Control Statements:• foreach Statement:- • Example:- • It is used for array and object. <?php $arr= array (10,20,30,40,50); • For every counter of loop, an array element and the next counter is foreach($arr as $i) shifted to next element. • Syntax:foreach (array_element as value) { // code is executed } { echo”$i<br/>”; } ?> 42 Unit – 02 Arrays, Functions and Graphics 43 PHP Array Definition:• Array in PHP is type of data structure that allow to store multiple elements of same data type under a single variable thereby saving us the efforts of creating a different variable for every data. • An Array in PHP actually an ordered map. A map is a type that associates values to keys. • An array stores multiple values of similar type in one single variable which can be accessed using their index or key. • 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"; 44 PHP Array Definition:• 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. Create an Array in PHP:• In PHP, the array() function is used to create an array: array(); 45 PHP Array Type:• 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 46 Get The Length of an Array:• The count() function is used to • Example:return the length (the number <?php of elements) of an array: $cars = array("Volvo", "BMW", • Output:"Toyota"); 3 echo count($cars); ?> 47 Indexed or Numeric Array:• An array with a numeric index where values are stores linearly • Numeric array use number as access key. • Syntax 1:<?php $variable_name[n]=value; ?> • 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"; 48 Indexed or Numeric Array:• Syntax 1 Example:• Output:<?php Computer Engg. $course[0] = “Computer Engg.”; Information Tech. $course[1] = “Information Tech.”; Civil $course[2] = “Civil”; // Accessing the element directly echo $course[0+, “<br>”; echo $course[1], “<br>”; echo $course[2], “<br>”; ?> 49 Indexed or Numeric Array:• Syntax 2:• Example:<?php <?php $variable_name[n]=array(n=>value, ……….); $course = array( 0=> “Computer Engg.”, 1 => “Information Tech.”, 2 => “Civil”); ?> echo $course[0]; Output:?> Computer Engg. 50 Loop Through an Indexed Array:• To loop through and print all the • Example:values of an indexed array, you <?php could use a for loop, like this: $cars = array("Volvo", "BMW", "Toyota"); • Output:$arrlength = count($cars); Volvo for($x = 0; $x < $arrlength; $x++) BMW { Toyota echo $cars[$x], "<br>"; } ?> 51 Associative Arrays:• This type of array is similar to • Syntax:indexed array but instead of linear storage, every value can be assigned with user define <?php key of string type. $variable_name*‘key_name’+=value; • Associative arrays are arrays that use named keys that you $variable_name=array(‘key_name’ assign to them. => value,……….); • An array with a string index ?> where instead of linear storage, each value assigned a specific key. 52 Associative Arrays:• 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"; • Example 1:<?php $age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43"); echo “Ben age is=”, $age*“Ben”+; ?> Output:- Ben age is= 37 53 Loop Through an Associative Array:• To loop through and print all • Example:the values of an associative <?php array, you could use a foreach $age = array("Peter"=>"35", loop, like this: • Output:Key=Peter, Value=35 Key=Ben, Value=37 Key=Joe, Value=43 "Ben"=>"37", "Joe"=>"43"); foreach($age as $x => $x_value) { echo "Key=" . $x . ", Value=" . $x_value; echo "<br>"; } ?> 54 Multidimensional Arrays:• These are array that contain • Syntax:other nested array. array ( • An array which contain single array (elements….), or multiple arrays within it an array (elements….), can be accessed via multiple indices. ……… • 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. 55 Multidimensional Arrays:• Example 1:- // accessing elements echo “Ram Email id is:” <?php .$person*0+*“email’”+ // Define multidimension array $person = array( echo “Laxman Age is:” array(“name => “Ram”, “age” => .$person*1+*“age’”+ “20”, “email” => ram@gmail.com”), ?> array(“name => “Laxman”, “age” => “18”, “email” => laxman@gmail.com”), Output:array(“name => “Sita”, “age” => “19”, Ram Email id is: ram@gmail.com “email” => sita@gmail.com”) Laxman Age is: 18 ); 56 Accessing Multidimensional Arrays elements:• First, take a look at the • We can store the data from the table above in a two-dimensional array, like following table: this: $cars = array ( array("Volvo",22,18), array("BMW",15,13), array("Saab",5,2), array("Land Rover",17,15) ); • Now the two-dimensional $cars array contains four arrays, and it has two indices: row and column. 57 Accessing Multidimensional Arrays elements:• To get access to the elements of the $cars array we must echo $cars[0][0].": In stock: point to the two indices (row ".$cars[0][1].", sold: ".$cars[0][2].".<br>"; and column): <?php $cars = array ( array("Volvo",22,18), array("BMW",15,13), array("Saab",5,2), array("Land Rover",17,15) ); 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>"; ?> 58 Accessing Multidimensional Arrays elements:- •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. 59 Accessing Multidimensional Arrays elements:• We can use a for loop inside another for loop to get element from multidimensional array. <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> </html> 60 Accessing Multidimensional Arrays elements:• 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 • 15 61 Extracting Data from Arrays :• You can use extract() function extract($course); to extract data from array and echo “CO=$CO<br>”; echo “IT=$IT<br>”; store it in variables. <html> <title> Array </title> <body> <?php $course*“CO”+ = “Computer Engg.”; $course*“IT”+ = “Information Tech.”; $course*“CE”+ = “Civil”; echo “CE=$CE<br>”; ?> </body> </html> Output: CO=Computer Engg. IT=Information Tech. CE=Civil 62 Compact() Function:• This function is opposite of Example:extract() function. <?php • It return an array with all the $var1=“PHP”; variables added to it. $var2=“JAVA”; • The compact() functions create $var3=compact(“var1”, “var2”); associative array whose key print_r(var3); value are the variable name ?> and whose values are the variable values. Output:Array( [var1]=> PHP [var2]=> JAVA) 63 Implode and Explode:• Imploding and Exploding are Syntax:couple of important functions string implode(separator, array); of PHP that can be applied on strings or arrays. • The implode() function accept • The implode() is a built-in two parameter out of which one function in PHP and is used to is optional and one is join the element of an array. mandatory. • The implode function return a • Separator:string from the element of an array. • Array:64 Implode :• Example:<html> <head> <title> array </title> <body> <?php $course[0] = “Computer Engg.”; $course[1] = “Information Tech.”; $course[2] = “Civil”; $text=implode(“,”,$course); echo $text; ?> </body> </html> Output:- Computer Engg., Information Tech., Civil 65 Implode :• Example without separator:<html> <head> <title> array </title> <body> <?php $inputArray= array(‘CO’, ‘IF’, ‘CE’); // join without separator print_r(implode($inputArray)); print_r(“<BR>”); // join without separator print_r(implode(“-”,$inputArray)); ?> </body> </html> Output:COIFCE CO-IF-CE 66 Explode:• The explode() function break a string into an array. • The explode() is a built-in function in PHP is used to split a string in different string. • The explode() function split a string based on the string delimeter. • Syntax:array explode(separator, OrignalString, NoOfElements); • The implode() function accept three parameter out of which one is optional and two is mandatory. • Separator:- • OrignalString:• NoOfElements 67 Explode :• Example:<html> <head> <title> array </title> <body> <?php $str= PHP: Welcome to the world of PHP; print_r(explode(“ ”,$str)); ?> </body> </html> Output:- Array ( [0]=> PHP: [1]=> Welcome [2]=> to [3]=> the [4]=> world [5]=> of [6]=> PHP 68 Array_flip() function :• The array_flip() function flip/exchange all key with their associated value in an array. • The array_flip() is a built-in function in PHP is used to exchange element within array. <html> <head> <title> array </title> <body> <?php $a=array( “CO”=> “Computer Engg.”, “IT” => “Information Tech.”, “CE” => “Civil”); $result=array_flip($a); print_r($result); ?> </body> </html> Output:Array ( [Computer Engg.]=> CO [Information Tech.]=> IT [Civil]=> CE) 69 Traversing Arrays:• Traversing an array means to visit each and every element of array using a looping structure and and iterator function . • There are several way to traverse array in PHP. <?php $course = array(“CO”, “IT”, “CE”); echo “Looping using foreach:<br>”; foreach($course as $val) { echo $val “<br>”; $total = count($course); echo “The number of element are $total<br>”; echo “Looping using for:<br>”; for($n=0; $n<$total; $n++) { echo $course*$n+, “<br>”; } ?> 70 Traversing Arrays:• Output:foreach($course as $val) { Looping using foreach : echo $val “<br>”; CO $total = count($course); IT echo “The number of element are $total<br>”; CE The number of elements are 5 echo “Looping using for:<br>”; for($n=0; $n<$total; $n++) Looping using for : { CO echo $course*$n+, “<br>”; IT } CE ?> 71 Modifying Data in Arrays:• Example:<html> <head> <title> Modifying in array </title> <body> <?php $course*0+ = “Computer Engg.”; $course*1+ = “Information Tech.”; $course*2+ = “Civil”; echo “Before Modification”; echo $course*0+, “<br>”; echo $course[1], “<br>”; echo $course[2], “<br>”; echo “After Modification <br>”; $course[1] = “Mechanical Engg.”; $course[] = “Electrical Engg.”; for($i=0; $i<count($course);$i++) { echo $course*$i+, “<br>”; } ?> </body></html> 72 Modifying Data in Arrays:• Output:Before Modification Computer Engg. Information Tech. Civil After Modification Computer Engg. Mechanical Engg. Civil Electrical Engg Deleting Array Element:• The unset() function is used to remove element from array. • The unset() function is used to destroy any other variable and same way use to delete any element of an array. • Syntax:void unset($var,….); 73 Deleting Array Element:• Example 1:<?php $course = array(“CO”, “IT”, “ME”, “CE”); echo “Before Deletion: <br>”; echo $course*0+, “<br>”; echo $course*1+, “<br>”; echo $course*2+, “<br>”; echo $course[3], “<br>”; unset($course[1]); echo “Before Deletion: <br>”; print_r($course); echo “Delete entire array elements: <br>”; unset($course[1]); ?> • Output:Array ([0]=> CO [2]=> ME [3]=> CE) Delete entire array elements: 74 Deleting Array Element:• Example 2:<?php $course*0+ = “Computer Engg.”; $course*1+ = “Information Tech.”; $course*2+ = “Civil”; $course[3] = “Electrical Engg.”; echo “Before Deletion: <br>”; echo $course*0+, “<br>”; echo $course*1+, “<br>”; echo $course*2+, “<br>”; echo $course[3], “<br>”; echo “After Deletion: <br>”; $course*1+ = “ ”; for($i=0; $i<count($course);$i++) { echo $course*$i+, “<br>”; } ?> 75 Deleting Array Element :• Output:Before Deletion: Computer Engg. Information Tech. Civil Electrical Engg. After Deletion: Computer Engg. Civil Electrical Engg Reducing an array:• The array_reduce() function apply a user define function to each element of an array, so as to reduce the array to a single value. • Syntax:• Mixed array_reduce(array $array, callable $callback [, mixed $initial = null]) 76 Reducing Array Element :• Example:<?php $n = array(1, 3, 5, 7); $total = array_reduce($n, ‘add’); echo $total; ?> • Output:- 16 Array_search:• The array_search() function an array for a value and return the key • Syntax:• Mixed array_reduce (mixed $to_find, array $input [, bool $strict = false]) 77 Array_search :• Example:<?php $a = array(“a”=> “5”, “b”=> “7”, “c”=> “9”,); echo array_search(7, $a, true); ?> • Output:- b 78 Sorting Array :• Sorting refer to ordering data in • ksort() - sort associative arrays in an alphanumerical, numerical ascending order, according to order and increasing or the key decreasing fashion. • Sorting function for array in PHP • arsort() - sort associative arrays in descending order, according • sort() - sort arrays in ascending order to the value • rsort() - sort arrays in descending • krsort() - sort associative arrays order in descending order, according • asort() - sort associative arrays in to the key ascending order, according to the value 79 sort() and rsort() in Array :• Example:<?php $num = array(40, 61, 2, 22, 13); echo “Before sorting:<br>”; $arrlen=count($num); for($x=0; $x<$arrlen; $x++) { echo $num[$x], “<br>”; } echo “After sorting in Ascending order:<br>”; sort($num); $arrlen=count($num); for($x=0; $x<$arrlen; $x++) { echo $num*$x+, “<br>”; } echo “After sorting in Descending order:<br>”; 80 sort() and rsort() in Array :sort($num); $arrlen=count($num); for($x=0; $x<$arrlen; $x++) { echo $num*$x+, “<br>”; } ?> • Output:Before sorting:40 61 2 22 13 After sorting in Ascending order: 2 13 22 40 61 81 sort() and rsort() in Array :Output:After sorting in Descending order: 61 40 22 13 2 82 aort() and ksort() in Array :• Example:echo "<br>"; <?php } $age = array("Peter"=>"35", echo “Sorting according to Key:<br>”; "Ben"=>"37", "Joe"=>"43"); ksort($age); echo “Sorting according to foreach($age as $x => $x_value) Value:<br>”; { asort($age); echo "Key=" . $x . ", Value=" . foreach($age as $x => $x_value) $x_value; echo "<br>"; { echo "Key=" . $x . ", Value=" . } ?> $x_value; 83 aort() and ksort() in Array :Output:Sorting according to Value: Key=Peter, Value=35 Key=Ben, Value=37 Key=Joe, Value=43 Sorting according to Key: Key=Ben, Value=37 Key=Joe, Value=43 Key=Peter, Value=35 84 Splitting and Merging Array :• You can also cut up and • You can also merge two or more merge array when needed. array with array_mearge() • Suppose you have 4 course in array of course and you want to get a subarray consisting of • Syntax:last 2 items. • You can do this with array_merge(array1, array2,…..); array_slice() function • Syntax:array_slice(array, start, length, preserve); 85 Splitting Array :• Example:echo “After Spliting array: <br>”; <?php subarray = array_slice($course, 1, $course*0+ = “Computer Engg.”; 2); foreach($subarray as $value) $course*1+ = “Information Tech.”; { $course*2+ = “Civil”; echo “Before Spliting array: <br>”; echo “Course: $value<br>”; } echo $course*0+, “<br>”; ?> echo $course*1+, “<br>”; echo $course*2+, “<br>”; 86 Splitting Array :• Output:Before Spliting array: Computer Engg Information Tech. Civil After Spliting array: Course: Information Tech. Course: Civil 87 Merging Array :• Example:<?php $sem5 = array(“ACN”, “OSY”, “SEN”); $sem6 = array(“WPD”, “JAVA”, “Python”); $subject = array_merge($sem5, $sem6); foreach($subject as $value) { echo “Subject: $value<br>”; } ?> Output:Subject: ACN Subject: OSY Subject: SEN Subject: WPD Subject: JAVA Subject: Python 88 array_diff() & PHP Array functions:• Example:<?php $a1 = array(“ACN”, “OSY”, “SEN”); $a2 = array(“ACN”, “JAVA”, “Python”); $diff = array_diff($a1, $a2); ?> Output:Array ([1]=> OSY [2]=> Python) • • • • • • • • • • array_intersect():array_chunk():array_combine():array_unique():array_count_value() array_pop():array_product():array_push:array_reverse():array_sum():89 PHP Functions and its Types:• The real power of PHP comes • A function will be executed by a from its functions. call to the function. • PHP function are similar to • There a two part other programming language. 1) Crate a PHP function • A function is a piece of code which take one or more input 2) calling a PHP function of parameter and does some processing and return a value. • User define function declaration • PHP has more than 1000 start with word function: built-in functions, and in addition you can create your own custom functions. 90 PHP Functions and its Types:• Syntax:function functionName() { code to be executed; } • Example:<html> <head> <title> PHP function Program </title> </head> <body> <?php> function writeMessage() { echo “Welcome to PHP function!”; } writeMessage(); ?> </body> </html> Output:Welcome to PHP function! 91 PHP Functions with Parameters:• PHP gives you option to pass your parameters inside a function. • Example 1:<html> <head> <title> PHP function with parameter </title> </head> <body> <?php> function add($num1, $num2) { $sum = $num1+ $num2; echo “Sum of two number is: $sum”; } add(70,40); ?> </body> </html> Output:Sum of two number is: 110 92 PHP Functions with Parameters:• Example 2:familyName(“Ram","1985"); <html> familyName(“Laxman","1988"); <head> familyName(“Sita","1990"); <body> ?> </body> </html> <?php function familyName($fname, $year) { Output:echo “Name $fname Born in Name: Ram Born in 1985 $year <br>"; Name: Laxman Born in 1988 } Name: Sita Born in 1990 93 PHP Functions returning value:• A function can return a value using the return statement in conjunction with a value or object. • You can return more than one value from a function using return array (1,2,3,4). • Example:<?php> function add($num1, $num2) { $sum = $num1+ $num2; return $sum”; } $return_value = add(70,40); echo “Returned value from the function: $return_value”; ?> Output:Returned value from the function: 110 94 Variable Functions:• PHP support the concept variable function. • Means that if variable name is parentheses appended to it, PHP will look for a function with same name. • Example:<?php> function simple() { echo “In simple()<br/>”; } function data($arg =“”) , echo “In data(); argument was ‘$arg’.</br>”; } $func = ‘simple’; $func(); $func = ‘data’; $func(‘test’) ?> Output:In Simple() In data(); argument was ‘test’. 95 Anonymous Functions (Lambda Function):• We can define a function that has no specified name. such a function is Anonymous Functions or Lambda Funcion. • Use as a values of callback. • The function is randomly generated and returned. • Example 1:<?php> $add= creare_function( ‘$a’, ‘$b’, ‘return($a+$b)’); $r = $add(2, 3); echo $r; ?> Output:5 96 Anonymous Functions (Lambda Function):• Example 2:?> <?php> Output:Welcome To GPG $gpg= function($name); Welcome To Computer Dept. { printf(“\nWelcome To”, $name); }; $gpg(‘GPG’); echo”<br>”; $gpg(‘Computer Dept. ’); 97 Operation on String:• PHP string is a sequence of characters i.e. used to store and manipulate text . • String is one of the data type supported by PHP. • The string variable can contain alphanumerical characters. • A “string” of text can be stored in a variable in much the same way as a numerical value. • But the assignment must surround the string with quote mark (“…” or ‘…’) Single quoted string:<?php $name = ‘Ram’; $str = ‘Hello $name’; echo $str “br>”; var_dump(‘Hello Ram’); ?> Output: Hello $name string(9) Hello Ram 98 Operation on String: Double quoted string:<?php $name = ‘Ram’; $str = “Hello $name”; echo $str; ?> Output: Hello Ram 99 Converting to and from Strings: Using number_format():// convert string in number • The number_format() function echo number_format($num,3); is used to convert string into a ?> number. Output: 2021 <?php 2021.042 $num = “2021.0429”; //convert string in number echo number_format($num), “<br>”; 100 Converting to and from Strings: Using type casting:• Typecasting can directly // Type cast using float convert a string into float, echo (float)$num, “<br>”; double and integer primitive // Type cast using double type. echo (double)$num; <?php ?> $num = “2021.0429”; Output: 2021 //Type cast using int 2021.0429 echo (int)$num, “<br>”; 2021.0429 101 Converting to and from Strings: Using intval() and floatval:• The intval() and floatval() // intval() convert string into float function also convert a string echo floatval($num); into its corresponding integer ?> and float value. <?php Output: 2021 2021.0429 $num = “2021.0429”; //intval() convert string into int echo intval($num), “<br>”; 102 Type Specifier :• %: To display %. • u: display as an unsigned decimal number. • b: display in Binary number. • c: display as the corresponding • x: display as a hexadecimal number. ASCII character. • d: display as a decimal number. • e: for Scientific notation • f: display as a real number. • o: display as a octal number. • s: display as a string. 103 Type Specifier:• Example:<?php> printf(“ I have %s pens and %s pencils. <br>”, 3, 12); $m= 04; $date= 29; echo “The date is:”; printf(“%02d-%02d-%04d <br>”, $date, $m, $y); $str=sprintf(“ After using I have ?> %s pens and %s pencils.<br>”, 2, Output:10); I have 3 pens and 12 pencils. echo $str, “<br>”; After using I have 2 pens and 10 pencils. $y=2021; The date is: 29-04-2021 104 PHP String Functions:- 105 PHP String Functions:- 106 PHP String Functions:- 107 PHP String Functions:strcomp() 108 PHP String Functions:- trim($str) 109 PHP String Functions:ltrim($str) 110 PHP Math Functions:- 111 PHP Math Functions :- 112 PHP Math Functions :- 113 PHP Math Functions :- 114 PHP Math Functions :- 115 Round():• This function take numerical value as argument and return the highest integer value by rounding up value. • PHP_ROUND_HALF_UP: • PHP_ROUND_HALF_DOWN: • PHP_ROUND_HALF_EVEN: • PHP_ROUND_HALF_ODD: Example:• round(1.75572,2) = 1.76 • round(2341757, -3)= 234200 • round(7.5, 0, PHP_ROUND_HALF_UP)= 8 • round(7.5, 0, PHP_ROUND_HALF_DOWN)= 7 • round(7.5, 0, PHP_ROUND_HALF_EVEN)= 8 • round(7.5, 0, PHP_ROUND_HALF_ODD)= 7 116 PHP Date Function:• PHP Date function is an In-built function that works date data type. • The PHP date function is used to format a date or time into a human readable format. • Syntax:date(format, timestamp); Example:<?php echo “Today’s Date is:”; $today = date(“d/m/Y”); echo $today; ?> • Output:Today’s Date is: 01/04/2021 117 Get a Date:• Here are some characters that Example:are commonly used for dates: <?php • d - Represents the day of the month (01 to 31) • m - Represents a month (01 to 12) • Y - Represents a year (in four digits) • l (lowercase 'L') - Represents the day of the week 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"); ?> • Output:Today is 2020/11/03 Today is 2020.11.03 Today is 2020-11-03 Today is Tuesday 118 Get a Time:• Here are some characters that Example:are commonly used for times: <?php echo "The time is " . date("h:i:sa"); • H - 24-hour format of an hour (00 ?> to 23) • Output:• h - 12-hour format of an hour with leading zeros (01 to 12) The time is 07:50:27am • i - Minutes with leading zeros (00 to 59) • s - Seconds with leading zeros (00 to 59) • a - Lowercase Ante meridiem and Post meridiem (am or pm) 119 Get Your Time Zone:• Example:- • Create a Date With mktime():- • Syntax:<?php date_default_timezone_set("Americ mktime(hour, minute, second, month, day, year) a/New_York"); echo "The time is " . date("h:i:sa"); • Example:?> <?php $d=mktime(03, 14, 54, 04, 01, 2021); Output:echo "Created date is " . date("Y-m-d The time is 03:40:15pm h:i:sa", $d); ?> Output:- Created date is 2021-04-01 03:14:54pm 120 Basic Graphics Concept:• PHP support basic computer graphics. An image is a rectangle of pixels of various colors. • Computer usually create color using a color theory model called RGB model. • The three basic color that are combine to create the colors that we see on the computer display. • Creating an Image:• The imagecreate() function is used to create a new image. • Syntax:- imagecreate(x_size, y_size); • x_size and y_size parameter are in pixel. • Example:$img_height= 200; $img_width= 400; $img= imagecreate($img_height, $img_width); 121 Basic Graphics Concept:• It is preferred to use imagecreatetruecolor() to create a image instead of imagecreate(). • Because the image processing occurs on the highest quality image possible which can be create using imagecreatetruecolor() . • To set a colors to be used in image use imagecolorallocate() • You can pass RGB value on imagecolorallocate() to set color. • If you want solid red the you had pass red value 0-255 and blue and green value 0. $bg_color= imagecolorallocate($img, 200, 0, 0); 122 Basic Graphics Concept:• To send JPEG image back to • Example1:browser, you have to tell the <?php Brower you are doing so with the header function to set the $img_height= 200; $img_width= 400; image type. • You sent the image with the $img= imagecreate($img_height, $img_width); imagejpeg() function. $bg_color= imagecolorallocate($img, • Imagegif():200, 0, 0); • imagejpeg() header(‘Content-Type:image/jpeg); • Imagewbmp():imagejpeg($img); ?> • Imagepng():123 Create Image:• Example1:<?php $img_height= 200; $img_width= 400; $img= @imagecreate($img_height, $img_width); $bg_color= imagecolorallocate($img, 255, 0, 0); imagepng($im,"image.png"); imagedestroy($im); print "<img src=image.png?".date("U").">"; ?> 124 Draw Line on Image:- 125 Draw Line on Image:• <?php $im = @imagecreate(200, 200); $background_color = imagecolorallocate($im, 255, 255, 0); // yellow $red = imagecolorallocate($im, 255, 0, 0); // red $blue = imagecolorallocate($im, 0, 0, 255); // blue imageline ($im, 5, 5, 195, 5, $red); imageline ($im, 5, 5, 195, 195, $blue); imagepng($im,"image.png"); imagedestroy($im); print "<img src=image.png?".date("U").">"; ?> 126 Draw Rectangles on Image:Y1 X1 Y2 X2 127 Draw Rectangles on Image :• <?php $im = @imagecreate(200, 200); $background_color = imagecolorallocate($im, 255, 255, 0); // yellow $red = imagecolorallocate($im, 255, 0, 0); // red $blue = imagecolorallocate($im, 0, 0, 255); // blue imagerectangle ($im, 5, 10, 195, 50, $red); imagefilledrectangle ($im, 5, 100, 195, 140, $blue); imagepng($im,"image.png"); imagedestroy($im); print "<img src=image.png?".date("U").">"; ?> 128 Draw Ellipses on Image:- 129 Draw Ellipses on Image :• <?php $im = @imagecreate(200, 200); $background_color = imagecolorallocate($im, 255, 255, 0); // yellow $red = imagecolorallocate($im, 255, 0, 0); // red $blue = imagecolorallocate($im, 0, 0, 255); // blue imageellipse($im, 50, 50, 40, 60, $red); imagefilledellipse($im, 150, 150, 60, 40, $blue); imagepng($im,"image.png"); imagedestroy($im); print "<img src=image.png?".date("U").">"; ?> 130 Draw Arc on Image:- 131 Draw Arc on Image :• <?php $im = @imagecreate(200, 200); $background_color = imagecolorallocate($im, 255, 255, 0); // yellow $red = imagecolorallocate($im, 255, 0, 0); // red $blue = imagecolorallocate($im, 0, 0, 255); // blue imagearc($im, 20, 50, 40, 60, 0, 90, $red); imagearc($im, 70, 50, 40, 60, 0, 180, $red); imagefilledarc($im, 20, 150, 40, 60, 0, 90, $blue, IMG_ARC_PIE); imagefilledarc($im, 70, 150, 40, 60, 0, 180, $blue, IMG_ARC_PIE); imagepng($im,"image.png"); imagedestroy($im); print "<img src=image.png?".date("U").">"; ?> 132 Image with text:• The imagestring() function is an inbuilt function in PHP which is used to draw the string horizontally. • This function draw the string at given position. • Syntax:Imagestring( $image, $font, $x, $y, $string, $color); • Example:- png.php file name <?php header(‘Content-Type:image/jpeg); $img= imagecreate(150, 50); $bg_color= imagecolorallocate($img, 220, 230, 140); $txt_color= imagecolorallocate($img, 0, 0, 0); Imagestring( $img, 5, 6, 17, “Welcome to GPG”, $txt_color); imagepng($img); ?> 133 Image with text :• <?php; $im = @imagecreate(200, 200) $background_color = ima, 50, "Hello !", gecolorallocate($im, 255, 255, 0); // yellow $red = imagecolorallocate($im, 255, 0, 0); // red imagestring($im, 5, 10, "Hello !", $red); imagestring($im, 2, 5$red); imagestring($im, 3, 5, 90, "Hello !", $red); imagestring($im, 4, 5, 130, "Hello !", $red); imagestring($im, 5, 5, 170, "Hello !", $red); imagestringup($im, 5, 140, 150, "Hello !", $red); imagepng($im,"image.png"); imagedestroy($im); print "<img src=image.png?".date("U").">"; ?> 134 Resize Image:- 135 Resize Image:• <?php; $original_image = imagecreatefrompng("image.png"); $image_info = getimagesize("image.png"); $width = $image_info[0]; // width of the image $height = $image_info[1]; // height of the image $new_width = round ($width*0.7); $new_height = round ($height*0.7); $new_image = imagecreate($new_width, $new_height); imagecopyresized($new_image, $original_image, 0, 0, 0, 0, $new_width, $new_height, $width, $height); imagepng($new_image,"resized_image.png"); imagedestroy($new_image); print "<img src=image.png?".date("U").">"; ?> 136 Displaying Image in HTML page:• If you had a PNG on the server, • Example:abc.png, you could display it <html> this way in a web using HTML. <head> <title> Embedding created image in <img src= “abc.png”> HTML page </title> </head> • In the same way you can give <body> the name of the script that <h2> PNG image create using script generate the png image </h2> <br> <img src= “png.php”> <img src= “png.php”> </body> </html> 137 Creation of PDF Document:• FPDF is a PHP class which allows generating PDF file with pure PHP that is to say without using a PDFlib library. • F from FPDF stand for free. • We may use it for any kind of usage and modify it to suite we need. • Features of FPDF:Automatic page break. Choice of measure unit, page format and margins. Page header and footer format. Automatic line break and text justification. Image format (JPEG, GIF, and PNG) Color and line. Page compression. 138 Cell():- ‘http://www.gpgondia.ac.in’ 139 Creation of PDF Document :<?php require(‘fpdf.php’); $pdf = new FPDF(); $pdf->AddPage(); $pdf->SetFont(‘Arial’, ‘B’, 16); $pdf->Cell(80, 10, ‘Welcome to online class’); $pdf->Output(‘my_pdf.pdf’, ‘I’); ?> 140 Adding border , alignment, color , link in PDF Document :- <?php require('fpdf.php'); $pdf = new FPDF(); $pdf->AddPage(); $pdf->SetFont('Arial','B',16); $pdf->Cell(80,10,‘Welcome to GPG!',1,0,'R',false,'https://www.gpgondia.ac.in.com'); $pdf->Output(‘gpg.pdf','I'); // send to browser and display ?> 141 Adding background color in PDF Document :<?php require('fpdf.php'); $pdf = new FPDF(); $pdf->AddPage(); $pdf->SetFont('Arial','B',16); $pdf->SetFillColor(1,255,255); $pdf->Cell(80,10,‘Welcome to GPG!',1,0,'R',false,'https://www.gpgondia.ac.in.com'); $pdf->Output(‘gpg.pdf','I'); // send to browser and display ?> 142 Adding font colour by SetTextColor() in PDF Document :<?php require('fpdf.php'); $pdf = new FPDF(); $pdf->AddPage(); $pdf->SetFont('Arial','B',16); $pdf->SetFillColor(1,255,255); $pdf->SetTextColor(255,254,254); $pdf->Cell(80,10,‘Welcome to GPG!',1,0,'R',false,'https://www.gpgondia.ac.in.com'); $pdf->Output(‘gpg.pdf','I'); // send to browser and display ?> 143 Saving the PDF Document :• $pdf->Output('my_file.pdf','I'); // Send to browser and display • $pdf->Output('my_file.pdf','D'); // Force file download with name given ( name can be changed ) • $pdf->Output('my_file.pdf','F'); // Saved in local computer with the file name given • $pdf->Output('my_file.pdf','S'); // Return the document as a string. 144 Happy Learning Thank You ! 145 Unit- 03 Object Oriented Concept in PHP 146 Advantage of OOP:• OOP is an approach to software development that makes it easy to map business requirement to code modules. • PHP is OOP language, is a type of PL principle added to PHP, that helps in building complex, reusable web application. • OOP invoke the use of classes to organize the data and structure of application. • We model our problems and process using object. So object oriented application consist object that collaborate with each other to solve the problem • By using OOP in PHP we can create modular web application and perform any activity in the object model structure. • By using OOP there is opportunity for code reuses within given application as well as across different project. 147 Basic OOP Concepts:• Classes:- This is a programmer-defined data type, which includes local functions as well as local data. • Objects:- An individual instance of the data structure defined by a class. • Properties:- Characteristics of a class or object are known as properties. • Methods:- The behavior of a class that is, action associated with class. • Member Variable:- An individual instance of the data structure defined by a class. • Member function:- These are the function defined inside a class and are used to access object data. • Inheritance:- When a class is defined by inheriting the existing function of a parent class then it is called inheritance. • Parent Class:- A class that is inherited from another class. 148 Basic OOP Concepts:• Child Class:- A class that inherits from another class. This is also called a subclass or derived class. • Polymorphism:- This is an object-oriented concept where the same function can be used for different purposes • Overloading − A type of polymorphism in which some or all operators have different implementations depending on the types of their arguments. • Data Abstraction − Any representation of data in which the implementation details are hidden. • Encapsulation − refers to a concept where we encapsulate all the data and member functions together to form an object. • Constructor & Destructor:- Object Formation and Object Deletion. 149 Creating Classes and Object in PHP:• A class is template for object, and • Create Object:object is an instance of class. • Example:<?php class Car • Syntax:{ <?php } class classname_of_class $Maruti = new Car(); { $Honda = new Car(); // code is here print_r($Maruti ); } print_r($Honda ); ?> ?> 150 Creating and Using Property:• Class Prosperity are very similar to Declaring Properties:variables. Understanding Property Visibility:class MyClass • Public:- Access by any code, { whether that code is inside or pubic $property1; outside the class. • Private:- Access only by the code private $property2; inside the class. protected $property3; • Protected:- Like private property } but difference is any class that inherits from the class can access. 151 Creating and Using Property:• Example:- <?php class Car { // Properties public $name; public $color; // Methods function set_name($name) { $this->name = $name; } function get_name() { return $this->name; } } ?> 152 Accessing Property and Method:• Once we have created Object we can • Example1:use the -> (object operator) to <?php access property and method of the class Student object. { • Syntax:var $roll_no; var $name; $object->property_name; function display() { $object->method_name([arg,…..]); echo “Roll No:” . $this->roll_no . “<br>” 153 Accessing Property and Method:echo “Name:” . $this-> name; } } $s1 = new Student; $s1 -> roll_no =12; $s1 -> name = “Ram”; $s1 -> display(); ?> Output:- Roll No: 12 Name: Ram • Example2:<?php class Fruit { // Properties public $name; public $color; // Methods function set_name($name) { $this->name = $name; } 154 Accessing Property and Method:function get_name() { return $this->name; } } echo $apple->get_name(); echo "<br>"; echo $banana->get_name(); ?> $apple = new Fruit(); $banana = new Fruit(); $apple->set_name('Apple'); $banana->set_name('Banana'); Output:Apple Banana 155 Accessing Property and Method:Example:<?php class Rectangle { // Declare properties public $length = 0; public $width = 0; // Method to get the area public function getArea(){ return ($this->length * $this>width); } } // Create a new object from // Method to get the perimeter Rectangle class public function getPerimeter(){ $obj = new Rectangle; return (2 * ($this->length + $this// Get the object properties values >width)); } echo $obj->length; 156 Accessing Property and Method:// Call the object methods echo “Perimeter:” . $obj// Set object properties values >getPerimeter() . “<br>”; $obj->length = 30; echo “Area” . $obj->getArea(); $obj->width = 20; ?> Output:- Perimeter: 100 // Read the object properties values Area: 600 again to show the change echo $obj->width; echo $obj->length; echo $obj->width; 157 Differences:self • Self keyword is not preceded by any symbol. • To access class variable and method using the self keyword, we use scope resolution operator :: • It is refer to the static member of class. • Example:- self::<class_member> this • this keyword should be preceded with a $ symbol. • -> symbol is used with $this as we have used with an object to access the property of that object. • It is refer to the non static member of class with -> operator. • Example:- $this -> <class_member> 158 __construct Function in PHP:• A constructor allows you to Example:initialize an object's properties class MyClass upon creation of the object. { • If you create a __construct() function, PHP will automatically function_construct() call this function when you create { an object from a class. echo “Welcome to PHP constructor. • Notice that the construct function <br>”; starts with two underscores (__)! } • Constructor saves us from calling the set_name() method which } reduces the amount of code. $obj = new Myclass; 159 __construct Function in PHP:Constructor Type:• Default Constructor:• It has no parameters, but the value to the default constructor can be pass dynamically. • We can define constructor by using function__construct() Example:<?php class Sample { function Sample() { echo “Its a user define constructor of the class Sample. <br>”; } function__construct() { echo “Its a Pre-define constructor of the class Sample. <br>”; } } $obj = new Sample; ?> 160 __construct Function in PHP:Constructor Type:• Parameterized Constructor:• It take the parameters and you can pass the value to the data member. • It is use to initialize member variable at the time of object creation. • -> operator is use to set value for variable. Example:<?php class emp { private $fname; private lname; public function__construct($fname, $lname) { echo “Initializing the object…. <br>”; $this->fname = $fname; $this->lname = $lname; } public function showName() { 161 __construct Function in PHP:echo “ My name is “. Mr.” . $this>fname . “ ” . this->lname; } } $e1 = new emp ( “Ram”, “Mishra”); e1->showName(); Output:- Initializing the object…. My name is Mr. Ram Mishra Example2:<?php class Fruit { public $name; public $color; function __construct($name, $color) { $this->name = $name; $this->color = $color; } 162 __construct Function in PHP:function get_name() { echo “ $this->name is”; } function get_color() { return $this->color; } } $apple = new Fruit("Apple", "red"); echo $apple->get_name(); echo $apple->get_color(); ?> Output:- Apple is Red 163 __destruct Function in PHP:• A destructor is called when the Syntax:object is destructed or the script is function_destruct() stopped or exited. { • If you create a __destruct() function, PHP will automatically call this } function at the end of the script. • Notice that the destruct function starts with two underscores (__)! • A __destruct() function that is automatically called at the end of the script. 164 __destruct Function in PHP :Example:<?php class emp { Private $fname; private lname; public function__construct($fname, $lname) { echo “Initializing the object…. <br>”; $this->fname = $fname; $this->lname = $lname; } public function__destruct() { echo “Destroying Objrct…..”; } public function showName() { 165 __destruct Function in PHP :echo “ My name is “. Mr.” . $this- Example2:>fname . “ ” . this->lname; <?php } class Fruit { } public $name; public $color; $e1 = new emp ( “Ram”, “Mishra”); function __construct($name, $color) e1->showName(); { Output:Initializing the object…. My name is Mr. Ram Mishra Destroying Objrct….. $this->name = $name; } 166 __destruct Function in PHP :Advantages of __destruct function __destruct() function:{ • Destructor is used to free up echo "The fruit is {$thismemory allocation, so that space >name}."; is available for new object or free } up resources for other task. } • It effectively make programs run $apple = new Fruit("Apple"); more efficiently and is very ?> Output:- This fruit is Apple useful as they carry clean up tasks. 167 Inheritance in PHP:• Inheritance in OOP = When a The new sub class. class derives from another class. • Syntax:• The child class will inherit all the class Parent public and protected properties and methods from the parent { class. In addition, it can have its // parent class code own properties and methods. } • An inherited class is defined by class Child extends Parent using the extends keyword. { • We create a new sub class with all functionality of that existing // The child can be use the class, and we add ne member to parent class code } 168 Inheritance in PHP :Example 1:}} <?php Class Rect extends Shape class Shape { { public $height; public $length; public function__construct($length, public $width; $width, $height) public function__construct($length, { $width) { $this->length = $length; $this->length = $length; $this->width = $width; $this->width = $width; $this->height = $height; 169 Inheritance in PHP :} public function intro() Output:{ The length is 10, the width is 20 and echo "The length is {$this->length}, the height is 30 the width is {$this->width} and the height is {$this->height} "; } } $r = new Rect( 10, 20, 30) $r-> intro(); ?> 170 Inheritance in PHP :Example 2:<?php class Shape { public $length; public $width; public function__construct($length, $width) { $this->length = $length; $this->width = $width; } public function intro() { echo "The length is {$this->length} and the width is {$this->width} "; }} Class Rect extends Shape { public $height; public function__construct($length, $width, $height) { $this->length = $length; 171 Inheritance in PHP :$this->width = $width; $this->height = $height; } protected function introduction() { echo "The length is {$this->length}, the width is {$this->width} and the height is {$this->height} "; } } $r = new Rect( 10, 20, 30); $r-> intro(); $r-> introduction(); ?> Output:The length is 10 and the width is 20 Fatal error 172 Inheritance in PHP :} Example 3:protected function intro() <?php { class Shape echo "The length is {$this->length} { and the width is {$this->width} "; public $length; }} public $width; Class Rect extends Shape public function__construct($length, { $width) public function introduction() { { $this->length = $length; echo “The shape is Rectangle”; $this->width = $width; 173 Inheritance in PHP :$this->intro(); Type of Inheritance:- • Single Inheritance:- } } $r = new Rect( 10, 20, 30); $r-> introduction(); ?> Output:The shape is Rectangle. The length is 10 and the width is 20 When a subclass is derived simply from its parent class then this mechanism is known as Simple inheritance or Single or one level Inheritance. A B 174 Inheritance in PHP :• Syntax:class Parent { // parent class code } class Child extends Parent { // The child can be use the parent class code } • Multilevel Inheritance:When a subclass is derived from a derived class then this mechanism is known as the multilevel Inheritance. A B C 175 Inheritance in PHP :• Syntax:class A { } class B extends A { } class C extends B { } • Example:<?php class grandparent { function level1() { echo “ Grand-Parent <br>”; }} class parent extends grandparent { function level2() 176 Inheritance in PHP :{ echo “Parent <br>”; }} class child extends parent { function level3() { echo “ Child <br>”; }} $obj = new child() $obj = level1(); $obj = level2(); $obj = level3(); ?> Output:Grand-Parent Parent Child 177 Inheritance in PHP :• Example:• Hierarchical Inheritance consist of <?php Single parent class and is inherited by { multiple child class. public function f_a() • In this type one class is extended by { many subclasses. echo “class A”; • It is one-to-many relationship. } A } class b extends a B C D { • Hierarchical Inheritance:- 178 Inheritance in PHP :public function f_b() { echo “class B”; } } class c extends a { public function f_c() { echo “class C”; } } echo c::f_c(). “<br>”; echo c::f_a() ?> Output:class C Class A 179 Method or Function Overloading in PHP:• If the derived class is having a Example:same method name as the base <?php class then the method in the derived class take precedence class Base over or overrides the base class { method function show() • Function overloading or method { overloading is the ability to create multiple function of the echo “Display Base <br>”; same name with different } implementation depending on types of their requirement. } 180 Method or Function Overloading in PHP :class Derived extends Base { function show() { echo “Display Derived”; } } $obj = new Derived(); $obj = show(); ?> • Output:- Display Derived • To call base class show() method we can use parent::method(); • Scope resolution operator (::) is used to refer function and variable in base class. function show() { parent::show(); echo “Display Derived”; } 181 Method or Function Overriding in PHP:• In function overriding, both Example:parent and child classes should <?php have same function name with class P and number of arguments. { • It is used to replace parent function geeks() method in child class. { • The purpose of overriding is to echo "Parent"; change the behavior of parent } class method. • The two methods with the same } name and same parameter is class C extends P { called overriding. 182 Method or Function Overriding in PHP:function geeks() { echo "\nChild"; } } $p = new P; $c= new C; $p->geeks(); $c->geeks(); ?> • Output:- Parent Child • When a method or a class is declared as final then overriding on that method or class cannot be performed also inheritance with the class is not possible. 183 Class Overriding using Final Keyword:echo "<br> In the BaseClass Method display function"; } } // as the base class is declared as final function ABC() $obj1 = new BaseClass; $obj1->display(); { echo "<br> In the BaseClassMethod $obj1->ABC(); ABC function"; Output:} In the BaseClass Method ABC function function display() In the BaseClass Method display function { Example:final class BaseClass { // here you cannot extend the base class 184 Method Overriding using Final Keyword :Example:class BaseClass { // Final method – display echo "<br /> In the Base cLass ABC function"; } } // this cannot be overridden in base class class DerivedClass extends BaseClass final function display() { { function ABC() echo "<br /> In the Base class { display function"; echo "<br /> In the Derived class ABC } function"; function ABC() } { } 185 Method Overriding using Final Keyword :Cloning Object:$obj1 = new DerivedClass; $obj1->display(); $obj1->ABC(); • Object cloning is the process in PHP to create a copy of an object. • An object copy is created by using the clone keyword. • When an object is cloned, PHP will Output:perform a shallow copy of all In the Base class display function object property. In the Derived class ABC function • Syntax:-$copy_object_name = clone $object to_be_copied 186 Cloning Object :Example:<?php class MyClass { public $color; public $amount; } $obj = new MyClass(); $obj->color = 'red'; $obj->amount = 5; $copy = clone $obj; print_r($copy); ?> • Output:MyClass Object ([color] => red [amount] => 5) 187 __clone() method to break references:Example:<?php class MyClass { public $amount; public function __clone() { $value = $this->amount; unset($this->amount); $this->amount = $value; } } // or $amount = $value; $value = 5; $obj = new MyClass(); $obj->amount = &$value; $copy = clone $obj; $obj->amount = 6; print_r($copy); ?> Output:MyClass Object ([amount] => 5) 188 Introspection in PHP:• Introspection is the ability of a • You don’t need to know which program to examine an object’s methods or properties are characteristics, such as its name, defined when you write your parent class (if any), properties, code. and methods. • Instead, you can discover that • PHP offers a large number of information at runtime, which functions that you can use to makes it possible for you to write generic debuggers, serializes, accomplish the task. • With introspection, you can profilers. write code that operates on any class or object. 189 Introspection in PHP:- 190 Introspection :Example1:<?php if(class_exists(‘GPG')) { $obj =new GPG(); echo "This is www.gpg.ac.in"; } else { echo "Not exist"; } ?> Output:- Not exist 191 Introspection :Example2:<?php class GPG { //decl } if(class_exists(‘GPG')) { $obj =new GPG(); echo "This is www.gpg.ac.in"; } else { echo "Not exist"; } ?> Output:- This is www.gpg.ac.in 192 Introspection :Example3:<?php class GPG { function co() {} Function it() {} } $obj =new GPG(); $class_methods = get_class_method(‘GPG’); print_r($class_method); ?> Output:- Array ([0]=> co [1]=> it) 193 Serialization and unserialization in PHP:• Serialization is a technique used by programmer to preserve their working data in a format that can later be restore to its previous form. • Sterilizing object means converting it to byte stream representation that can stored in a file. • Serialization in PHP is mostly automatic process. • Example:<html> <body> <?php $s_data = serialize(array("Red", "Green", "Blue")); echo $s_data; $us_data = unserialize($s_data) ; echo $us_data; ?> </body></html> 194 Serialization in PHP:• Example 2:• Output:a:3:{i:0;s:3:"Red";i:1;s:5:"Green"; <?php i:2;s:4:"Blue";} class Student Array ([0]=>Red [1]=>Green $age = 19; [2]=>Blue function show_Age() { echo $this->age; } } 195 Serialization in PHP:$stud = new Student; Sstud->show_Age(); $s_obj = serialize($stud); $fp = fopen(“gpg.txt”, “w”); fwrite($fp, $s_obj); fclose($fp); $us_obj = unserialize($s_obj); $us_obj->show_Age(); ?> 196 Happy Learning Thank You ! 197 Unit- 04 Creating and Validating Forms 198 Web Page in PHP:• Now a days, PHP is becoming a • And submit it to web server for standard in the world of web processing. Forms are used to programming with its simplicity, communication between users performance, reliability, and server. flexibility and speed. • A form is an HTML tag that • One of the most powerful Graphical User Interface (GUI) feature of PHP is the way it item such as input box, check box, radio button etc. handles HTML forms. • Form are essential parts in web • The form is define using the development. Forms are used to <form>….</form> get input from the user. 199 Web Page in PHP:- 200 Creating Web Page Using GUI component:• A document that containing • Two methods “get” and “post” blank field, that the user can fill are commonly used to send data the data or user can select the from HTML controls to PHP script on server. data it is known as form. • Generally the data will store in • URL is used to specify the the database. We can create and location, which helps browser understand where to send the use form in PHP. • To get form data we need to use data on server mentioned in the PHP superglobals $_GET and “action” attribute of a form. $_POST. 201 Creating Web Page Using GUI component:• Example:<html> <head> <title> Simple PHP program</title></head> <body> <form method =“get” action= abc.php> <input name= “username” type=“text”> <input name= “submit” type=“Submit”> </form> </body></html> GET Method:• The GET method sends the encoded user information appended to the page request (to the url). • The page and the encoded information are separated by the ? character. http://www.gpg.com/index.html ?name1=value1&name2=value2 202 Creating Web Page Using GUI component:• The GET method is restricted to send up to 1024 character only. • Never use GET method if we have password or other sensitive information to be sent to server. • GET can not be used to send binary data, like image or word document to server. • The data sent by GET method can be accessed using QUERY_STRING environment var • Example:<?php if(isset($_GET*“s1”+) { echo “Welcome” . $_GET*‘name’+. “<br>”; echo “You are” . $_GET*‘name’+. “year old.”; } ?> 203 Creating Web Page Using GUI component:</form> <html> </body></html> <body> <form action =“<?php $_PHP_SELF?>” method= “GET”> Name:<input type=“text” name= “name” > Age:<input type=“text” name= “age”> <input name= “s1” value=“ok” type=“Submit”> 204 Creating Web Page Using GUI component:• The data sent by POST method Post Method:• The POST method transfer go through HTTP header so information via HTTP headers, security depend on HTTP protocol. not through the URL. • The POST method dose not have • The PHP provide $_POST any restriction on data size to be associative array to access all the sent information using POST sent. method. • The POST method can be used to send ASCII as well as Binary data. 205 Creating Web Page Using GUI component:• Example:<?php if(isset($_POST*“s1”+) { echo “Welcome” . $_POST*‘name’+. “<br>”; echo “You are” . $_POST*‘name’+. “year old.”; } ?> <html> <body> <form action =“<?php $_PHP_SELF?>” method= “POST”> Name:<input type=“text” name= “name” > Age:<input type=“text” name= “age”> <input name= “s1” value=“ok” type=“Submit”></body></html> 206 Server Role:- 207 Server Role:- Welcome.html 208 Server Role :• Example:- gpg.php <?php if(isset($_POST*“mailid”+) { echo “<p> Mail id:” $_POST*“mailid”+. ”; } ?> <html> gpg.html <body> <form method= “POST” action =“gpg.php” > <label>Mail id.</label> . <input type=“text” name= “mailid” id= “mailid”> <input type=“Submit” value=“Submit”> <input type="reset"> </form></body></html> 209 Form Control :HTML Input Types:• • • • • • • • • • • <input type="button"> <input type="checkbox"> <input type="color"> <input type="date"> <input type="datetime-local"> <input type="email"> <input type="file"> <input type="hidden"> <input type="image"> <input type="month"> <input type="number"> • <input type="password"> • <input type="radio"> • <input type="range"> • <input type="reset"> • <input type="search"> • <input type="submit"> • <input type="tel"> • <input type="text"> • <input type="time"> • <input type="url"> • <input type="week"> 210 Form Control :Text Field:- gpg.html <html> <body> <form method= “POST” action =“gpg.php” > <label for="fname">First name:</label><br> <input type="text" id="fname" name="fname"><br> <label for="lname">Last name:</label><br> <input type="text" id="lname" name="lname"> <input name= “s1” value=“ok” type=“Submit”></body></html> gpg.php:<?php if(isset($_POST*“s1”+) { echo “First Name” $_POST*“fname”+. “<br>”; echo “Last Name” $_POST*“lname”+; } ?> . . 211 Form Control :Radio Button:- gpg.html gpg.php:- <html> <body> <form method= “POST” action =“gpg.php” > <label> Select your Gender </label></br> <input type=“radio” value= “male” name=“gender” >Male</br> <input type=“radio” value= “female” name=“gender” >Female</br> <input type= “submit” value=“Submit”> </form></body></html> <?php if(isset($_POST*“gender”+) { echo “<p>Gender:” $_POST*“gender”+. “</p>”; } ?> . 212 Form Control :Text Area:- gpg.html gpg.php:- <html> <body> <form method= “POST” action =“gpg.php” > <label> Suggestion: </label><br> <textarea name= “data” id= “data” cols= “50” row= “5”> </teaxarea> <input name= “submit” type=“Submit”> </form></body></html> <?php if(isset($_POST*“data”+) { echo “<p>Suggestion:” $_POST*“data”+. “</p>”; } ?> . 213 Form Control :Check Box:- gpg.html <html> <body> <form method= “POST” action =“gpg.php” > <label> Select your Hobbies </label></br> <input type=“checkbox” value= “Cricket” name=“cricket” >Cricket</br> <input type=“checkbox” value= “Football” name=“football” >Football</br> <input type=“checkbox” value= “Hokey” name=“hokey” >Hokey</br> <input type= “submit” value=“Submit”></form></body></html> gpg.php:<?php echo “<p>You Hobbies are:” . $_POST*“cricket”+. “,” . $_POST*“football”+. “,” . $_POST*“hokey”+. “</p>”; ?> 214 Form Control :ListBox:- gpg.html <html> <body> <form method= “POST” action =“gpg.php” > <label> Select your Gender: </label></br> <select name=“gender” id= “gender”>Cricket</br> <option value= “Male”>Male</option> <option value= “female”>female</option> <input type= “submit” value=“Submit”></body></html> gpg.php:<?php if(isset($_POST*“gender”+) { echo “<p>You Gender is:” . $_POST*“gender”+. “</p>”; } ?> 215 Form Control :Buttons:- gpg.html <html> <body> <form method= “POST” action =“gpg.php” > <input type= “submit” name=“btnSub” value= “Save Changes”> <input type= “submit” name=“btnDel” value= “Delete”> <input type="button" onclick="alert('Hello World!')" value="Click Me!"> </form></body></html> gpg.php:<?php if($_SERVER *‘REQUEST_METHOD’ ==‘GET’+) { if(isset($_POST*“btnDel”+) { echo “Delete Button is clicked”; } else { echo “Save Button is clicked”; } } ?> 216 Form Control :hidden:- gpg.html <html> <body> <form method= “POST” action =“gpg.php” > <input type= “hidden” name=“user_id” id=“user_id value= “101”> <input type= “submit” value= “Submit”> <input type="button" </form></body></html> gpg.php:<?php if(isset($_POST*“user_id”+) { echo “USER ID:” $POST*“user_id”+ . “</p>”; } ?> . 217 Working with Multiple Forms:A Web page having multiple form • uniquely identify the form in can be processed in two type web page with multiple form. Posting each form to different • Data from each form to separate PHP script file for processing. PHP script file for processing by • Multiple functionality can be specific PHP script filename in provided in a single web page by the action attribute of the form. providing multiple forms in a web page having different • Each PHP script should be written in such a fashion that will functionality. • Each form on this web page will handle all the data coming from the form. be given a separate name that 218 Posting each form to different PHP script file:multiform.html <html> <body> <form name = “mailform” method= “POST” action =“maildata.php” > <input type= “text” name=“email” id=“email”> <input type= “submit” name = “mailsub” value = “Send mail”> </form> <form name = “mobileform” method= “POST” action =“mobiledata.php” > <input type= “text” name =“mobileno” id=“mobileno”> <input type= “submit” name = “mobilesub” value = “Send Contact info”> </form> </html> </body> 219 Posting each form to different PHP script file:Maildata.php mobiledata.php <?php <?php if($_SERVER *‘REQUEST_METHOD’ if($_SERVER ==‘POST’+) *‘REQUEST_METHOD’ ==‘POST’+) { { if(!empty($_POST*“mobilesub”+)) { if(!empty($_POST*“mailsub”+)) { echo “Your mail id is:” . echo “Your mail id is:” . $POST*‘mobileno’+; $POST*‘email’+; } } } } ?> ?> 220 Working with Multiple Forms:Posting all form to single PHP • uniquely identify the form in web page with multiple form. script file for processing. • Multiple functionality can be • Data from each form to single provided in a single web page by PHP script file for processing by providing multiple forms in a specifying PHP script filename in web page having different the action attribute of the form. functionality. • Each PHP script should be • Each form on this web page will written in such a fashion that will handle all the data coming from be given a separate name that multiple form. 221 Posting all form to single PHP script file:singleform.html <html> <body> <form name = “mailform” method= “POST” action =“singleform.php” > <input type= “text” name=“email” id=“email”> <input type= “submit” name = “mailsub” value = “Send mail”> </form> <form name = “mobileform” method= “POST” action =“singleform.php” > <input type= “text” name =“mobileno” id=“mobileno”> <input type= “submit” name = “mobilesub” value = “Send Contact info”> </form> </html> </body> 222 Posting all form to single PHP script file :singleform.php if(!empty($_POST*“mobilesub”+)) <?php { if($_SERVER *‘REQUEST_METHOD’ ==‘POST’+) echo “Your mail id is:” . { $_POST*‘mobileno’+; if(!empty($_POST*“mailsub”+)) } { echo “Your mail id is:” . } $_POST*‘email’+; ?> } else 223 A Forms having multiple Submit Buttons:• Multiple operation can be • Single PHP script is sufficient to provided on a single form by handle all the operation providing different buttons for mentioned on the button in the form. different operation. • Based on which button is clicked • PHP script will identify the data in the form is processed buttons which is being clicked differently for the operation and will carry out the operation according to it. mentioned on the button. • Identification of the button is done by its name on the server. 224 A Forms having multiple Submit Buttons :multibutton.html <input type= “submit” name = <html> <body> “subbtn” value = “Subtract”> <form name = “arithmatic” </form> method= “POST” action =“multibutton.php” > </html> </body> <input type= “text” name=“no1” id=“no1”> <input type= “text” name=“no2” id=“no2”> <input type= “submit” name = “addbtn” value = “Add”> 225 A Forms having multiple Submit Buttons :multibutton.php <?php if($_SERVER *‘REQUEST_METHOD’ ==‘POST’+) { if(isset($_POST*“addbtn”+)) { echo “Addition of this two number is:” . ((int)$_POST*‘no1’+ + ((int)$_POST*‘no2’+); } else if(isset($_POST*“subbtn”+)) { echo “Subtraction of this two number is:” . ((int)$_POST*‘no1’+ ((int)$_POST*‘no2’+); } } ?> 226 Web Page Validation:• Use may mistakenly submit the • empty():- Ensure that text field is data through form with empty not blank it is with some data. or in wrong format. • is_numerical():- Ensure that data • PHP script must ensure that entered in a text field is a required field are complete and numerical value. submit data is in valid format. • preg_match():- Used to perform • PHP provide some inbuilt validation for entering text in the function by using this function text field, function accepts a that input data can be validated. “regular expression”. 227 A Forms having multiple Submit Buttons :validation.html <html> <body> <form method= “POST” action =“validation.php” > Name: <input type= “text” name=“name” id=“name”/><br> Mobile No: <input type= “text” name=“mobileno” id=“mobileno”><br> Email ID:<input type= “text” name = “email” value = “email”><br> <input type= “submit” name = “submit” value = “Submit”> </form> </html> </body> 228 Posting all form to single PHP script file :validation.php if(!is_numeric($_POST*“mobileno <?php ”+)) if($_SERVER { *‘REQUEST_METHOD’ ==‘POST’+) { echo “Enter Valid Mobile if(empty($_POST*“name”+)) Number</br>”; { } echo “Name Can’t be $pattern= "^[_a-z0-9-]+(\.[_a-z0Blank</br>”; 9-]+)*@[a-z0-9-]+(\.[a-z0-9} ]+)*(\.[a-z]{2,3})$^”; 229 Posting all form to single PHP script file :validation.php Output:- if(!preg_match($pattern,$_P Name Can’t be Blank OST*“email”+)) Enter Valid Mobile Number { echo “Enter Valid email Enter Valid email ID. ID.</br>”; } } ?> 230 Supergloabals:• The Superglobals array allow you to specify where the input data come from and that is what method was used. • Superglobals are predefine variable in PHP which mean that they are accessible, regardless of scope. • You can access them from any function, class or file. • $_SERVER • $_REQUEST • $_GET • $_POST • $_COOKIE • $_SESSION • $_FILE • $GLOABALS • $_PHP_SELF • $_ENV • $argc • $agrv 231 Cookies:• PHP cookie is a small piece of information which is stored at client browser. It is used to recognize the user. • Cookie is created at server side and saved to client browser. Each time when client sends request to the server, cookie is embedded with request. Such way, cookie can be received at the server side. • In short, cookie can be created, sent and received at server end. • There are three steps involved in identifying returning users − • Server script sends a set of cookies to the browser. For example name, age, or identification number etc. • Browser stores this information on local machine for future use. • When next time browser sends any request to web server then it sends those cookies information to the server and server uses that information to identify the user. 232 Cookies :- 233 Attribute of Cookies:• name:- This sets the name of the • Expiry − This specify a future time cookie and is stored in an in seconds since 00:00:00 GMT on environment variable called 1st Jan 2020. After this time cookie HTTP_COOKIE_VARS. This variable will become inaccessible. If this parameter is not set then cookie is used while accessing cookies. • Value − This sets the value of the will automatically expire when the named variable and is the content Web Browser is closed. • Domain − This can be used to that you actually want to store. • Path − This specifies the specify the domain name in very directories for which the cookie is large domains and must contain at valid. A single forward slash least two periods to be valid. All character permits the cookie to be cookies are only valid for the host and domain which created them. valid for all directories. 234 Attribute of Cookies:• Security − This can be set to 1 to specify that the cookie should only be sent by secure transmission using HTTPS otherwise set to 0 which mean cookie can be sent by regular HTTP. • Create Cookies With PHP:• PHP provide inbuilt function setcookie(), that can send appropriate header to create the cookie on the browser. • While creating the cookie, we have to pass require arguments with it. • Only name argument must but it is better to pass value, expire and path to avoid any ambiguity. • Syntax:setcookie(name, value, expire, path, domain, secure, httponly); 235 Create Cookies :<html><body> • <?php $cookie_name = "user"; $cookie_value = “GPG"; • setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); if(!isset($_COOKIE[$cookie_name ])) { echo "Cookie named '" . $cookie_name . "' is not set!"; } else { echo "Cookie '" . $cookie_name . "' is set!<br>"; echo "Value is: " . $_COOKIE[$cookie_name]; } ?> </body> </html> 236 Create Cookies :<?php setcookie("name", “Ganesh", time()+3600, "/","", 0); setcookie("age", "36", time()+3600, "/", "", 0); ?> <html> <head> <title>Setting Cookies </title> </head> <body> <?php echo "Set Cookies"?> </body> </html> 237 Accessing Cookies with PHP:<html><head> <title>Accessing Cookies with PHP</title> </head> <body> <?php echo $_COOKIE["name"]. "<br />"; echo $HTTP_COOKIE_VARS["name"]. "<br />"; echo $_COOKIE["age"] . "<br />"; echo $HTTP_COOKIE_VARS["age"] . "<br />"; ?> </body> </html> 238 Accessing Cookies with PHP:• You can use isset() function to check if a cookie is set or not. <html><head> <title>Accessing Cookies with PHP</title> </head> <body> <?php if(isset($_COOKIE["name"])) { echo "Welcome " . $_COOKIE["name"] . "<br />"; } else { echo "Sorry... Not recognized" . "<br />"; } ?> </body> </html> 239 Deleting Cookie with PHP:<?php setcookie( "name", "", time()60, "/","", 0); setcookie( "age", "", time()- 60, "/","", 0); ?> <html> <head> <title>Deleting Cookies with PHP</title></head> <body> <?php echo "Deleted Cookies" ?> </body> </html 240 Session:• Cookies are used to store user • Session data is stored on the data on the client’s browser is server side and each session is not the most secure way of assigned with a unique session storing data, it can be easily ID for that session data hacked. • As session data is store on the • Cookies data for a website is server there is no need to send uploaded every time a request is any data along with the URL for sent for specify URL on the each request to server. server. • More data can be store in • Both this problem can be solved session as compared with cookie by using session data to store because location for storing data is Server. user data. 241 Session :- 242 Session:• A session creates a file in a temporary directory on the server where registered session variables and their values are stored. • This data will be available to all pages on the site during that visit. • The location of the temporary file is determined by a setting in the php.ini file called session.save_path. • Before using any session variable make sure you have setup this path. • PHP session is used to store and pass information from one page to another temporarily. • PHP session technology widely used in shopping website. • Where we need to store and pass cart information. 243 Start Session:• It is very easy to create and start • With the data store in that session. session in PHP. • PHP session can be started by • Syntax:calling session_start() function. • If it is new session then <?php session_start() function will generate a unique SID for the session_start(); ?> session. • Else a same function will be used to access existing along 244 Set Session Variables:• Session variable can be set with a help of a PHP global variable: $_SESSION. • Data in the session is stored in the form of keys and value pair. • We can store any type of data on the server, which include array and object. • Suppose, We want to store username in the session. • So it can be assessed whenever it is required throughout the session • Syntax:<?php session_start(); $_SEESION*“userneme”+= “GPG”; ?> 245 Set Session Variables :<?php session_start(); // Start the session echo "Session variables are set."; ?> ?> </body> <html> </html> <body> <?php Output:// Set session variables Session variables are set. $_SESSION*“Name"+ = “GPG"; $_SESSION*“Address"+ = “Gondia"; 246 Get Session Variables:• Session variable can be get with a help of a PHP global variable: $_SESSION. • While accessing the data using $_SESSION variable we have to mentioned key in the $_SESSION variable. • Suppose, We want retrieve the data stored in session variable. • Syntax:<?php session_start(); echo “Userneme:-” $_SEESION*“userneme”+; ?> 247 Get Session Variables :<?php session_start(); // Start the session ?> <html> <body> <?php // Get session variables echo “User Name:- ” . $_SESSION*“Name"+. “.<br>”; echo “Address:- ” . $_SESSION*“Address"+. “.”; </body> </html> Output:User Name:- GPG Address:- Gondia. 248 Session_register():session_is_registered() • The session_register() register • The one or more global variables function can also be used to make sure the variable exists with the current session • session_register() takes two before attempting to read the arguments, the string value. representing the variable name • Syntax:and the value to be assigned to the variable <?php • Session variables are accessed by using the variable name as session_register(‘username’, the index key into the ‘GPG’); ?> $_SESSION array. 249 Session_register():<?php session_start(); // Start the session session_register(‘username’, ‘GPG’); function session_register($key, $value) { $_SESSION[$key] = $value; echo “Session is created and User registration of “.$value.” is completed</br>”; } function session_is_registered($keyname) { echo “Checking Session exist or not</br>”; if(isset($_SESSION[$keyname])) { echo “session exist<br/>; return true; } 250 Session_register():else { echo “session dose not exist<br/>”; return false; } } ?> • Output:Session is created and User registration of GPG is completed 251 Sending E-mail:• PHP use Simple Mail Transmission Protocol (SMTP) to send mail. • To send e-mail using PHP we must configure the php.ini with the details of how to sends email. • PHP Mail:• PHP mail is an inbuilt PHP function which is used to send emails from PHP scripts. • It is cost effective way of notifying users of important events. • It can also be used to send email, to your newsletter subscriber, password reset link to user, activation link etc. • Syntax:mail( to, subject, message, header, parameters) 252 Sending E-mail:<html><head> <title>Sending email using PHP</title> </head> <body> <?php $to = "xyz@somedomain.com"; $subject = "This is PHP mail"; $message = "<b>This is HTML message.</b>"; $message .= "<h1>This is headline.</h1>"; $header = "From:abc@somedomain.com \r\n"; $header .= "Cc:afgh@somedomain.com \r\n"; $header .= "MIME-Version: 1.0\r\n"; 253 Sending E-mail:$header .= "Content-type: text/html\r\n"; $retval = mail ($to, $subject, $message, $header); if( $retval == true ) { echo "Message sent successfully."; } else { echo "Message could not be sent..."; } ?> </body> </html> 254 Happy Learning Thank You ! 255 Unit- 05 Database Operation 256 MySQL Introduction:• MySQL is an open-source relational database management system (RDBMS). It is the most popular database system used with PHP. MySQL is developed, distributed, and supported by Oracle Corporation. • MySQL is named after co-founder Monty Widenius's daughter: My • SQL the abbreviation for Structured Query Language. • MySQL is one of the best RDBMS being used for developing various web based software application. • MySQL is main component of web application like XAMPP, LAMP and WAMP. • MySQL is used by many popular websites which include Facebook, Flickr, Mediawiki, Twitter and YouTube • It is designed to allow simple request from a database via command. 257 MySQL Introduction:• MySQL database stores data into • +----+------------+-----------+----------------------+ tables like other relational | id | first_name | last_name | email| +----+------------+-----------+----------------------+ database. A table is a collection of | 1 | Ram | Maharaj | rammaharaj@mail.com | related data, and it is divided into | 2 | Laxma | Maharaj | laxmanmaharaj@mail.com rows and columns • The data in a MySQL database are • Each row in a table represents a stored in tables which consists of data record that are inherently connected to each other such as columns and rows. information related to a particular • MySQL operate using client/server person, whereas each column architecture in which the server represents a specific field such as run on the machine the database id, first_name, last_name, email, and client connect to the server etc over network. 258 Feature of MySQL :• Easy to use:• Free to download:• Ease of Management:• Client/Server Architecture:• Compatible on many OS:• Robust Transaction support:• Compressive application Development:• High Performance:- • No License Fee:• Security:• High Availability:• Scalability:• High Flexibility:• High Productivity:• Speed:- 259 Data type in MySQL :• Data type is specifies a particular type of data, like integer, floating point, Boolean etc. • MySQL support a number if SQL standard data types in various category. • It use many different data type broken into mainly 3 category:numeric, date ant time and string type. • We can determine the data type in MySQL with the following characteristics: • The type of values (fixed or variable) it represents. • The storage space it takes is based on whether the values are a fixedlength or variable length. • Its values can be indexed or not. • How MySQL performs a comparison of values of a particular data type. 260 String Data Types:- 261 Numeric Data Types:- 262 Date and Time Types:- 263 Binary Large Object Data Types (BLOB):- 264 Accessing MySQL via the Command Line:the command-line • There are three main way can • Starting interface:interact with MySQL: • After installing XAMPP, you will be 1. Command Line able to access the MySQL 2. Web interface such as executable from given directory phpMyAdmin C:\xampp\mysql\bin 3. Programming language like • MySQL default user will be root and will not have had password PHP set. • By using CMD select->Run, enter CMD into the run box. 265 Accessing MySQL via the Command Line:• In window command prompt enter below command C:\xampp\mysql\bin\mysql -u root • You can check everything is working as it should be. SHOW databases; For Linux:mysql -u root -p • MySQL Commands:• SQL command and Keyword are case-insensitive. • It is recommended to use uppercase for all database operation. • Table name are case-sensitive on Linux, case insensitive on window. • It is recommended to use lowercase for tables. 266 MySQL Commands:- 267 Database Related Command :• Creating Database:• A database is a collection of data. MySQL allows us to store and retrieve the data from database in a efficient way. • Syntax:CREATE DATABASE <database name>; • We can use/select created database use using MySQL USE Command:- USE <database name>; Example:MariDB [none]> CREATE DATABASE GPG; Query OK, 1 row affected(0.01 sec) MariDB [none]> USE GPG; Database Changed MariDB [GPG]> 268 Database Related Command :• Table Related Command:• Drop Database:• We can drop/delete/remove a • In order to create a table we MySQL database easily with the have to choose an appropriate MySQL DROP DATABASE database to operation using USE command. command. • It delete all the table of the • Table can created using CREATE database along with database TABLE command into the database and by mentioning the permanently. field with its type. • Syntax:DROP DATABASE database name; 269 Creating a Table:• In order to create a table we have to choose an appropriate database for operation using USE command. • Table can be created using CREATE TABLE command into the database and by mentioning the field with its type. • Syntax:CREATE TABLE [IF NOT EXISTS] <table name> (<field name> data type [optional parameter]0 ENGINE = storage engine; • Example:• CREATE TABLE students(rolln VARCHAR(16), name VARCHAR(120), percent float(5,2)) ENGINE MyISAM; 270 Table Related Command :• Describe Command:• For checking whether your new table has been created we can use DESCRIBE command. • Syntax:DESCRIBE<table name>; • Adding Data to a Table:INSERT INTO <table name> (colomn_1, column_2..) VALUES (value_1, value_2..); • Example:INSERT INTO student(rollno, name, percent) VALUES (1, ‘Ram’, 75.4); • Deleting Table:• Syntax:DROP Table<table name>; 271 MySQL storage Engine:• A storage engine is a software module that a database management system use to create, read, update data from a database. • There are two types of storage engine in MySQL:- transection and non- transection. • List of storage engines MySQL supported storage engines: InnoDB MyISAM Memory CSV Merge Archive Federated Blackhole Example 272 Connecting to MySQL Database:• Creating a Login files:• When a web site is developed with PHP it contains multiple program file files that will require access to MySQL and will thus need the login and password details. • It is good to create a single file to store login credential and then include that file whenever it is needed. • Example:- login.php <? $hn = ‘localhost’; $db = ‘college’; $un = ‘root’; $pw = ‘’; ?> 273 Connecting to MySQL Database:• All login credentials that are used to log MySQL server are <? saved in the file login.php, we can include it in any PHP file to require_once ‘login.php’; access the database by using $conn = new mysql($hn, require_once statement. $un, $pw, $db); • It will generate a fatal error if if($conn->connect_error) the file is not found. die ($conn->connect_error); ?> 274 Connecting to MySQL Database:• Building and Executing a Query: Example:<?php require_once ‘login.php’; <?php $conn = new mysql($hn, $un, $query = “SELECT * FROM $pw, $db); if($conn->connect_error) die STUDENT”; ($conn->connect_error); $result = $conn->query($query); $query = “SELECT * FROM if(!$result) die($conn->error) STUDENT”; $result = $conn->query($query); ?> if(!$result) die($conn->error) 275 Connecting to MySQL Database:$result->data_seek($j); $row = $result->num_row; echo ‘Percentage’ .$resultfor($j=0; $j<row; ++$j) >fetch_assoc()*‘percent’+.<br/>’; { } $result->data_seek($j); $result->close(); echo ‘Roll No.: ’ .$result- $conn->close(); >fetch_assoc()*‘rollno’+.<br/>’; ?> $result->data_seek($j); echo ‘Name: ’ .$result>fetch_assoc()*‘name’+.<br/>’; 276 Connecting to MySQL Database:• Fetching a Row:• To fetch one row at a time fetch_array() method is used to fetched each row entirely at a time. • This return single row of data as an array, which is then assigned to the array $row. Example:<?php require_once ‘login.php’; $conn = new mysql($hn, $un, $pw, $db); if($conn->connect_error) die ($conn->connect_error); $query = “SELECT * FROM STUDENT”; $result = $conn->query($query); if(!$result) die($conn->error) 277 Connecting to MySQL Database:echo ‘Name: ’ .$row*‘name’+. ‘br/>’; $row = $result->num_row; echo ‘Percentage: ’ for($j=0; $j<row; ++$j) .$row*‘percent’+. ‘br/>’; { } $result->data_seek($j); $result->close(); $row = $result$conn->close(); >fetch_array(MYSQLI_ASSOC); echo ‘Roll No.: ’ .$row*‘rollno’+. ?> ‘br/>’; 278 Connecting to MySQL Database:• Fetching a Row:- • Closing a Connection:- • MySQL_NUM:- • Sresult->close(); • MSYQL_ASSOC:- • $result->close(); • MySQL_BOTH:- 279 Connecting to MySQL Database:• myslqli_fetch_object:<?php $conn=mysqli_connect(“localhos t”, “root”, “college”); if(mysqli_connect_error()) { echo “Failed to connect MySQL”; } $sql= “SELECT rollno,nane, percent FROM student”; $result= mysqli_query($conn, $sql); while($row= myslqli_fetch_object($result)); { echo $row->rollno; echo $row->name; echo $row->percent; } 280 Thank You! 281