PHP Book
PHP Book
SYLLABUS
Web Based Application Development with PHP (22619)
Teaching Examination Scheme
Scheme
la. Write simple PHP program | 1.1 History and Advantages of PHP, Syntax of
to solve the given PHP.
Unit - 1 <Speau 12 Variables, Data types, Expressions and
Expressions and lb. Use relevant decision operators, constants.
control making control Soe to} 13 Decision making Control statements - if,
statements SOLVES GIVEN PraUiem: if-else, nested if, switch, break and
in PHP lc. Solve the given iterative continue statement.
problem . relevant loop 14 Loop control structures - while, do - while,
Statement. for and foreach.
2a. Manipulate the given type | 2.1 Creating and Manipulating Array, Types of
of arrays to get the desired Arrays - Indexed, Associative and
result. Multi-dimensional arrays.
2b. Apply implode, explode 2.2 Extracting data from arrays, implode,
Unit - I functions on the given array. explode, and array flip.
Arrays, 2c. Apply the given string 2.3 Traversing Arrays.
Functions and functions on the character] 24 Function and its types - User defined
Graphics array. function, Variable function and
2d. Scale the given image using Anoflymenic finction,
graphics concepts/functions. | 2.5 Operations on String and __ String
functions : str_word_count(),strlen(),str
rev(), strpos(), str_replace(), ucwords(),
strtoupper(), strtolower(), stremp().
2.6 Basic Graphics Concepts, Creating Images,
Images with text, Scaling Images, Creation
of PDF document.
(iv)
3a. Write constructor and 3.1 Creating Classes and Objects
cesirantor functions ape) the 3.2. Constructor and Destructor
Unit - HI given problem in PHP.
.
Apply Object | 3b. Implement
. .
inheritance to
3.3. Inheritance, . Overloading and Overriding,
i Cloning Object.
Oriented extend the given base class. : oo
Concepts in PHP | 3. Use overloading / overriding 3.4 Introspection, Serialization
4a. Use the relevant form | 4.1 Creating a webpage using GUI
controls to get user's input. Components, Browser Role-GET and
4b. Design web pages using
multiple Forms for the given
POST methods, Server Role
problem. 4.2. Form controls: text box, text area, radio
3 ae ge button, check box, list, buttons.
Apply the given validation
Unit- IV rules on form. 4.3 Working with multiple forms :
valiCreating and
stint torts 4d. Set/ .
modity/ aes .
cookies 2
- A web page aya:
having many forms.6
using cookies attributes. - A form having multiple submit buttons.
de. Manage the given session] 4.4 Web page validation.
using session variables. . . .
4.5 Cookies-Use of cookies, Attributes of
cookies, create cookies, modify cookies
value, and delete cookies.
4.6 Session- Use of session, Start session, get
session variables, destroy session.
4.7 Sending E-mail.
5a. Create database for the | 5.1 Introduction to MySQL - Create a database.
St problem using PHP 5.2. Connecting to a MySQL database : MySQL
BERPE database server from PHP.
Unit - V 5b. Anes data oT: a 5.3. Database Operations Insert data,
Database atabase Using Script. Retrieving the Query result.
Operations 2c Apply the specified update 5.4 Update and delete operations on table
operation in database record data
using PHP script. ,
5d. Delete the given record from
the database using PHP
script.
”
TABLE OF CONTENTS
2.6.1 Creating Images .........
0000 e eee 2-19
4.3.2 A Form Having Multiple Submit Buttons. 4 - 23 5.4 Update and Delete Operations on Table Data . 5 - 10
44 “WebPage Validation ..:. 5 «sien:
s cswoan sve 4-24 §.5 Programming Examples using PHP-MYSQL . 5 - 11
History
PHP was developed in 1994 by Apache group.
PHP stands for PHP : Hypertext Preprocessor.
PHP is a server-side scripting language. It is mainly used for form handling and database access.
It is free to download and use.
Advantages
. PHP code can be embedded in the HTML document. The code must be enclosed within <?php and >
If the PHP script is stored in some another file and if it needs to be referred then include construct is used.
For instance:
Include(“myfile.htm1")
a-t)
Web Based Application Development with PHP 1-2 Expressions and Control Statements in PHP
xor
PHP Document[FirstCode.php]
<html>
<head>
<title> PHP Demo </title>
</head>
<body>
<?php
$i=10;
echo "<h3>Welcome to first PHP Document </h3>";
echo "The value of variable is = $i";
27>
</body>
</html>
Output
Step 2: Click on Download XAMPP for Windows or Linux depending upon your operating system.
Step 3: When prompted for the download, click "Save" and wait for your download to finish.
Step 4: Install the program, and click on "Run." Accept default settings by clicking Next button. Finally you will
get installation completion message.
Step 5: On your drive, the XAMPP folder will be created. Click on xampp_start file, this will enable to start
Apache, MySQL and Tomcat start.
Step 6: The control panel for XAMPP will look like this,
Step 7: Write a PHP script and save it in C:\XAMPP\htdocs\php-examples folder by giving the filename and
extension as .php
Step 8: Open the web browser and type http://localhost/php-examples/yourfilename.php
Step 9: The web application will be executed within your web browser.
For example
PHP Script[stringDemo1.php]
<?php
Output
Le Se
I like PHP
Review Questions
1. What is PHP ? Give general syntax of PHP.
2. Give the advantages of PHP.
Variables
e Variables are the entities that are used for storing the values.
¢ PHP isa dynamically typed language. That is PHP has no type declaration.
e The value can be assigned to the variable in following manner -
$variable_name=value
e If the value is not assigned to the variable then by default the value is NULL. The unsigned variables are
called unbound variable.
* If the unbound variable is used in the expression then its NULL value is converted to the value 0.
¢ Following are some rules that must be followed while using the variables -
1. | The variable must start with letter or underscore _, but it should not begin with a number.
It consists of alphanumeric characters or underscore.
3. There should not be space in the name of the variable.
4. While assigning the values to the variable the variable must start with the $. For example
$marks=100;
Data Types
There are four scalar types that are used in PHP and those are Integer, Boolean, Double and String. Let us
discuss each one by one.
Integer Type
e For displaying the integer value the Integer type is used.
¢ Itis similar to the long data type in C.
e = The size is 32 bit.
Double Type
e For displaying the real values the double data type is used.
¢ It includes the numbers with decimal point, exponentiation or both. The exponent can be represented by E
or e followed by integer literal.
e It is not compulsory to have digits before and after the decimal point. For instance .123 or 123. is allowed
in PHP.
String Type
e There is no character data type in PHP. If the character has to be represented then it is represented using
the string type itself; but in this case the string is considered to be of length 1.
e The string literals can be defined using either single or double quotes.
e In single quotes the escape sequence or the values of the literals can not be recognized by PHP but in
double quotes the escape sequences can be recognized. For example
‘The total marks are= $marks'
Boolean Type
« There are only two types of values that can be defined by the Boolean type and those are TRUE and
FALSE.
e If Boolean values are used in context of integer type variable then TRUE will be interpreted as 1 and
FALSE will be interpreted as 0.
. If Boolean values are used in context of double type then the FALSE will be interpreted as 0.0,
Constants
* Constant is an identifier that contains some value.
* Once the constant value is assigned to this identifier it does not get changed.
e Constant is case sensitive by default.
e Generally the constant identifiers are specified in upper case.
e The valid constant name must start with letter or underscore. It may then followed by the digits.
e Using define function we can assign value to the constant. The first parameter in define function is the
name of the constant and the second parameter is the value which is to be assigned.
For example :
ConstDemo.php
<?php
Operators
PHP supports the collection of arithmetic operators such as +,-,/,*,%,++ and — with their usual meaning.
While using the arithmetic operators if both the operands are integer then the result will be integer itself.
If either of the two operands is double then the result will be double.
PHP has large number of predefined functions. Some of these functions are enlisted in the following
table -
Function Purpose
floor The largest integer less than or equal to the parameter is returned
For example floor(4.9) will return 4,
ceil The smallest integer less than or equal to the parameter is returned
For example ceil(4.9) will return 5,
2. Relational Operators
3. Boolean Operators
¢ The Boolean operators are
Operator Meaning
Il
xor The XOR operation will be performed.
5. Bitwise Operators
eS Xor $x “$y Bits that are set in $x or $y but not both are set.
~ Not ~$x Bits that are set in $x are not set, and vice versa.
<< Shift left $x<<$y Shift the bits of $x Sy steps to the left. Another purpose of this operator can
also be “multiply by two”.
>> Shift right $x>>$y Shift the bits of $x Sy steps to the right. Another purpose of this operator
can also be “divide by two”.
A bit (Binary digit) is the basic unit of information stored in the computing system that exists in two possible
states, represented as ON or OFF. In a computer system, the ON state considered as 1 and OFF state
considered as 0.
The truth table for bitwise operations is as given below.
a b alb a&b ab
0 0 0 0 0
0 1 ir 0 at
1 0 1 0 ls
1 1 1 1 0
For example
Consider $a=40 and $b=80. Binary form of these values is given below.
$a = 00101000
$b= 01010000
akb 00000000 0
a%b 01111000
a<<1 01010000
a>>l 00010100 20
Programming Example
<?php
$a = 40;
$b = 80;
$AND_opr = ($a & $b);
SOR_opr = ($a | $b);
$NOT_opr = (~$a);
$XOR_opr = ($a ~ $b);
echo "<br/>AND Operation: ".$AND_opr;
echo "<br/>OR Operation: ".$OR_opr;
echo "<br/>NOT Operation: ".$NOT_opr;
echo "<br/>XKOR Operation: ".$KOR_opr;
echo "<br/> Left shift operation: ".($a< <1);
echo "<br/> Right shift operation: ".($a>>1);
?>
Output
@ localhost:8089/php-examples) X +
€) > @ VD @ ocathost:8089/php
AND Operation: 0
OR Operation: 120
NOT Operation: -41
XOR Operation: 120
Left shift operation: 80
Right shift operation: 20
6. Assignment Operator
The assignment operator is used to assign the values to variables. Following is a list of assignment operators.
+ a+=5 meansa=a+5
= a-=5 meansa=a-5
Similarly *=, /= operators are used for performing arithmetic multiplication and division operation.
Expressions
e Expressions are most important building blocks in PHP.
« Expression can be defined as an entity that has some value.
¢ For example
$a=100;
is an expression
¢ The complex form of expression is a function. For example
?>php
function fun()
{
return 1;
}
$val=fun();
The numeric value can also be displayed using the print. For example -
print(100);
+ PHP also makes use of the printf function used in C. For example
printf(The student %d has %f marks” $roll_no,$marks);
e Following is a simple PHP document which makes use of the statements for displaying the output.
PHP Document[OutputDemo.php]
<html>
<head>
<title> Output Demo</title>
</head>
<body>
<?php
print "<h2>Welcome to my Website </h2>";
print "<hr/>";
$roll_no=1;
$name="AAA";
print{("<b>The roll number: %d</b>",$roll_no); Output
print “<br/><b>"; ~ =
printf("The name: %s" $name); @ Output Demo - Mozilla Firefox | © fee)
* The echo statement can display the text and variable value as follows —
$a=10;
echo “a = “. $a;
The echo can output one or more strings. Print can only output one string.
Review Questions
1. List and explain various data types in PHP.
2. Explain different types of operators used in PHP.
3 Explain the term expression with suitable example.
1. The if Statement
Syntax
if(expression)
{
statement inside;
statement outside;
Example
<?php
$a = 80;
$b = 40;
if(S$a>$b)
echo “a is greater than b*;
?>
Syntax
if(expression)
{
Statements;
}
else
{
Statements;
}
Example
<?php
$a = 80;
$b = 40;
if(Sa>$b)
echo a is greater than b";
else
echo "b is greater than a";
>
Syntax
if(condition1){
// Code to be executed if condition! is true
} elseif(condition2){
// Code to be executed if the condition! is false and condition2 is true
} else{
// Code to be executed if both condition1 and condition2 are false
}
Example
<?php
$num = 100;
if($num> 100)
echo "Number is greater than 100°;
elseif($num<100)
echo "Number is less than 100°;
else
echo "Number is equal to 100";
>
Ex. 1.3.1 : Write a PHP program to find the largest number among three numbers.
Sol. :
<html>
<head>
<title>Selection Demo</title>
</head>
<body>
<?php
print "<h2>Selection Statement </h2>";
$a=10;
$b=20;
$c=30;
if($a>$b)
if($a>$c)
print "<b> <I>a is the largest number </I></b>";
else
print "<b> <I> c is the largest number</I> </b>";
else
if($b>$c)
print “<b> <I>b is the largest number</I> </b>";
else
print "<b> <I>c is the largest number</I> </b>";
I>
</body>
</html>
Selection Statement
cis the largest number
default:
/{ Code to be executed if n is different from all labels
}
Example
<?php
$today = getdate();
switch($today['weekday'])
{
case "Monday':print "Today is Monday";
break;
break;
case "Friday":print "Today is Friday";
break;
case "Saturday":print "Today is Saturday";
break;
case "Sunday':print "Today is Sunday ";
break;
default: print "Invalid input";
}
?>
Output
Today is Friday
Syntax
break
Enter loop
Condition
for loop
Exit loop
For example
$i =0;
for ($i = O;$i <= 7;$1+ +)
{
if ($i==3)
{
break;
echo $i;
Syntax
Continue
Enter loop
Condition
Exit loop
Remaining
statements
For example
$i =0;
for ($i = 0;$i <= 7;$i+ +)
{
if ($i==3)
A
continue;
}
echo $i;
echo "<br/>";
}
Output
0
1
2
4
TECHNICAL PUBLICATIONS” - An up thrust for knowledge
Web Based Application Development with PHP 1-16 Expressions and Control Statements in PHP
5
6
7
Difference between break and continue
2. It causes early termination of the entire loop. It causes early execution of the next iteration.
}
Example
<?php
$i=1;
print "The numbers are ...";
print "<br/>";
while($i<=10)
{
print $i;
print "<br/>";
$i++;
}
?> Output
Fea
Ela Edit Yiew “Hietory_Rookmes “Tools Hep
| Ei nttp://ocathost/p..ples/.oopDemol.php | +
igen
¢ lier
> E)_ mt hittpecathost’phy eam Be oP
‘The numbers
are ...
1
2
3
4
5
6
3
8
9
10
Introduction to Arrays
« Arrays is a collection of similar type of elements, but in PHP you can have the elements of mixed
type together in single array.
¢ Ineach PHP, each element has two parts key and value.
¢ The key represents the index at which the value of the element can be stored.
¢ The keys are positive integers that are in ascending order.
[24.4] Creating and Manipulating Arrays
Syntax
$array_name=array(value)
Example : Following PHP script shows how to create an array in PHP
ArrayCreateDemo.php
<!DOCTYPE html>
<html>
<body>
<?php
$fruits = array("Mango", "Apple", "Banana","Grapes');
echo $fruits[0] . ",". $fruits[1] .",". $fruits[2] . ",". $fruits[3];
?>
</body>
</html>
Output
@ Mozilla Firefox = o
€ @ GO @® localhost:8089/php -~ UR »
Mango.Apple.Banana.Grapes
(2-1)
Web Based Application Development with PHP 2-2 Arrays, Functions and Graphics
Program Explanation :
In above program,
(1) We have created an array named fruits using array() construct
(2) In the echo statement we are displaying each element of the array with the help of array index such as
fruits[0],fruits[1],... and so on.
PHP Document
<!DOCTYPE html>
<html>
<body>
<?php
$Student = array("AAA","BBB',"CCC","DDD","EEE");
echo "<br/> Original Array<br/>";
print_r($Student);
echo "“<br/>Deleting element at index 2<br/>";
unset($Student[2]);
print_r($Student);
echo "<br/> Adjusting gap<br/>";
$Student= array_values( $Student);
print_r($Student);
?>
</body>
</html>
Output
Original Array
Array ( [0] => AAA [1] => BBB [2] => CCC [3] => DDD [4] => EEE )
Deleting element at index 2
Asray ( [0] => AAA [1] => BBB [3] => DDD [4] => EEE)
Adjusting gap
Array ( [0] => AAA [1] => BBB [2] => DDD [3] => EEE )
Script Explanation :
1. In above script we have used unset function to create a gap at index 2
2. Later on we have used array_values() to adjust this gap by subsequent element.
3. Using the print_r function the array can be displayed on the browser window.
PHP Document
<!DOCTYPE html>
<html>
<body>
<?php
$Student = array(1=>"AAA",2=>"BBB');
echo "<br/>Original Array <br/>";
print_r($Student);
if(isset($Student([0]))
echo "<br/>There is no value set at index 0<br/>";
if(isset($Student[1]))
echo "The value present at index 1 is: "$Student/1];
2>
</body>
</html>
7
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Web Based Application Development with PHP 2-4 Arrays, Functions and Graphics
Types of Arrays
_ Oo x
[9 PHP Indexed Arrays x +
Array( [0] => AAA [1] => BBB [2] => CCC )
$mylist(5] = 100;
2. Associated array : Associated arrays are the arrays with named keys. It is a kind of array with name
and value pair. For example
<html>
<head>
<title >PHP Associative Array</title>
</head>
<body>
<?php
$city['AAA"] = "Pune";
$city["BBB"] = "Mumbai;
$city["CCC"] = "Chennai";
ani oO x
[E) PHP Associative Array x +
3. Multidimensional Arrays
¢ PHP support for multidimensional arrays.
+ Wecan store the elements in two dimensional array as
$Student = array
(
array(10,"AAA"),
array(20,"BBB"),
array(30,"CCC"),
‘
+ The complete PHP program in which the multidimensional array is created and accessed is as
follows-
PHP Document
<!DOCTYPE html>
<html>
<body>
<?php
$Student = array
(
array(10,"AAA"),
array(20,"BBB"),
array(30,"CCC"),
‘
echo "The elements in Two dimensional array...<br/>";
for ($row = 0; $row < 3; $row++) {
for ($col = 0; $col < 2; $col++) {
echo " ".$Student[$row] [$col];
}
echo "<br/>";
}
?>
</body>
</html>
ig
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Web Based Application Development with PHP 2-6 Arrays, Functions and Graphics
Output
€)39 24 DOloa ow YD =
Review Questions
1. What is array ? How to create and manipulate arrays ?
2. Explain various types of arrays in PHP.
[22] Extracting Data from Arrays, Implode, Explode and Flip Functions
<?php
$arr = array("a" => "Pune","b" => "Mumbai",
extract($arr);
echo "\$a = $a; \$b = $b; \$c = $c";
>
</body>
</html>
7
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Web Based Application Development with PHP 2-7 Arrays, Functions and Graphics
(E) localhost:8089/php-examples) X
implodeDemo.php
<!DOCTYPE html>
<html>
<body>
<?php
$arr[0] = "Red";
$arr[1] = "Blue";
$arr[2] = "Green";
$arr[3] = "Yellow";
$text = implode(",",$arr);
echo $text;
?>
</body>
</html>
Output
©} locathost:8089/php-examples’ X
@ ODO @ bocalhost:8089/php-e a) | »
(©) >
Red.Blue.Green, Yellow
7
TECHNICAL PUBLICATIONS. - An up thrust for knowledge
Web Based Application Development with PHP 2-8 Arrays, Functions and Graphics
<?php
$str="I Love my Country";
$arr=explode(" “,$str);
print_r($arr);
>
</body>
</html>
Output
[E) localhost:8089/php-examples) X +
Array
( [0] => I [1]
= Love [2]
=> my [3] => Country)
Example Program
<!DOCTYPE html>
<html>
<body>
7
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Web Based Application Development with PHP 2-9 Arrays, Functions and Graphics
<?php
$arr=array("Red"=> 10,"Green"= > 20,"Blue"= >30,"Black"= >40);
$result=array_flip($arr);
print_r($result);
2>
</body>
</html>
Output
[E) locathost:8089/php-examples x +
Array ( [10] => Red [20] => Green [30] => Blue [40] => Black)
Review Question
1. Explain extract, implode, explode and flip function in arrays.
print "<br/>";
$myval=next($mylist);
print("The next value of the array is <b>$myval</b>");
?>
Output
=u. tere]
[Els tocnee nena»
File Edit View History Bookmarks Toots Help
+ The foreach function is used to iterate through all the elements of the loop. The syntax of foreach
statement is as follows -
7
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Web Based Application Development with PHP 2-11 Arrays, Functions and Graphics
foreach($array as $value)
{
statements to be executed
}
e The above code can be modified and written as follows -
PHP Document[ArrayFunDemo6.php]
<?php
$mylist = array("Hello", "PHP","You',"Are","Wonderfull!!!");
foreach($mylist as $value)
{
print("The current value of the array is <b>$value</b>");
print "<br/>";
}
?>
The output will be the same as above.
Review Question
1. How to traverse an array in PHP ?
Functions
Defining Function
* The syntax of the function definition is as follows -
function name_of_function(parameter list)
{
statements to be executed in function
wad
¢ The function gets executed only after the call to that function. The call to the function can be from
anywhere in the PHP code.For example -
PHP Document[FunDemo1.php]
<?php
function myfun()
{
print "<i>This statement is in myfun()</i>";
5
print “<b>The Function Demo Program</b>";
print "<br/>";
myfun();
?>
Output
+ The return statement is used for returning some value from the function body. Following PHP scripts
shows this idea.
PHP Document[FunDemo2.php]
<?php
function Addition()
$b=20;
$c=$at+$b;
return $c;
}
print "<b>The Function Demo Program with return statement</b>";
print "<br/>";
print "10+20= ".Addition();
?>
Output
Parameters
+ The parameters that we pass to the function during the call is called the actual parameter. These
parameters are generally the expressions.
+ The parameters that we pass to the function while defining it is called the formal parameters. These
are generally the variables. It is not necessary that the number of actual parameters should match
with the number of formal parameters.
+ If there are few actual parameter and more formal parameters then the value of formal parameter is
will be some unbounded one.
+ If there are many actual parameters and few formal parameters then the excess of actual parameters
will be ignored.
+ The default parameter passing technique in PHP is pass by value. The parameter passing by value
means the values of actual parameters will be copied in the formal parameters. But the values of
formal parameters will not be copied to the actual parameters.
« Following PHP script illustrates the functions with parameters
3
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Web Based Application Development with PHP 2-13 Arrays, Functions and Graphics
PHP Document[FunDemo3.php]
<?php
function Addition($a,$b)
$c=$a+t$b;
retum $c;
b
print "<b>The Function Demo Program with parameter passing and return statement </b>";
print "<br/>";
$x= 10;
$y=20;
print "10+20= ".Addition($x,$y);
2?>
1. Add & at the beginning of the name of the formal parameter. For example -
<?php
function add_some_extra($string)
{
$string= ‘This string is replaced’;
}
$str = ‘This is a string ';
Sstr1=&$str; //adding & at the beginning of the name of formal parameter.
print "Before function call: $str<br/>";
add_some_extra($str1);
print "After function call: $str<br/>";
>
The output of the above code is one and the same it will be as follows -
Output
- Oo x
http://local..nceDemo.php X | =
Types of Functions
2. Variable Functions
¢ Variable function is a concept in which the variable name is appended with parenthesis.
e In PHP, we can create a variable to which the function is assigned and then that variable is called just
like a function.
* Note that the variable function should always be preceded by $ sign.
To understand the concept of variable function let us see one example
Suppose we have three functions namely red(), blue() and green(). These functions can be called with the
help of variable function as follows —
VariableFunDemo.php
<!DOCTYPE html>
<html>
<body>
<?php
function red()
{
echo “Roses are Red";
}
function blue()
£
echo "Sky is Blue";
function green()
3. Anonymous Function
The anonymous function is a function which is similar to regular function but the difference between
regular function and anonymous function is that the anonymous function have no name.
Syntax
function($argument1,$argument2){
//anonymous function definition
hk
There are two important rules that need to be followed while writing the anonymous function
Programming Example
AnonymousFunDemo.php
<!DOCTYPE html>
<html>
<body>
<?php
$addition=function(S$arg1,$arg2)
{
return "Addition = ".($arg1+$arg2);
ik
echo $addition(10,20);
I>
</body>
</html>
7
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Web Based Application Development with PHP 2-16 Arrays, Functions and Graphics
(2) locathost:8089/php-examples’ X
(€) > GF | O ® vocaost:3089/php-e “Owl » =
Addition
= 30
Review Questions
1. What is function ? How to pass parameters to the function ?
2. Explain variable and function with suitable example in php.
[25] Strings
¢ String is a collection of characters.
¢ InPHP the string is denoted within a double quote.
¢ Concatenation is the only one operator used in string.It is denoted by dot.
¢ Strings are treated as the array of characters. The first position of the character is indexed as 0.
¢ The sample PHP script that stores the string in a variable is as given below -
PHP Script[stringDemo1.php]
<?php
$s="I like PHP";
echo $s;
?>
Output
I like PHP
Note that the variable s is assigned with the string. The string is given in a double quote. Then using the
echo whatever string is stored in the variable s is displayed on the console.
7
TECHNICAL PUBLICATIONS. - An up thrust for knowledge
Web Based Application Development with PHP 2-17 Arrays, Functions and Graphics
Sol. : For this program we will apply various built in string manipulating functions to the string. The PHP code is
as follows :
<?php
$Str1="PHP is Fun";
$length = strlen($Str1);
echo "<b> Length:</b>The length of string: $Str1 is = $length";
echo "<br/> <b>Position: </b>The position of word Fun in the $Str1 is “.strpos($Str1,'Fun’);
$Str1="Hello";
7
TECHNICAL PUBLICATIONS.- An up thrust for knowledge
Web Based Application Development with PHP 2-18 Arrays, Functions and Graphics
$Str2="hello";
if(stremp($Str1,$Str2))
echo "<br/> <b>Comparison: </b> The two strings $Str1 and $Str2 are not equal";
else
echo "<br/> <b>Comparision: </b> The two strings $Str1 and $Str2 are equal’;
$Str1="HELLO";
echo "<br/> <b>Changing Case: </b> The string $Str1 becomes ".strtolower($Str1);
echo "<br/> <b>Reversing String: </b> The string $Str1 is reversed as ".strrev($Str1);
$Str1="Hello';
$Str2="Friend";
echo "<br/><b>Concatenating strings: </b> The string $Str1 and $Str2 are concatenated ".$Str1.$Str2;
echo "<br/><b>Replacing all instances of string: </b> The string tictactoe is now ";
echo str_replace("t","p",‘tictactoe");
$Str1="PHP is fun";
$newstring=substr_replace($Str1,"FUN",7,9);
echo "<br><b>Replacing substring: </b> $Str1 becomes $newstring";
?>
Output
= o x
http://local...ringDemo.php X — =F
Review Question
1. What is string ? Explain various operations that can be performed on strings
Creating Images
Step 2 : The next step is to send a Content-Type header to the browser with the appropriate content type
for the kind of image being created. Once that is done, we call the appropriate output function. The
ImageJPEG( ) , ImagePNG( ), and ImageWBMP{ ) functions create JPEG, PNG, and WBMP files from the
image, respectively. This can be done using following code
imagejpeg($image);
header('Content-Type: image/jpeg’);
Let us now see a simple program that creates the basic rectangular image
Programming Example
<?php
$image = imagecreate(300,200);
imagejpeg($image);
header('Content-Type: image/jpeg’);
>
Output
%@ ImageCreateDemo.php
(JPEG Image, 300 x 200 pixels)
- Mozill.. = — Qo
File Edit View History Bookmarks Tools Help
€ @ OD @® localhost -~ UN »
GIF image/gif
JPEG image/jpeg
PNG image/png
WBMP image/vnd.wap.wbmp
Where
image is the image object
color is given in Red,Green,Blue form. One can specify the color in hexadecimal form as well.
Programming Example
<?php
$image = imagecreate(300,200);
Sred = imagecolorallocate(Simage,255,0,0);
imagejpeg($image);
header('Content-Type: image/jpeg’);
2>
Output
ImageCreateDemo.php JPEG) +
ig
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Object Oriented Concepts in PHP
Properties
Properties are the data values of the class that can be defined using -> operator. For example
$s1=new Student();
$s2=new Student();
$s1->rollNo= 101;
$s2->rollNo=102;
Method
The methods defined in the class specify the functionality of the object. They define the tasks
each instance of a class can perform. For example —
PHP Document
<?php
class Student
{
/* Member variables */
var $rollNo;
var $name;
/* Member functions */
function setRollNo($r){
@G-1)
Web Based Application Development with PHP 3-2 Object Oriented Concepts in PHP
$this->rollNo = $1;
}
function getRollNo(){
echo $this->rollNo ."<br/>";
}
function setName($nm){
$this->name = $nm;
}
function getName(){
echo $this->name ." <br/>";
}
Output
$Stud1 = new Student();
$Stud2 = new Student(); & localhost X
/* Assigning values to properties*/
$Stud1->setName("AAA"); ; - wea =
$Stud2-> setName("BBB"); € © ® boca “(>| =
$Stud1->setRollNo(101);
$Stud2-> setRollNo(102); AAA
BBB
/* Reading values from properties*/ 101
$Stud1->getName(); 102
$Stud2->getName();
$Stud1->getRollNo();
$Stud2->getRollNo();
?>
Visibility
¢ Visibility is used to determine the accessibility of a class member.
¢ There are three modes of visibility and those are - 1. Public, 2. Protected and 3. Private.
¢ The public keyword means that the property or method is accessible to any code that has a reference
to the object. The public properties and method are represented using + in UML class diagram.
¢ The private keyword sets a method or variable to only be accessible from within the class. This means
that we cannot access or modify the property from outside of the class. The private properties and
method are represented using - in UML class diagram.
« The protected members are used during the inheritance. They are denoted using # in class diagram.
Review Questions
1. What is class ? Explain it with syntax and example.
2 Write a php program to illustrate creation of class and object in PHP.
3. Explain properties and methods of OOP in PHP.
4. What is visibility in PHP ?
* Inside of a class one must always use the $this syntax to reference all properties and methods
associated with this particular instance of a class.
For example —
class Student
{
<?php
class Student {
public $name;
function __construct($name) {
$this->name = $name;
t
function __destruct() {
echo "<h4>The Student record with name '{$this->name}' is removed from the database.</h4>";
}
}
$s = new Student("Ashwini');
?>
</body>
</html>
7
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Web Based Application Development with PHP 3-4 Object Oriented Concepts in PHP
Output
The Student record with name 'Ashwini' is removed from the database.
Program Explanation :
In above program,
(1) We have created a class named Student with attribute name.
(2) The constructor is defined using __construct function. When object s is created using following
statement.
$s = new Student("Ashwini");
the constructor function is called by passing name=Ashwini.
(3) At the end of PHP program, before closing it, the destructor function is called. The destructor
function is defined as __ destruct.
Review Question
1. What is constructor and destructor ? How will you use it in PHP ?
//child class
class Samsung extends Mobile {
private $model;
7
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Web Based Application Development with PHP 3-6 Object Oriented Concepts in PHP
//set property
$phone->setColor("Black");
$phone->setModel("Samsung-Galaxy");
//get property
$color = $phone->getColor();
$model = $phone->getModel();
$result=3.14*$arguments[0]*$arguments|(0];
echo "<br/>The area of circle is: "$result;
return;
}
if(count($arguments)==2) {
$result=$arguments|0]*$arguments| 1];
echo "<br/>The area of rectangle is: "$result;
return;
}
else
echo "Unknown Method";
}
$obj = new shape();
$obj->area(10);
$obj->area(10,20);
?>
</body>
</html>
Output
[) localhost:8089/php-examples x |+-
{
echo "<br/>Inside Child Class";
}
}
$obj1 = new A();
$obj2 = new B();
$obj1->fun();
$obj2->fun();
?>
</body>
</html>
(E) locathost:8089/php-examples) X|
Cloning Object
. Definition : Object cloning means creating copy of object.
» We can clone an object in two ways - first one by assignment statement and second one by using
__clone operator . This __clone is a magic method.
* If we perform $s2=$s1 then it is called shallow copy.
¢ If we perform $s2= clone $s1 then it is called deep copy.
* In shallow copy both the objects point to same reference while in deep copy separate copy of
references is created for each object.
* The concept of shallow copy and deep copy is represented by following figure.
Ly
TECHNICAL PUBLICATIONS — - An up thrust for knowledge
Web Based Application Development with PHP 3-9 Object Oriented Concepts in PHP
Following is an object cloning program that uses clone operator for copying the object.
Programming Example
<!DOCTYPE html>
<html>
<body>
<?php
class Student {
private $name;
private $rollno;
function __construct($name,$rollno) {
$this->name = $name;
$this->rollno = $rollno;
function __clone(){
echo "<h3> Copying object.....</h3>";
}
function display()
{
echo "<h4>Name: $this->name</h4>";
echo "<h4>RollNo: $this->rollno</h4>";
</body>
</html>
7
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Web Based Application Development with PHP 3-10 Object Oriented Concepts in PHP
Output
€)> @ OD @ becalhost:8089/php-e -~ Ow »
Name: Ashwini
RollINo: 101
Copying object.....
Name: Ashwini
RollNo: 101
Review Questions
1. What is inheritance ? How to achieve it in PHP ?
2. Explain method overloading and method overriding in PHP.
3. What is object cloning? How to clone the object in PHP ?
IntrospectionDemo.php
<?php
class Parent1
{
public function myfun(){
echo "<br/>******* In Parent class ********";
echo "<br/>This function is inside: ".get_class($this);
}
}
class child extends Parent1
{
public function myfun() {
%
TECHNICAL PUBLICATIONS — - An up thrust for knowledge
Web Based Application Development with PHP 3-11 Object Oriented Concepts in PHP
if(class_exists("Parent1")){
$o0bj_parent1=new Parent1();
echo "<br/> <br/>The class name is: ".get_class($obj_parent1);
$obj_parent1->myfun();
}
if(class_exists("child")){
$obj_child=new child();
echo “<br/> <br/>The class name is: ".get_class($obj_child);
$obj_child->myfun();
2>
Output
| 62) localhost:8089/php-examples) X +
Serialization()
* Serializing an object means converting it to a byte stream representation that can be stored ina file.
* This is useful for persistent data. For example, PHP sessions automatically save and restore objects.
* Serialization in PHP requires two functions namely - the serialize() and unserialize( ).
¢ Using serialize() method, resulting string is a binary representation of the object and therefore may
contain unprintable characters.
* Using unserialize() method, the string can be reconstituted back into an object.
Ly
TECHNICAL PUBLICATIONS — - An up thrust for knowledge
Web Based Application Development with PHP 3-12 Object Oriented Concepts in PHP
¢ The Serializable interface is used while performing serialization in PHP. It can be represented as
follows —
interface Serializable {
public function serialize();
public function unserialize($serialized);
}
« Programming Example :
<?php
$array|"a"]= "Archana";
$array|"b"] = "Rupali’;
$array['c"] = "Aishwarya";
$array["d"] = "Madhura";
print "<br/> <h3>Serializing the array...</h3>";
$str = serialize($array);
print $str . "\n";
print "<br/> <h3>UnSerializing the array...</h3>";
$arr = unserialize($str);
var_dump($arr);
2>
Output
/€3} localhost/php-examples/seria)
€) > @| © localhost/php-examples/serializeDemo.php Oe » =
Total number
f elements in String length of
o
sense 3s:1:"d";s:7:"Madhura";}
String element
UnSerializing the array...
Application of Serialization
Various user request of the objects can be stored in serialized form and then at the next request the object
is deserialized to reestablish previous session. Thus using serialization and unserialization the states of
the requests-responses can be maintained.
Review Questions
1. Explain the concept of introspection with suitable PHP program.
2. What is serialization ? Explain it with suitable example.
Qo00
%
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Creating and Validating Forms
Step 1: User creates a web page using form. Various form elements are placed on the form. The user can
make a request via web browser with the help of this web page.
Step 2 : The web server fulfills the request and sends back the response to the user in the same web browser.
1. Parameters remain in browser history because they are Parameters are not saved in browser history.
part of the URL.
2. GET is less secure compared to POST because data sentis | POST isa little safer than GET because the
part of the URL. So it is saved in browser history and parameters are not stored in browser history or
server logs in plaintext. in web server logs.
5. GET method should not be used when sending passwords POST method used when sending passwords or
or other sensitive information. other sensitive information.
6. Only limited amount of information is sent using GET Large amount of information is sent using
request. POST request.
(4-1)
Web Based Application Development with PHP 4-2 Creating and Validating Forms
Name: ABC
Name=ABC&Nationality=India
ss
Query String
* PHP is used for form handling. For that purpose the simple form can be designed in XHTML and the
values of the fields defined on the form can be transmitted to the PHP script using GET and POST
methods.
* For forms that are submitted via "GET" method, we can obtain the form via the $_GET array variable.
* For forms that are submitted via "POST" method, we can obtain the form via the $_POST array
variable.
* The $_GET and $_POST arrays are the most important superglobal variables in PHP since they allow
the programmer to access data sent by the client in a query string.
«It works as follows -
7
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Web Based Application Development with PHP 4-3 Creating and Validating Forms
Multiprocess setup
For installing Apache, PHP and MySQL an all in package like XAMPP/WAMPP is preferred.
Ex. 4.1.1 : Explain how can you create a web based application using XAMPP. Give all the steps required in
detail.
Sol. : XAMPP isa free distribution package that makes it easy to install Apache Web Server, MySQL,
PHP, PEAR. Here in XAMPP(The X stands for any OS) or WAMPP(the W stands for Windows OS).
Step 2: Click on Download XAMPP for Windows or Linux depending upon your operating system.
Step 3: When prompted for the download, click "Save" and wait for your download to finish.
Step 4: Install the program, and click on "Run." Accept default settings by clicking Next button. Finally you
will get installation completion message.
Step 5: On your drive, the XAMPP folder will be created. Click on xampp_start file, this will enable to start
Apache, MySQL and Tomcat start.
Step 6: The control panel for XAMPP will look like this
7
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Web Based Application Development with PHP 4-5 Creating and Validating Forms
Step 7: Write a PHP script and save it in C:\XAMPP\htdocs\php-examples folder by giving the filename
and extension as .php
Step 8 : Open the web browser and type http://localhost/php-examples/yourfilename.php
Step 9: The web application will be executed within your web browser.
For example
PHP Script[stringDemo1.php]
<?php
$s="I like PHP";
echo $s;
>
http://localhost/ph...les/stringDemol
php
¢ >
|) hittp://locathost/php-examples/stringDemol
php + | 8B - GoD}
Back — Forward
I like PHP
Review Questions
1. Explain the method of passing information via query strings.
2. What is $_GET and $_POST superglobal arrays ? Explain its working.
3. Write a short note on - Apache and PHP.
4. Explain PHP internals in brief.
%
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Web Based Application Development with PHP 4-6 Creating and Validating Forms
Form Controls
The HTML form is defined using the <form> element.
Typical component of forms are text, text area, checkboxes, radio buttons and push buttons.
HTML allows us to place these form components on the web page and send the desired information
to the destination server.
All these form contents appear in the <form> tag.
The form has an attribute action which gets executed when user clicks a button on the form.
Various attributes of form are —
Attribute Description
action It specifies the url where the form should be submitted.
Let us learn various form components with the help of simple HTML documents.
Text Box
Text is typically required to place one line text. For example if you want to enter some name then it is
always preferred to have Text field on the form.
The text field can be set using
<input type="text" size="30" name ="username” value=" ">
The input type is text and the value of this text field is “ ” That means the blank text field is
displayed initially and we can enter the text of our choice into it. There is size parameter which
allows us to enter some size of the text field.
Some other parameters or attributes can be
o maxlength that allows us to enter the text of some maximum length.
© name indicates name of the text field.
o align denotes the alignment of the text in the text field. The alignment can be left, right, bottom
and top.
Programming Example
Step 3 : Open the web browser and type the name of the HTML file created in step 1
[E) tocathost:8089/php-examples) X
Click Submit button, and you can invoke the php file. It will display following message
® localhost:8089/php-examples)
In above code, we can use $_POST instead of $_GET array.And when we use $_POST array in the PHP
script, the form method on HTML form must post. That means the form code in HTML form must be
<form action="hello.php” method="post" >
Text Area
Text field is a form component which allows us to enter single line text, what if we want to have multiple
line text ,then you must use textarea component.
Syntax
<textarea name=name_of_component rows="some_number” cols="some_number”></textarea>
Various parameters that can be set for the text area can be
7
TECHNICAL PUBLICATIONS. - An up thrust for knowledge
Web Based Application Development with PHP 4-8 Creating and Validating Forms
Step 1:
Input.html
<form action="Info.php" method="get">
Enter your Feedback<br/>
<textarea name="feedback' rows="5" cols="50"></textarea>
<br/>
<input type="submit" value="Submit"/>
</form>
Step 2:
Info.php
<?php
$data=$_GET["feedback'];
echo "Your feedback is: <br/>".$data;
2?>
Output
) locathost:8089/php-examples x |+
| Submit | v
7
TECHNICAL PUBLICATIONS. - An up thrust for knowledge
Web Based Application Development with PHP 4-9 Creating and Validating Forms
) localhost:8089/php-examples x |
dio Button
This form component is also use to indicate the selection from several choices.
Using input type=“radio” we can place radio button on the web page.
Syntax
<input type="radio" name="name" value="Value_in_number'>
Step 1:
Input.html
<for rm action="Info.php" method="get">
Please Select your favorite fruit:<br/>
<input type="radio" name="fruit" value="Mango">Mango<br/>
<input type="radio" name=“fruit" value="Banana">Banana<br/>
<input type="radio" name= "fruit" value="Grapes">Grapes <br/>
<br/>
<input type="submit" value="Submit"/>
</form>
Step 2:
Info.php
<?php
$choice=$ GETT["fruit");
if(($choice!=null))
{
echo("My favorite fruit is: ".S$choice);
7
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Web Based Application Development with PHP 4-10 Creating and Validating Forms
©) locathost:8089/php-examples) X
(©) FO Otectnestsoss OF »
Please Select your favorite
fruit:
Click Submit button and the php page will be displayed as follows —
f localhost:8089/php-examples/
Check Box
¢ It is the simplest component which is used particularly when we want to make some selection from
several options.
¢ For having the checkbox we have to specify the input type as checkbox.
* Syntax
<input type="checkbox" name="name_of_option" value="value_in_number" checked="checked">Mango<br/>
+ If we want to get the checkbox displayed as checked then set checked="checked"
« Programming Example
chkDemo.php
<form action="#" method="post">
<h3> Enter your Favorite Programming Language:</h3>
7
TECHNICAL PUBLICATIONS: - An up thrust for knowledge
Web Based Application Development with PHP 4-11 Creating and Validating Forms
O crc++
M Java
M PHP
| Submit
Java
PHP
7
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Web Based Application Development with PHP 4-12 Creating and Validating Forms
List
PHP allows us to have List on the web page so that the desired selection can be made.
The parameter select is for the List component and option parameter is for setting the values to the
options of the list.
Syntax
<select name="... ">
<option value=" ">label</option>
<option value: “">Jabel</option>
</select>
ListDemo.php
<form action="#" method="post">
<h3> Select your Favorite Programming Language:</h3>
foreach($_POST|'Language’] as $selected)
{
echo $selected."</br>";
7
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Web Based Application Development with PHP 4-13 Creating and Validating Forms
Output
(2) locathost:8089/php-examples x | +
C/C++ A
ct
Java
PHP: v
Submit |
CiC++
Java
Python
Button
We can create the button using <input type ="submit'>
Various parameters of submit button are
1) name denotes the name of the submit button.
2) value is for writing some text on the text on the button.
ButtonDemo.php
<form action="#" method="post">
<h3> Login Form</h3>
User Name:<input type="text" name="username"/>
<br/> <br/>
Password: <input type="password" name="password'/>
<br/> <br/>
<input type="submit" name= "submit" value="Submit'/>
<br/>
</form>
<?php
if(isset($_POST['submit']))//to run PHP script on submit
{
echo "<h3> Welcome user: ".$_ POST['username']."</h3>";
7
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Web Based Application Development with PHP 4-14 Creating and Validating Forms
@ localhost:8089/php-examples x | +
€) > @ |O © bocalhostsos: -UNW!» =
Login Form
Ex. 4.2.1: Create HTML form with one textbox to get user’s name. Also write PHP code to show length of entered
name when, the HTML form is submitted.
Sol.: Step 1 : The HTML form can be created as follows
<!DOCTYPE html>
<html>
<head> <title> HTML-PHP DEMO</title>
</head>
<body>
<form method="post" action="http://localhost/getdata.php">
Name: <input type="text" name="myname" size="20"/>
<br/>
<input type="submit" name="submit" value="submit"/>
</form>
</body>
</html>
Step 2: The PHP script to display the length of submitted name is as written below
<?php
7
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Web Based Application Development with PHP 4-15 Creating and Validating Forms
Output
= Oo x
HTML-PHP DEMO x +
Name: |chitra
— o x
localhost/php-exs <=
€ @® localh: @
Ex. 4.2.2: Create HTML form to enter one number. Write PHP code to display the message about number is odd or
even.
Sol.:
Step 1: The HTML form for accepting number is created as below -
<!DOCTYPE html>
<html >
<head> <title> HTML-PHP DEMO</title>
</head>
<body>
<form method="post" action="http://localhost/getdata.php">
Enter Number: <input type="text" name="mynum" size="5"/>
<br/>
<input type="submit" name="submit" value="submit"/>
</form>
</body>
</html>
Step 2 : The PHP script deciding whether the number is even or odd is as given below -
<?php
print "The number is: ";
print $_POST['mynum'];
$a= $_POST["mynum"];
if($a%2==1)
print "<br/> The number is odd *;
7
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Web Based Application Development with PHP 4-16 Creating and Validating Forms
else
print "<br/> The number is even ";
?>
Output
- o x
HTML-PHP DEMO x +
— Oo x
[ localhost/php-exs Xe
€ localho ¢ » =
Ex. 4.2.3 : Create a form containing information Sr.no, title of the book, publishers, quantity, price read the data
from the form and display it using PHP script.
Sol.: Step 1 : Create an HTML page for inputting the data. Following is the code for HTML script .
HTML Document{input.html]
<Idoctype html public "-//w3c//dtd html 4.0 transitional//en">
<html>
<head>
<title> Book Order Form </title>
</head>
<body>
<h3> Enter the Book Data </h3>
<form method="post" action="http://localhost/php-examples/formdemo.php">
<table>
<tr>
<td> Sr.No. </td>
<td><input type="text" name="SLNo"> </td>
</tr>
<tr>
<td>Book name</td>
<td><input type="text" name="BName"> </td>
Fi
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Web Based Application Development with PHP 4-17 Creating and Validating Forms
</tr>
<tr>
<td>Publisher</td>
<td><input type="text" name="PUBName'> </td>
</tr>
<u>
<td> Price</td>
<td><input type="text" name="Price"> </td>
</tr>
<td> Quantity</td>
<td><input type="text" name="Oty"> </td>
</tr>
<tr>
Step 2 : Create a PHP script which will read out the data entered by the user using HTML form. The
code is as follows -
PHP Document[formdemo.php]
<html>
<head>
<title> Book Information</title>
</head>
<body>
<?php
$BName=$_POST["BName'];
$PUBName=$_POST|"PUBName'];
$Price=$_POST|'Price'];
$Qty=$_POSTI'Aty'|;
>
<center>
<h3> Book Data </h3>
<table border=1>
<tr>
<th>Book name</th>
<th>Publisher</th>
<th>Price</th>
<th>Quantity</th>
</tr>
<u>
<td> <?php print ("$BName"); ?> </td>
<td> <?php print ("$PUBName"); ?> </td>
<td> <?php printf("%3.2f',$Price); 7></td>
7
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Web Based Application Development with PHP 4-18 Creating and Validating Forms
StNo. 10
Book name Sofware Engineering
Publisher Technical Publications
Price 250
Quantity 10
Submit)
{ Clear)
Now click on the Submit button and the PHP file will be invoked. The output will then be as follows -
MaMa.eee)
File Edit View History Bookmarks Tools Help
[Elscckintomition = :
Ex. 4.2.4: Write a PHP program to accept a positive integer ‘N’ through a HTML form and to display the sum of
all the numbers from 1 to N.
Sol. :
<html>
<head>
<title> PHP Demo </title>
</head>
<body>
<form method="post">
%
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Web Based Application Development with PHP 4-19 Creating and Validating Forms
Output
PHP Demo x +
€ ® localh ¢ »
10 Submit
Review Question
1. Explain date and time control in HTMLS with necessary illustrations.
In some web applications, we can have multiple forms in a single PHP document. Following program
shows how to handle the requests from multiple forms.
ManyFormDemo.php
<form method="post">
<h3> Personal Information Form</h3>
User Name: <input type="text" name="username"/>
<br/> <br/>
Address: <input type="text" name="address'/>
<br/> <br/>
<input type="submit" name="submit_personal_info" value="Submit"/>
<br/>
</form>
<form method="post">
7
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Web Based Application Development with PHP 4-20 Creating and Validating Forms
<h3> Feedback Form</h3>
<textarea name= "feedback" rows="5" cols="50"> </textarea>
<br/>
<input type="submit" name="submit_feedback" value="Submit Feedback'/>
</form>
<?php
if(!empty($_POST['submit_personal_info’]))
Output
(on Submitting Personal_info form)
[&) localhost:8089/php-examples) X +
7
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Database Operations
After installing MySQL or XAMPP, we can use MySql prompt for submitting the SQL queries. With the
help of SQL queries we can create database, insert data to database, update or delete data from the
database.
We can get the command prompt for MySQL by executing mysql.exe file present in MySQL folder. As I
have installed XAMPP, I could locate MySQL folder as
6-1)
Web Based Application Development with PHP 5-2 Database Operations
t > ThisPC >» Local Disk (C:) > xampp » mysql > bin vod Searchbin
Just double click the mysql.exe file and you will get the command prompt mysql>
Following are the illustrations that help us to perform various operations on database using MySQL
queries.
1. Creating database
mysql> CREATE DATABASE mydb;
Query OK, 1 row affected (0.15 sec)
|mysql |
| students |
| test |
qe
4 rows in set (0.06 sec)
7
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Web Based Application Development with PHP Database Operations
or
w
4. Creating table
We must create a table inside a database hence it is a common practice to use create table command after
USE database command. While creating a table we must specify the table fields.
mysql> CREATE TABLE my_table(id INT(4),.name VARCHAR(20));
Query OK, 0 rows affected (0.28 sec)
5. Displaying a table
After creating the table using SHOW command we can see all the existing tables in the current database.
mysql> SHOW TABLES;
| Tables_in_mydb |
pannncenecenenennenennnne +
| my_table |
+-
1 row in set (0.00 sec)
We can also write SELECT statement for selecting particular row by specifying some condition such as -
mysql> SELECT * FROM my_table where id=1;
or
mysql> SELECT * FROM my_table where name='SHILPA’;
Thus we can insert the rows into the table by repeatedly giving the INSERT command.
7
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Web Based Application Development with PHP 5-4 Database Operations
If we want to get the records in sorted manner then we use ORDER BY clause
| id |name |
ne +
| 4 | MONIKA |
| 1|SHILPA |
| 2 | SUPRIYA |
| 3 | YOGESH |
+ ah anna nnnnnne +
4 rows in set (0.00 sec)
| 1|SHILPA |
| 2|SUPRIYA |
| 3| YOGESH |
| 4| PRIYANKA |
shana haan +
4 rows in set (0.00 sec)
7
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Web Based Application Development with PHP 5-5 Database Operations
Then use SELECT statement for displaying the contents of the table we use following command
mysql> SELECT * FROM my_table;
| 1|SHILPA |
| 2 | SUPRIYA |
| 4 | PRIYANKA |
-+
3 rows in set (0.00 sec)
Review Questions
1. Explain the benefits of PHP and MySQL.
MYSQL is running
Low
Local host on which the Password
1. Creation of Database
+ We can create a database using the function mysql_query. The mysql_error() function is used to
obtain the error messages if any command gets failed.
* mysql_query function in php is used to pass a sql query to mysql database.
Syntax
mysql_query ( string query |, resource link _identifier])
This function returns the query handle for SELECT queries, TRUE/FALSE for other queries, or FALSE on
failure.
7
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Web Based Application Development with PHP 5-6 Database Operations
Example
mysql_query("CREATE DATABASE mydb",$conn)
Syntax
mysql_connect ( string server , string username , string password)
Returns a MySQL link identifier on success, or FALSE on failure.
Example
$conn=mysql_connect("localhost ","root',"mypassword");
* The mysql_close() function is used to close the database connection.
Syntax
mysql_close (Connection)
}
mysql_close($conn); //closing the database
?>
2. Selecting Database
The database can be selected using the function mysql_select_db().
Syntax
mysql_select_db ( string database_name [, resource link identifier])
Where
mysql_select_db() attempts to select existing database on the server associated with the specified link
identifier. It returns TRUE on success, or FALSE on failure.
For example -
<?php
// Make a MySOL Connection
7
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Web Based Application Development with PHP 5-7 Database Operations
3. Creation of Table
Before creating the table a database must be created and within which the table can be created. Note that
before creating a table the desired database must be selected.
<?php
// Make a MySQL Connection
um oo
$conn=mysql_connect("localhost ,"root","mypassword");
if(!$conn)
{
die(‘error in connection’.mysql_error());
}
//Create a database
if(mysql_query("CREATE DATABASE mydb',$conn))
{
print “Database created";
}
else
{
print “Error creating database :". mysql_error();
}
mysql_select_db(“mydb",$conn); //before creating table select the database
$query="CREATE TABLE my_table
(
id INT(4),
name VARCHAR(20)
a
mysql_query($query,$conn);//Execution of Query
1. Insertion of Data
For inserting a data into the table we use the INSERT query. For example
$query=" INSERT INTO my_table (idname) VALUES(1,'SHILPA’)";
mysql_query($query,$conn);//Execution of Query
7
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Web Based Application Development with PHP 5-8 Database Operations
Here is a PHP script in which insert query is used to insert two records in the table
<?php
// Make a MySQL Connection
$conn=mysql_connect("localhost","root","mypassword");
if('$conn)
{
die(‘error in connection’.mysql_error());
}
mysql_select_db(“mydb",$conn); //select the database
$query=" INSERT INTO my_table (idmame) VALUES(1,'SHILPA’)";
mysql_query($query,$conn);//Execution of Query
$query=" INSERT INTO my_table (idmame) VALUES(2,'MONIKA)”;
mysql_query($query,$conn);//Execution of Query
Sometimes values that can be inserted in the table can be obtained from some another script and these
values might be present in the variables. Insertion of such data can be done using $_POST variables. It is
as shown below -
<?php
The above execution returns a result handle. Then The mysq]_fetch_array() is used to retrieve a row of
data as an array from a MySQL result handle.
Syntax :
mysql_fetch_array(result, result_type)
7
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Web Based Application Development with PHP 5-9 Database Operations
PHP Script for Displaying records
<?php
// Make a MySQL Connection
$conn=mysql_connect("localhost ","root","mypassword");
if('$conn)
{
die(‘error in connection’.mysql_error());
}
mysql_select_db(“mydb",$conn); //select the database
//Execution of Query for displaying the data
$result=mysql_query("SELECT * FROM my table”);
while($row = mysql_fetch_array($result))
{
echo $row|'id'] ."". $row[‘name’]; //Each record will be displayed
/fline by line
echo "<br />";
}
mysql_close($conn); //closing the database
>
Syntax
int mysql_num_rows ( resource $result )
Example
<?php
// Make a MySQL Connection
$conn=mysql_connect("localhost :3306/mydb ","root","mypassword');
if(!$conn)
{
die(‘error in connection'.mysq]l_error());
}
//Select a database
mysql_select_db("mydb", $conn);
Snum_rows = mysql_num_rows(Sresult);
//Print number of rows
echo "Total number of rows are $num_rows";
mysql_close($conn); //closing the database
2?>
Syntax
mysql_num_fields(resource_name)
7
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Web Based Application Development with PHP 5-10 Database Operations
It returns the number of fields present in the resource and false on failure
Example
<?php
// Make a MySQL Connection
$conn=mysql_connect("localhost:3306/mydb , root","mypasswora");
if(!$conn)
{
die(‘error in connection'.mysql_error());
}
//Select a database
mysql_select_db("mydb", $conn);
$result = mysql_query("select id;mame from my_table where id = '1' ");
echo mysql num _fields($result); // since two fields are fetched, returns 2
a>
Review Questions
1. Explain with PHP code, how to connect to a database ?
For example
<?php
// Make a MySQL Connection
$conn=mysql_connect("localhost' ,‘root","mypasswora");
if(!$conn)
{
die(‘error in connection’.mysql_error());
}
7
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Web Based Application Development with PHP 5-11 Database Operations
For example —
<?php
Review Questions
1. Write a PHP program to update the database.
2. How will you delete record from database using PHP program ?
Sol.: We will create a table in the database test. The name of the table is mytable. Then we will insert the record
into the table using the INSERT command, update particular field of the record using the command UPDATE and
Delete the record using the command DELETE.
The PHP script is as fo llows -
PHP Document[DBDemo.php]
<?php
print "<br/>";
echo "Table Created!";
7
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Web Based Application Development with PHP 5-12 Database Operations
echo $row|'id'];
echo "</td> <td>";
echo $row[‘name]};
echo "</td> <td>";
echo $row['phone');
echo "</td> <td>";
echo $row|‘emailld’];
echo "</td></tr>";
}
echo "</table>";
$result = mysql_query("UPDATE mytable SET phone='55555' WHERE phone ='22222")
or die(mysql_error());
print "<br/>";
echo "Data Updated!";
$result =mysql_query("SELECT * FROM mytable")
or die(mysql_error());
print "<br/>";
print “<b>User Database</b>";
echo "<table border='1'>";
echo "<tr><th>ID</th> <th>Name</th> <th>Phone</th><th>Email-ID</th> </tr>";
while($row = mysql_fetch_array( $result ))
{
// Print out the contents of each row into a table
7
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Web Based Application Development with PHP 5-13 Database Operations
echo "<tr><td>";
echo $row|'id'];
echo "</td> <td>";
echo $row['name'];
echo "</td> <td>";
echo $row|'phone’);
echo "</td><td>";
echo $row|['emailld'];
echo "</td></tr>";
}
echo "</table>";
7
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Web Based Application Development with PHP 5-14 Database Operations
Output
(@ Meta Feet
Ble £48 View History Bookmats Toots Help
Girma. nocamorp-sampley080¢me-pro| +|
shes soe |(E
+
tee n a
‘Connected to database!
‘Table Created!
Data Inserted!
User Database
ID Name Phose — EmailID
1 Priyanka11111 labe123@gmad com
2 Kumar [22222 |pqrll @yahoo com
3 [Archana [33333 xya@rediffinad
com
Data Updated!
User Database
ID Name Phose — Email-ID
1 Priyanka/11111 labe123}@gmalcom
2 (Kumar {55555 [email protected]
3. Archana [33333 xyz @rediffinal
com
Data Deleted!
User Database
ID Name Phose| Email ID
1 Priyanka/11111 labe123@emaacom
2 [Kumar [55555 jpqrl1@
yahoo com
Ex. 5.5.2: Create a HTML form “result.html” with a text box and a submit button to accept registration number of
the student. Write a “result.php” code to check the status of the result from the table to display whether the
student has “PASS” or “FAIL” status. Assume that the MYSQL database “my_db” has the table “result_table” with
two columns REG_NO and STATUS. Also write a PHP program to delete a record from result_table.
Sol. :
Step1: Create a database named my_db. Create a table result_table for this database and insert the
values in this table. The table is created as follows —
REG_NO STATUS
101 PASS
102 FAIL
103 PASS
104 FAIL
105 PASS
Step 2: Create an HTML form to accept the registration number, the HTML document is as follows —
result.html
<!DOCTYPE html>
<html>
<head>
<title> STUDENT RESULT </title>
</head>
<body>
<form name="myform" method="post" action="http://localhost/php-examples/result.php" >
<input type="text" name="reg_no"/>
<input type="submit" value="Submit"/>
</form>
7
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Web Based Application Development with PHP 5-15 Database Operations
</body>
</html>
Step 3: Create a PHP script to accept the registration number. This php script will connect to MYSQL
database and the status(PASS or FAIL) of the corresponding registration number will be displayed.
result.php
<?php
// Make a MySOL Connection
$conn=mysql_connect("localhost","root","");
if(!$conn)
5!
die(‘error in connection'.mysql_error());
}
mysql_select_db("my_db",$conn); //select the database
//Execution of Query for displaying the data
$reg_no = intval($_POST|'reg_no']);
Step4: Load the HTML form created in Step 2 and click the submit button by entering some
registration number.
€ > © fie ¢ »
[105 | | Submit
7
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Web Based Application Development with PHP 5-16 Database Operations
= o xX
localhost/php-exe, X
105 is PASS
{
echo $row|'REG_NO|] ."is". $row['STATUS]]; //Each record will be displayed
/fine by line
echo "<br />";
}
Ex. 5.5.3 : Write a user defined function ‘Calculatelnterest’ using PHP to find the simple interest to be paid for a
loan amount. Read the loan amount, the number of years and rate of interest from a database table called
LOANDETAILS having three fields AMT, YEARS, and RATE, and Calculate the interest using the user defined
function.
Sol. :
Step1: Create a database table named LOANDETAILS having three fields AMT, YEARS and RATE.
Insert the values in it. The sample table will be as follows —
AMT YEARS RATE
10000 5 69
7
TECHNICAL PUBLICATIONS - An up thrust for knowledge