PHP
PHP
MSBTE - I Scheme
S.Y. Diploma Semester - VI
Computer Engineering Group
(CO / CM / IF / CW)
M.E. (Computer)
Formerly Assistant Professor in
P.E.S. Modern College of Engineering,
Pune
TECHNICAL
PUBLICATIONS
SINCE 1993 An Up-Thrust for Knowledge
(i)
Web based Application
development with PHP
Subject Code : 22619
Published by :
®
TECHNICAL Amit Residency, Office No.1, 412, Shaniwar Peth, Pune - 411030, M.S. INDIA
PUBLICATIONS P h . : + 9 1 - 0 2 0 - 2 4 4 9 5 4 9 6 / 9 7 , Te l e f a x : + 9 1 - 0 2 0 - 2 4 4 9 5 4 9 7
SINCE 1993 An Up-Thrust for Knowledge
Email : [email protected] Website : www.technicalpublications.org
ISBN 978-93-89750-01-0
(iv)
3a. Write constructor and 3.1 Creating Classes and Objects
destructor functions for the 3.2 Constructor and Destructor
Unit - III given problem in PHP.
3.3 Inheritance, Overloading and Overriding,
Apply Object 3b. Implement inheritance to Cloning Object.
Oriented extend the given base class.
Concepts in PHP 3.4 Introspection, Serialization
3c. Use overloading / overriding
to solve the given problem.
3d. Clone the given object.
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 POST methods, Server Role
multiple Forms for the given
problem. 4.2 Form controls : text box, text area, radio
button, check box, list, buttons.
4c. Apply the given validation
Unit - IV rules on form. 4.3 Working with multiple forms :
Creating and - A web page having many forms.
4d. Set/ modify/ delete cookies
validating forms
using cookies attributes. - A form having multiple submit buttons.
4e. 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.
given problem using PHP 5.2 Connecting to a MySQL database : MySQL
script. database server from PHP.
Unit - V 5b. Insert data in the given 5.3 Database Operations : Insert data,
database using PHP script. Retrieving the Query result.
Database
Operations 5c. 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.
(v)
Table of Contents
2.6.1 Creating Images . . . . . . . . . . . . . . . . . . . . 2 - 19
Unit - I
2.6.2 Images with Text. . . . . . . . . . . . . . . . . . . . 2 - 21
Chapter - 1 Expressions and Control 2.6.3 Scaling Images . . . . . . . . . . . . . . . . . . . . . 2 - 21
Statements in PHP 2.6.4 Creation of PDF Document. . . . . . . . . . . . 2 - 23
(1 - 1) to (1 - 24)
Unit - III
1.1 History and Advantages of PHP . . . . . . . . . . . . 1 - 1
1.1.1 Syntax of PHP. . . . . . . . . . . . . . . . . . . . . . . 1 - 1 Chapter - 3 Object Oriented Concepts in PHP
1.1.2 How to Write and Execute PHP Program ? 1 - 3 (3 - 1) to (3 - 12)
1.2 Variables, Data types, Expressions, Operators and
Constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 - 4 3.1 Creating Classes and Objects. . . . . . . . . . . . . . . 3 - 1
3.1.1 Defining Classes . . . . . . . . . . . . . . . . . . . . . 3 - 1
1.2.1 Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 - 4
3.1.2 Instantiating Objects . . . . . . . . . . . . . . . . . . 3 - 1
1.2.2 Data Types . . . . . . . . . . . . . . . . . . . . . . . . . 1 - 4
3.1.3 Properties . . . . . . . . . . . . . . . . . . . . . . . . . . 3 - 1
1.2.3 Constants. . . . . . . . . . . . . . . . . . . . . . . . . . . 1 - 5
3.1.4 Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 - 1
1.2.4 Operators. . . . . . . . . . . . . . . . . . . . . . . . . . . 1 - 6
3.1.5 Visibility . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 - 2
1.2.5 Expressions . . . . . . . . . . . . . . . . . . . . . . . . . 1 - 9
3.2 Constructors and Destructor . . . . . . . . . . . . . . . 3 - 2
1.2.6 Displaying Messages on Screen . . . . . . . . . 1 - 9
1.3 Decision Making Control Statements . . . . . . . 1 - 11 3.3 Inheritance, Overloading and Overriding, Cloning
Object. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 - 4
1.4 Loop Control Structures. . . . . . . . . . . . . . . . . . 1 - 16 3.3.1 Data Encapsulation . . . . . . . . . . . . . . . . . . . 3 - 4
1.5 Programming Examples based on Control Structures 3.3.2 Inheritance. . . . . . . . . . . . . . . . . . . . . . . . . . 3 - 5
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 - 18
3.3.3 Overloading. . . . . . . . . . . . . . . . . . . . . . . . . 3 - 6
Unit - II 3.3.4 Overriding . . . . . . . . . . . . . . . . . . . . . . . . . . 3 - 7
3.3.5 Cloning Object . . . . . . . . . . . . . . . . . . . . . . 3 - 8
Chapter - 2 Arrays, Functions and Graphics 3.4 Introspection and Serialization . . . . . . . . . . . . 3 - 10
(2 - 1) to (2 - 26)
Unit - IV
2.1 Introduction to Arrays . . . . . . . . . . . . . . . . . . . . 2 - 1
2.1.1 Creating and Manipulating Arrays . . . . . . . 2 - 1 Chapter - 4 Creating and Validating Forms
2.1.2 Types of Arrays. . . . . . . . . . . . . . . . . . . . . . 2 - 4 (4 - 1) to (4 - 32)
2.2 Extracting Data from Arrays, Implode, Explode and
4.1 Creating Web Page, GET and POST Methods,
Flip Functions . . . . . . . . . . . . . . . . . . . . . . . . . . 2 - 6
Server Role. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 - 1
2.3 Traversing Arrays . . . . . . . . . . . . . . . . . . . . . . . 2 - 9 4.1.1 Creating Web Page . . . . . . . . . . . . . . . . . . . 4 - 1
2.4 Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 - 11 4.1.2 GET and POST Methods . . . . . . . . . . . . . . 4 - 1
2.4.1 Defining Function . . . . . . . . . . . . . . . . . . . 2 - 11 4.1.3 Concept of Subglobal Array . . . . . . . . . . . . 4 - 2
2.4.2 Parameters. . . . . . . . . . . . . . . . . . . . . . . . . 2 - 12 4.1.4 Server Role . . . . . . . . . . . . . . . . . . . . . . . . . 4 - 3
2.4.3 Types of Functions . . . . . . . . . . . . . . . . . . 2 - 14 4.1.4.1 Apache and PHP. . . . . . . . . . . . . . . . . 4 - 3
2.5 Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 - 16 4.1.4.2 Installation of Apache, PHP and MySQL
2.6 Basic Graphics Concepts . . . . . . . . . . . . . . . . . 2 - 18 .................................4-4
4.2 Form Controls . . . . . . . . . . . . . . . . . . . . . . . . . . 4 - 6
(vi) R
UNIT - I
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.html”)
The variable names in PHP begin with the $ sign.
Following are some reserved keywords that are used 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";
?>
</body>
</html>
Output
R
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Web Based Application Development with PHP 1-3 Expressions and Control Statements in PHP
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
$s="I like PHP";
echo $s;
?>
R
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Web Based Application Development with PHP 1-4 Expressions and Control Statements in PHP
Output
Review Questions
1. What is PHP ? Give general syntax of PHP.
2. Give the advantages of PHP.
1.2.1 Variables
Variables are the entities that are used for storing the values.
PHP is a dynamically typed language. That is PHP has no type declaration.
The value can be assigned to the variable in following manner -
$variable_name=value
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.
2. 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;
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
For displaying the integer value the Integer type is used.
It is similar to the long data type in C.
The size is 32 bit.
Double Type
For displaying the real values the double data type is used.
R
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Web Based Application Development with PHP 1-5 Expressions and Control Statements in PHP
It includes the numbers with decimal point, exponentiation or both. The exponent can be represented by E
or e followed by integer literal.
It is not compulsory to have digits before and after the decimal point. For instance .123 or 123. is allowed
in PHP.
String Type
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.
The string literals can be defined using either single or double quotes.
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’
will be typed as it is but
“The total marks are= $marks”
will display the value of $marks variable.
Boolean Type
There are only two types of values that can be defined by the Boolean type and those are TRUE and
FALSE.
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.
1.2.3 Constants
Constant is an identifier that contains some value.
Once the constant value is assigned to this identifier it does not get changed.
Constant is case sensitive by default.
Generally the constant identifiers are specified in upper case.
The valid constant name must start with letter or underscore. It may then followed by the digits.
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
// Valid constant names
define("MYVALUE","10");
echo MYVALUE; These statements will cause
// Invalid constant names error. If we remove these
define("1MYVALUE","something"); statements then we will get 10
echo 1MYVALUE; as an output.
?>
R
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Web Based Application Development with PHP 1-6 Expressions and Control Statements in PHP
1.2.4 Operators
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
There are eight relational operators used in PHP.
These are <,>,<=,>=,!=,== has their usual meaning. These are six traditional operators.
The operator === is used in PHP. It returns true if both operands that are using === have same type and
have same value.
The operator !== is opposite of ===.
If one of the operand in the six operators is not same then the coercion will occur automatically.
3. Boolean Operators
The Boolean operators are
Operator Meaning
R
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Web Based Application Development with PHP 1-7 Expressions and Control Statements in PHP
5. Bitwise Operators
Following are bitwise operators used in PHP.
Operator Name Example Result
& And $x & $y Bits that are set in both $x and $y are set.
^ 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 $y steps to the left. Another purpose of this operator can
also be “multiply by two”.
>> Shift right $x >> $y Shift the bits of $x $y 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 a|b a&b a^b
0 0 0 0 0
0 1 1 0 1
1 0 1 0 1
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
Operation Result in Binary Result in Decimal
a&b 00000000 0
R
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Web Based Application Development with PHP 1-8 Expressions and Control Statements in PHP
a<<1 01010000 80
a>>1 00010100 20
Programming Example
<?php
$a = 40;
$b = 80;
$AND_opr = ($a & $b);
$OR_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/>XOR Operation: ".$XOR_opr;
echo "<br/> Left shift operation: ".($a<<1);
echo "<br/> Right shift operation: ".($a>>1);
?>
Output
6. Assignment Operator
The assignment operator is used to assign the values to variables. Following is a list of assignment operators.
R
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Web Based Application Development with PHP 1-9 Expressions and Control Statements in PHP
+= a += 5 means a = a + 5
-= a -= 5 means a = a - 5
Similarly *=, /= operators are used for performing arithmetic multiplication and division operation.
1.2.5 Expressions
R
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Web Based Application Development with PHP 1 - 10 Expressions and Control Statements in PHP
PHP also makes use of the printf function used in C. For example
printf(“The student %d has %f marks”,$roll_no,$marks);
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";
printf("<b>The roll number: %d</b>",$roll_no); Output
print "<br/><b>";
printf("The name: %s",$name);
print "</b>";
?>
</body>
</html>
The echo can output one or more strings. Print can only output one string.
R
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Web Based Application Development with PHP 1 - 11 Expressions and Control Statements in PHP
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($a>$b)
echo "a is greater than b";
?>
Syntax
if(expression)
{
Statements;
}
else
{
Statements;
}
Example
<?php
$a = 80;
$b = 40;
if($a>$b)
echo "a is greater than b";
else
echo "b is greater than a";
?>
R
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Web Based Application Development with PHP 1 - 12 Expressions and Control Statements in PHP
Syntax
if(condition1){
// Code to be executed if condition1 is true
} elseif(condition2){
// Code to be executed if the condition1 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>";
?>
</body>
</html>
R
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Web Based Application Development with PHP 1 - 13 Expressions and Control Statements in PHP
Output
Example
<?php
$today = getdate();
switch($today['weekday'])
{
case "Monday":print "Today is Monday";
break;
case "Tuesday":print "Today is Tuesday ";
break;
case "Wednesday":print "Today is Wednesday ";
break;
case "Thursday":print "Today is Thursday";
break;
case "Friday":print "Today is Friday";
break;
case "Saturday":print "Today is Saturday";
R
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Web Based Application Development with PHP 1 - 14 Expressions and Control Statements in PHP
break;
case "Sunday":print "Today is Sunday ";
break;
default: print "Invalid input";
}
?>
Output
Syntax
break
For example
$i = 0;
for ($i = 0;$i <= 7;$i++)
{
if ($i==3)
{
break;
}
R
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Web Based Application Development with PHP 1 - 15 Expressions and Control Statements in PHP
echo $i;
echo "<br />";
}
Output
0
1
2
The continue Statement
The continue statement is used to skip some statements inside the loop. The continue statement is used
with decision making statement such as if...else.
The continue statement forces to execute the next iteration of the loop to execute.
The flowchart for continue statement is,
Syntax
Continue
For example
$i = 0;
for ($i = 0;$i <= 7;$i++)
{
if ($i==3)
{
continue;
}
echo $i;
echo "<br />";
}
Output
0
1
2
4
R
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
1. This statement terminates the execution of It terminates only the current iteration of the loop.
remaining iteration of the loop.
2. It causes early termination of the entire loop. It causes early execution of the next iteration.
R
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Web Based Application Development with PHP 1 - 17 Expressions and Control Statements in PHP
Syntax
do{
// Code to be executed
} while(condition);
Example
<?php
$i=1;
print "The numbers are ...";
print "<br/>";
do
{
print $i;
print "<br/>";
$i++;
} while($i<=10);
?>
Output
The output will be same as above.
Syntax
for(initialization; condition; increment){
// Code to be executed
}
Example
<?php
print "The numbers are ...";
print "<br/>";
for($i=1;$i<n)
{
print $i;
print "<br/>";
$i++;
}
?>
Output
The output will be same as above.
R
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Web Based Application Development with PHP 1 - 18 Expressions and Control Statements in PHP
</head>
<body>
<center>
<?php
print "<table border =1>";
print "<tr>";
print "<th>Number</th>";
print "<th>Square</th>";
print "<th>Cube</th>";
Output
print "</tr>";
for($i=1;$i<=10;$i++)
{
print "<tr>";
print "<td>$i";
print "</td>";
print "<td>";
print $i*$i;
print "</td>";
print "<td>";
print pow($i,3);
print "</td>";
print "</tr>";
}
print "</table>";
?>
</center>
</body>
</html>
Ex. 1.5.2 : Write a PHP script to compute the sum and average of N numbers.
Sol. :
<html>
<head>
<title> Sum and Average </title>
</head>
<body>
R
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Web Based Application Development with PHP 1 - 19 Expressions and Control Statements in PHP
<center> Output
<?php
$sum=0;
for($i=1;$i<=10;$i++)
{
$sum+=$i;
}
$avg=$sum/10;
print "The Sum is: $sum";
print "<br/>";
print "the Average is: $avg";
?>
</center>
</body>
</html>
Ex. 1.5.3 : Write PHP programs to print whether current year is leap year or not.
Sol. : Output
<html>
<head>
<title>Leap Year Demo</title> </head>
<body>
<?php
$year=2016;
print "<br/>";
if($year%4==1)
{ printf("Year %d is not a leap year",$year); }
else
{ printf("Year %d is a leap year",$year); }
?>
</body>
</html>
Ex. 1.5.4 : Write PHP programs to print whether given number is odd or even.
Sol. :
<html> Output
<head>
<title>Even Odd Demo</title>
</head>
<body>
<?php
for($i=1;$i<=10;$i++)
{
$num=$i;
print "<br/>";
if($num%2==1)
{ printf("Number %d is Odd",$num); }
else
{ printf("Number %d is Even",$num); }
}
R
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Web Based Application Development with PHP 1 - 20 Expressions and Control Statements in PHP
?>
</body>
</html>
Ex. 1.5.5 : Write PHP script to compute the sum of positive integers upto 30 using do-while statement.
Sol. : Output
<html>
<head>
<title>Sum of Integers</title>
</head>
<body>
<?php
$sum=0;
$i=1;
do
{
$sum=$sum+$i;
$i++;
}while($i<=30);
printf("The sum of first 30 positive integers is %d ",$sum);
?>
</body>
</html>
Ex. 1.5.6 : Write PHP script to compute factorial of ‘n’ using while or for loop construct.
Sol. :
<html> Output
<head>
<title>Factorial Program</title>
</head>
<body>
<?php
$n = 5;
$factorial = 1;
for ($i=$n; $i>=1; $i--)
{
$factorial = $factorial * $i;
}
echo "Factorial of $n is $factorial";
?>
</body>
</html>
R
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Web Based Application Development with PHP 1 - 21 Expressions and Control Statements in PHP
Ex. 1.5.8 : Construct a PHP script to compute the squareRoot, Square, Cube and Quad of 10 numbers.
Sol. :
<html>
<head>
<title>SQUARE CUBE QUAD DEMO</title>
</head>
<body>
<?php
print "<b>Table<br/>";
print "<table border='1'>";
print "<tr><th>num</th><th>Sqr</th><th>Cube</th><th>Quad</th></tr>";
for($count=1;$count<=10;$count++)
{
$sq=$count*$count;
$cube=$count*$count*$count;
$quad=$count*$count*$count*$count;
print "<tr><td>$count</td><td>$sq</td><td>$cube</td><td>$quad</td></tr>";
}
print "</table>";
?>
</body>
</html>
R
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Web Based Application Development with PHP 1 - 22 Expressions and Control Statements in PHP
Output
Ex. 1.5.9 : With the use of PHP, switch case and if structure perform the following and print appropriate message.
i) Get today's date ii) If date is 3, it is dentist appointment. iii) If date is 10, go to conference.
iv) If date is other than 3 and 10, no events are scheduled.
Sol. :
<!DOCTYPE html>
<html>
<body>
<?php
echo “Today date is ” . date(“d/m/y”) . “<br>”;
if((date(“d”)<3)||(date(“d”)>10))
Output
echo “No Event!!!”;
else if((date(“d”)>3)&&(date(“d”)<10))
echo “No Event!!!”;
else
{
switch(date(“d”))
{
case 3 : echo “Dentist Appointment”;
break;
case 10 : echo “Go to Conference”;
break;
}
}
?>
</body>
</html>
R
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Web Based Application Development with PHP 1 - 23 Expressions and Control Statements in PHP
R
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Web Based Application Development with PHP 1 - 24 Expressions and Control Statements in PHP
Notes
R
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Web Based Application Development with PHP 2-1 Arrays, Functions and Graphics
UNIT - II
2
2.1 Introduction to Arrays
Arrays, Functions and Graphics
Arrays is a collection of similar type of elements, but in PHP you can have the elements of mixed
type together in single array.
In each 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.
2.1.1 Creating and Manipulating Arrays
For creating an array in PHP, we use array() construct.
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
R
TECHNICAL PUBLICATIONS
(2 - 1)- An up thrust for knowledge
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>
R
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Web Based Application Development with PHP 2-3 Arrays, Functions and Graphics
Output
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];
?>
</body>
</html>
R
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Web Based Application Development with PHP 2-4 Arrays, Functions and Graphics
R
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Web Based Application Development with PHP 2-5 Arrays, Functions and Graphics
3. Multidimensional Arrays
PHP support for multidimensional arrays.
We can 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>
R
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Web Based Application Development with PHP 2-6 Arrays, Functions and Graphics
Output
Review Questions
1. What is array ? How to create and manipulate arrays ?
2. Explain various types of arrays in PHP.
2.2 Extracting Data from Arrays, Implode, Explode and Flip Functions
<?php
$arr = array("a" => "Pune","b" => "Mumbai", "c" => "Chennai");
extract($arr);
echo "\$a = $a; \$b = $b; \$c = $c";
?>
</body>
</html>
R
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Web Based Application Development with PHP 2-7 Arrays, Functions and Graphics
Output
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
R
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
<?php
$arr=array("Red"=>10,"Green"=>20,"Blue"=>30,"Black"=>40);
$result=array_flip($arr);
print_r($result);
?>
</body>
</html>
Output
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
The foreach function is used to iterate through all the elements of the loop. The syntax of foreach
statement is as follows -
R
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
}
The above code can be modified and written as follows -
PHP Document[ArrayFunDemo6.php]
<?php
$mylist = array("Hello", "PHP","You","Are","Wonderful!!!");
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 ?
2.4 Functions
R
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Web Based Application Development with PHP 2 - 12 Arrays, Functions and Graphics
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()
{
$a=10;
$b=20;
$c=$a+$b;
return $c;
}
print "<b>The Function Demo Program with return statement</b>";
print "<br/>";
print "10+20= ".Addition();
?>
Output
2.4.2 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
R
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+$b;
return $c;
}
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);
?>
Output
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';
}
R
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Web Based Application Development with PHP 2 - 14 Arrays, Functions and Graphics
2. Variable Functions
Variable function is a concept in which the variable name is appended with parenthesis.
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";
}
R
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Web Based Application Development with PHP 2 - 15 Arrays, Functions and Graphics
function green()
{ You can change it to
echo "Trees are Green"; “blue” or “green”
}
$fun_var="red";
$fun_var(); Calling variable function.
?> $ sign is must
</body>
</html>
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
};
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($arg1,$arg2)
{
return "Addition = ".($arg1+$arg2);
};
echo $addition(10,20);
?>
</body>
</html>
R
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Web Based Application Development with PHP 2 - 16 Arrays, Functions and Graphics
Output
Review Questions
1. What is function ? How to pass parameters to the function ?
2. Explain variable and anonymous function with suitable example in php.
2.5 Strings
String is a collection of characters.
In PHP 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
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.
R
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";
R
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Web Based Application Development with PHP 2 - 18 Arrays, Functions and Graphics
$Str2="hello";
if(strcmp($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
Review Question
1. What is string ? Explain various operations that can be performed on strings
With 256 possible values for each red, blue and green color there are 16,777,216 possible colors for
every pixel.
R
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Web Based Application Development with PHP 2 - 20 Arrays, Functions and Graphics
GIF image/gif
JPEG image/jpeg
PNG image/png
WBMP image/vnd.wap.wbmp
R
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Web Based Application Development with PHP 2 - 21 Arrays, Functions and Graphics
AddTxtImageDemo.php
<?php
$image = imagecreate(300,200);
$white = imagecolorallocate($image,255,255,255);
$red = imagecolorallocate($image,255,0,0);
ImageFilledRectangle($image,50,50,100,100,$red);
ImageString($image,5,50,120,"Welcome",$red);
imagejpeg($image);
header('Content-Type: image/jpeg');
?>
Output
R
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Web Based Application Development with PHP 2 - 22 Arrays, Functions and Graphics
Following program illustrates the use of imagecopyresampled for scaling the image
ScaleImgDemo.php
<?php
$image = imageCreateFromJPEG('d://apple.jpg'); The sample image apple.jpg
$width = ImageSx($image);
$height = ImageSy($image);
$x=$width/2;
$y=$height/2;
$scaledImg=ImageCreateTrueColor($x,$y);
ImageCopyResampled($scaledImg,$image,0,0,0,0,$x,$y,$width,$height);
header('Content-Type: image/png');
ImagePNG($scaledImg);
?>
Output
R
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Web Based Application Development with PHP 2 - 23 Arrays, Functions and Graphics
FPDF is an open source library which is used for creating a PDF document. It is open source means ,
we can get it downloaded freely from internet.
Features of fpdf:
o It provides the choice of measure unit, page format and margins for pdf page.
o It provides the support for various fonts, colors, encoding, and image formats.
If you have downloaded your php using XAMPP package, then by default it is present at the location
c:/xampp/php/pear/fpdf/
Programming Example: Following is a simple php program that creates a PDF document with some
text written on it.
pdfDemo.php
<?php
require('c:/xampp/php/pear/fpdf/fpdf.php'); 1
$pdf=new FPDF(); 2
3 $pdf->AddPage();
$pdf->SetFont('Arial','B',20); 4
$pdf->Cell(100,100,'This is my First PDF page using PHP!'); 5
$pdf->Output(); 6
?>
R
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Web Based Application Development with PHP 2 - 24 Arrays, Functions and Graphics
Output
R
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Web Based Application Development with PHP 2 - 25 Arrays, Functions and Graphics
Review Questions
1. Write a PHP script to create an image and display text along with the image in PHP.
2. Write a PHP program to illustrate scaling of image.
3. What are features of fpdf ? Explain how will you create pdf using php.
R
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Web Based Application Development with PHP 2 - 26 Arrays, Functions and Graphics
Notes
R
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Web Based Application Development with PHP 3-1 Object Oriented Concepts in PHP
UNIT - III
$this->rollNo = $r;
}
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();
/* Assigning values to properties*/
$Stud1->setName("AAA");
$Stud2->setName("BBB");
$Stud1->setRollNo(101);
$Stud2->setRollNo(102);
3.1.5 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
{
...
function __construct($rollNo,$firstName, $lastName, $age)
{
$this->rollNo=rollNo;
$this->firstName = $firstName;
$this->lastName = $lastName;
$this->age = $age;
}
}
The new constructor can be used as follows -
$s1=new Student(101,”AAA”,”BBB”,17);
$s2= new Student(102,”XYZ”,”PQR”,25);
Destructor
Destructor is a specialized function which is used to deallocate the memory allocated to it.
It is denoted as __destruct().
PHP Destructor method is called just before PHP is about to release any object from its memory. It is
normally called before closing the file.
Programming Example
destructDemo.py
<!DOCTYPE html>
<html>
<body>
<?php
class Student {
public $name;
function __construct($name) {
$this->name = $name;
}
function __destruct() {
echo "<h4>The Student record with name '{$this->name}' is removed from the database.</h4>";
}
}
$s = new Student("Ashwini");
?>
</body>
</html>
R
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Web Based Application Development with PHP 3-4 Object Oriented Concepts in PHP
Output
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 ?
R
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Web Based Application Development with PHP 3-5 Object Oriented Concepts in PHP
//child class
class Samsung extends Mobile {
private $model;
R
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
Programming Example
<!DOCTYPE html>
<html>
<body>
<?php
class A {
function fun()
{
echo "Inside Parent Class";
}
}
class B extends A{
function fun()
{
echo "<br/>Inside Child Class";
}
}
$obj1 = new A();
$obj2 = new B();
$obj1->fun();
$obj2->fun();
?>
</body>
</html>
Output
R
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>
R
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Web Based Application Development with PHP 3 - 10 Object Oriented Concepts in PHP
Output
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() {
R
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Web Based Application Development with PHP 3 - 11 Object Oriented Concepts in PHP
if(class_exists("Parent1")){
$obj_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();
}
?>
Output
Serialization()
Serializing an object means converting it to a byte stream representation that can be stored in a 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.
R
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);
?>
Output
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.
R
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Web Based Application Development with PHP 4-1 Creating and Validating Forms
UNIT - IV
4.1 Creating Web Page, GET and POST Methods, Server Role
4.1.1 Creating Web Page
The web page is created using following steps
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 sent is POST is a 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.
R
TECHNICAL PUBLICATIONS - An up thrust for knowledge
(4 - 1)
Web Based Application Development with PHP 4-2 Creating and Validating Forms
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 -
R
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Web Based Application Development with PHP 4-3 Creating and Validating Forms
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 is a 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
R
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;
?>
Output
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.
R
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Web Based Application Development with PHP 4-6 Creating and Validating Forms
Let us learn various form components with the help of simple HTML documents.
Input.html
<form action=”hello.php” method=”get”>
Name: <input type=”text” name=”user”/>
<input type=”submit” value=”Submit”/>
</form>
Hello.php
<?php
$name=$_GET["user"];
R
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Web Based Application Development with PHP 4-7 Creating and Validating Forms
Step 3 : Open the web browser and type the name of the HTML file created in step 1
Click Submit button, and you can invoke the php file. It will display following message
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”>
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
R
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;
?>
Output
R
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Web Based Application Development with PHP 4-9 Creating and Validating Forms
Step 1 :
Input.html
<form 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=$_GET["fruit"];
if(($choice!=null))
{
echo("My favorite fruit is: ".$choice);
}
?>
R
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Web Based Application Development with PHP 4 - 10 Creating and Validating Forms
Output
Click Submit button and the php page will be displayed as follows –
chkDemo.php
<form action="#" method="post">
<h3> Enter your Favorite Programming Language:</h3>
R
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Web Based Application Development with PHP 4 - 11 Creating and Validating Forms
R
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Web Based Application Development with PHP 4 - 12 Creating and Validating Forms
4.2.5 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=" ">label</option>
<option value=" ">label</option>
…
</select>
ListDemo.php
<form action="#" method="post">
<h3> Select your Favorite Programming Language:</h3>
<h4>(Press ctrl+click for multiple selection)</h4>
<select name="Language[]" multiple>//initializing name with array
<option value="C/C++">C/C++</option>
<option value="C#">C#</option>
<option value="Java">Java</option>
<option value="PHP">PHP</option>
<option value="Python">Python</option>
</select>
<br/><br/>
<input type="submit" name="submit" value="Submit"/>
<br/>
</form>
<?php
if(isset($_POST['submit']))//to run PHP script on submit
{
echo "<h4>You have selected... </h4>";
foreach($_POST['Language'] as $selected)
{
echo $selected."</br>";
}
}
?>
R
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Web Based Application Development with PHP 4 - 13 Creating and Validating Forms
Output
4.2.6 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>";
}
?>
R
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Web Based Application Development with PHP 4 - 14 Creating and Validating Forms
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
print "The name is: ";
print $_POST["myname"];
$len= strlen($_POST["myname"]);
print "<br/> The length of name is: ";
print $len;
?>
R
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Web Based Application Development with PHP 4 - 15 Creating and Validating Forms
Output
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 ";
R
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
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]
<!doctype 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>
R
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>
<tr>
<td>Price</td>
<td><input type="text" name="Price"></td>
</tr>
<td>Quantity</td>
<td><input type="text" name="Qty"></td>
</tr>
<tr>
<td><input type="submit" value="Submit"></td>
<td><input type="submit" value="Clear"></td>
</tr>
</table>
</form>
</body>
</html>
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=$_POST["Qty"];
?>
<center>
<h3> Book Data </h3>
<table border=1>
<tr>
<th>Book name</th>
<th>Publisher</th>
<th>Price</th>
<th>Quantity</th>
</tr>
<tr>
<td><?php print ("$BName"); ?></td>
<td><?php print ("$PUBName"); ?></td>
<td><?php printf("%3.2f",$Price); ?></td>
R
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Web Based Application Development with PHP 4 - 18 Creating and Validating Forms
Now click on the Submit button and the PHP file will be invoked. The output will then be as follows -
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">
R
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Web Based Application Development with PHP 4 - 19 Creating and Validating Forms
?>
Output
Review Question
1. Explain date and time control in HTML5 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">
R
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Web Based Application Development with PHP 4 - 20 Creating and Validating Forms
<?php
if(!empty($_POST['submit_personal_info']))
{
echo "<h3> Welcome user: ".$_POST['username']."</h3>";
}
if(!empty($_POST['submit_feedback']))
{
echo "<h3> We value your feedback: </h3>";
echo "Your feedback is<br/>".$_POST["feedback"];
}
?>
Output
(on Submitting Personal_info form)
R
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Web Based Application Development with PHP 4 - 21 Creating and Validating Forms
R
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Web Based Application Development with PHP 4 - 22 Creating and Validating Forms
R
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Web Based Application Development with PHP 4 - 23 Creating and Validating Forms
One can create a PHP page with multiple submit buttons on single form. The action indicated by each
submit button is separately handled in PHP.
Following is a calculator program, in which basic arithmetic operations are triggered by four submit
buttons.
Calculator.php
<form method="post">
<h3> Simple Arithmetic Calculator</h3>
Number 1:<input type="text" size="5" name="num1"/>
<br/><br/>
Number 2:<input type="text" size="5" name="num2"/>
<br/><br/>
<input type="submit" name="add" value="ADDITION"/>
<input type="submit" name="sub" value="SUBTRACTION"/>
<input type="submit" name="mul" value="MULTIPLICATION"/> Four Submit buttons on
<input type="submit" name="div" value="DIVISION"/> a single form
<?php
if(!empty($_POST['add']))
{
$result=$_POST['num1']+$_POST['num2'];
echo "<h3> Addition: ".$result."</h3>";
}
if(!empty($_POST['sub']))
{
$result=$_POST['num1']-$_POST['num2'];
echo "<h3> Subtraction: ".$result."</h3>";
}
if(!empty($_POST['mul']))
{
$result=$_POST['num1']*$_POST['num2'];
echo "<h3> Multiplication: ".$result."</h3>";
}
if(!empty($_POST['div']))
{
$result=$_POST['num1']-$_POST['num2'];
echo "<h3> Division: ".$result."</h3>";
}
?>
R
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Web Based Application Development with PHP 4 - 24 Creating and Validating Forms
Output
preg_match function : The preg_match() function searches string for pattern, returning true if pattern exists,
and false otherwise.
Syntax
int preg_match ( string $pattern , string $subject [, array &$matches [, int $flags = 0 [, int $offset = 0 ]]] )
where
pattern denotes the pattern to be searched for
subject denotes the input string
$matches[0] will contain the text that matched the full pattern
The optional parameter offset can be used to specify the alternate place from which to start the search.
R
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Web Based Application Development with PHP 4 - 25 Creating and Validating Forms
</form>
</body>
</html>
<?php
// On submitting form below function will execute.
if(isset($_POST['submit'])){
if (empty($_POST["name"]))
{
echo "Name is required";
}
else
{
$name = test_input($_POST["name"]);
// check name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name))
{
echo "Only letters and white space allowed";
}
}
}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
//php code ends here
?>
Output
R
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Web Based Application Development with PHP 4 - 26 Creating and Validating Forms
R
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Web Based Application Development with PHP 4 - 27 Creating and Validating Forms
Output
4.5 Cookies
Cookie is a small file that server embeds in the user’s machine. This is another method of passing user
information to the server.
Cookies are used to identify the users.
A cookie consists of a name and a textual value. A cookie is created by some software system on the
server.
In every HTTP communication between browser and server a header is included. The header stores
the information about the message.
The header part of http contains the cookies.
There can be one or more cookies in browser and server communication.
Uses of Cookies
While cookies can be used for any state-related purpose, they are principally used as a way of
maintaining continuity over time in a web application.
One typical use of cookies in a website is to “remember” the visitor, so that the server can customize
the site for the user.
Some sites will use cookies as part of their shopping cart implementation so that items added to the
cart will remain there even if the user leaves the site and then comes back later.
Cookies are also frequently used to keep track of whether a user has logged into a site.
PHP Document[CookieSetDemo.php]
<?php
$Cookie_period=time()+60*60*24*30;
setcookie("Myname", "Monika", $Cookie_period);
?>
Output
Note that you have got the blank screen it indicates that the cookie is set. In above PHP document we
have set the PHP script for one month. Just observer the third parameter of the setcookie function.
Now you can retrieve the cookie and read the value to ensure whether or not the cookie is set.
R
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Web Based Application Development with PHP 4 - 29 Creating and Validating Forms
PHP Document[CookieReadDemo.php]
<html>
<head><title>Reading Cookies</title>
<body>
Output
<?php
if (isset($_COOKIE["Myname"]))
echo "<h3>Welcome " . $_COOKIE["Myname"]."!!!</h3>";
else
echo "<h3>Welcome guest!</h3>";
?>
</body>
</html>
Program Explanation
The isset function is used for checking whether or not the cookie is set.
Then using the $_COOKIE the value of the cookie can be retrieved.
Review Questions
1. Explain the concept of cookies with its working.
2. Write a PHP script to demonstrate creation and reading of cookies.
R
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Web Based Application Development with PHP 4 - 30 Creating and Validating Forms
Because server storage is a finite resource, objects loaded into memory are released when the request
completes, making room for other requests and their session objects. This means there can be more
active sessions on disk than in memory at any one time.
Sometimes the information about the session is required by the server. This information can be
collected during the session. This process is called session tracking.
In PHP, session state is available to the developer using the $_SESSION variable. The unique ID for
the sessions can be stored in superglobal array $_SESSION.
PHP keeps track of session by using a function called session_start(). Due to the call to session_start()
function the session ID is created and recorded.
Following is a simple PHP script in which the information about session is tracked.
PHP Document[SessionDemo.php]
<?php
session_start();
if(isset($_SESSION['pgvisit']))
{
$_SESSION['pgvisit']=$_SESSION['pgvisit']+1;
echo "<h3>You are visiting this page for <i>". $_SESSION['pgvisit']."</i> times</h3>";
}
else
{
$_SESSION['pgvisit']=1;
echo "<h3>You are visiting this page for the first time</h3>";
}
?>
R
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Web Based Application Development with PHP 4 - 31 Creating and Validating Forms
Program Explanation :
In above program, we have started the session by using session_start() function.
The isset() function checks if the pgvisit variable has already been set. If pgvisit has been set, we can
increment our counter. If pgvisit is not set, then we create a set it to 1.
The value of pgvisit is displayed on the screen.
Review Question
1. Explain the working of session handling in PHP.
Review Question
1. Explain the use of mail() function in PHP.
R
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Web Based Application Development with PHP 4 - 32 Creating and Validating Forms
Notes
R
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Web Based Application Development with PHP 5-1 Database Operations
UNIT - V
5
5.1 Introduction to MySQL
Database Operations
MYSQL is a open source database product and can be downloaded from the web site
http://dev.mysql.com/downloads/mysql.
MYSQL is a kind of database in which the records are stored in an entity called tables.
In the tables the data is arranged in the rows and columns.
We can query a database to retrieve particular information. Query is a request or a question for the
database. There is a common practice of making use of structured query language(SQL).
Advantages of PHP-MySQL
PHP is a server side scripting language and it has an ability to create dynamic pages with customized
features. Using PHP-MySQL user friendly and interactive web sites can be created.
Both PHP and MySQL are open-source technologies that work hand-in-hand to create rich internet
applications. The purchased code provides you the encrypted source code to prevent replication or
modification, whereas open-source programs encourage users to utilize, scrutinize and customize the
code.
Due to availability of these technologies as free of cost, the cost effective web solutions can be created.
PHP-MySQL are stable technologies and have cross platform compatibility. Hence the web
application developed using these technologies become portable.
Since HTML can be embedded within the PHP, there is no need to write separate code for web-
scripting.
Open-source coding has been checked and doubled checked by thousands or even millions of people
around the world. Hence one can built the reliable web application using these technologies.
The most popular web sites being developed using PHP and MySQL technologies
are -
1. Facebook 2. WordPress
3. Wikipedia 4. Yahoo
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
R
TECHNICAL PUBLICATIONS
(5 - 1)- An up thrust for knowledge
Web Based Application Development with PHP 5-2 Database Operations
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)
R
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Web Based Application Development with PHP 5-3 Database Operations
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 |
+-----------------------+
| my_table |
+-----------------------+
1 row in set (0.00 sec)
R
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
R
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;
+------+---------------+
| id | name |
+------+---------------+
| 1 | SHILPA |
| 2 | SUPRIYA |
| 4 | PRIYANKA |
+------+---------------+
3 rows in set (0.00 sec)
Review Questions
1. Explain the benefits of PHP and MySQL.
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.
R
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Web Based Application Development with PHP 5-6 Database Operations
Example
mysql_query("CREATE DATABASE mydb",$conn)
The mysql_connect() function Open a connection to a MySQL Server.
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)
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 MySQL Connection
R
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
$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)
)”;
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 (id,name) VALUES(1,'SHILPA')”;
mysql_query($query,$conn);//Execution of Query
R
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 (id,name) VALUES(1,'SHILPA')”;
mysql_query($query,$conn);//Execution of Query
$query=” INSERT INTO my_table (id,name) VALUES(2,'MONIKA')”;
mysql_query($query,$conn);//Execution of Query
Syntax :
mysql_fetch_array(result, result_type)
R
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Web Based Application Development with PHP 5-9 Database Operations
Syntax
int mysql_num_rows ( resource $result )
This returns number of rows in result on success, or NULL on error.
Example
<?php
// Make a MySQL Connection
$conn=mysql_connect("localhost :3306/mydb ","root","mypassword");
if(!$conn)
{
die('error in connection'.mysql_error());
}
//Select a database
mysql_select_db("mydb", $conn);
$num_rows = mysql_num_rows($result);
//Print number of rows
echo "Total number of rows are $num_rows";
mysql_close($conn); //closing the database
?>
Syntax
mysql_num_fields(resource_name)
R
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","mypassword");
if(!$conn)
{
die('error in connection'.mysql_error());
}
//Select a database
mysql_select_db("mydb", $conn);
$result = mysql_query("select id,name from my_table where id = '1' ");
echo mysql_num_fields($result); // since two fields are fetched, returns 2
?>
Review Questions
1. Explain with PHP code, how to connect to a database ?
2. Write a PHP code to retrieve data from database.
For example
<?php
// Make a MySQL Connection
$conn=mysql_connect("localhost","root","mypassword");
if(!$conn)
{
die('error in connection'.mysql_error());
}
R
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Web Based Application Development with PHP 5 - 11 Database Operations
For example –
<?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=” DROP DATABASE mydb”;
mysql_query($query,$conn);//Execution of Query
mysql_close($conn); //closing the database
?>
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
// Make a MySQL Connection
mysql_connect("localhost", "root", "mypassword") or die(mysql_error());
mysql_select_db("test") or die(mysql_error());
echo "Connected to database!";
mysql_query("CREATE TABLE mytable(id INT NOT NULL AUTO_INCREMENT, PRIMARY KEY(id), name
VARCHAR(30),
phone INT,emailId VARCHAR(30))")
or die(mysql_error());
print "<br/>";
echo "Table Created!";
R
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Web Based Application Development with PHP 5 - 12 Database Operations
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
R
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['emailId'];
echo "</td></tr>";
}
echo "</table>";
$result = mysql_query("DELETE FROM mytable WHERE phone='33333'")
or die(mysql_error());
print "<br/>";
echo "Data Deleted!";
$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
echo "<tr><td>";
echo $row['id'];
echo "</td><td>";
echo $row['name'];
echo "</td><td>";
echo $row['phone'];
echo "</td><td>";
echo $row['emailId'];
echo "</td></tr>";
}
echo "</table>";
?>
R
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Web Based Application Development with PHP 5 - 14 Database Operations
Output
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. :
Step 1 : 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 –
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>
R
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 MySQL Connection
$conn=mysql_connect("localhost","root","");
if(!$conn)
{
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']);
R
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Web Based Application Development with PHP 5 - 16 Database Operations
Sol. :
Step 1 : 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 –
R
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Web Based Application Development with PHP 5 - 17 Database Operations
Step 2 : The PHP code for calculating the simple interest the above values in a function will be as
follows –
Interest.php
<?php
function CalculateInterest()
{
// Make a MySQL Connection
$conn=mysql_connect("localhost","root","");
if(!$conn)
{
die('error in connection'.mysql_error());
}
mysql_select_db("my_db",$conn); //select the database
//Execution of Query for displaying the data
$result=mysql_query("SELECT * FROM LOANDETAILS");
$row = mysql_fetch_array($result);
$amount= $row['AMT'];
$rate= $row['RATE'];
$years= $row['YEARS'];
$interest=($amount * $rate *$years)/100;
mysql_close($conn); //closing the database
return $interest;
}
print "Simple Interest =".CalculateInterest();
?>
Output
R
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Web Based Application Development with PHP 5 - 18 Database Operations
Notes
R
TECHNICAL PUBLICATIONS - An up thrust for knowledge
R
Laboratory Work
Experiment 2 : Write a PHP program to demonstrate the use of decision making control structures
using -
a) If statement
b) If-else statement
c) Switch statement
Sol. : Refer Section 1.3
Experiment 3 : Write a PHP program to demonstrate the use of looping structures using -
a) While statement
b) Do-while statement
c) For statement
d) Foreach statement
Sol. : Refer Section 1.4
Experiment 6 : Write a simple PHP program to demonstrate use of simple function and
parameterized function.
Sol. : Refer Section 2.4
Experiment 7 : Write a simple PHP program to create PDF document by using graphics concepts.
Sol. : Refer Section 2.6.4
Experiment 14 : Write a simple PHP program for sending and receiving plain text message (e-mail).
Sol. : Refer Section 4.7
Experiment 16 : Develop a simple application to Update, Delete table data from database.
Sol. : Refer example 5.1.1
R
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Web Based Application Development using PHP S-1 Solved Sample Test Papers
R
TECHNICAL PUBLICATIONS
(S - 1)- An up thrust for knowledge
Web Based Application Development using PHP S-2 Solved Sample Test Papers
c) What is the difference between GET and POST methods ? (Refer section 4.1.2)
d) Enlist various form of controls in PHP ? (Refer section 4.2)
e) Enlist the advantages of MySQL. (Refer section 5.1)
f) Give MySQL query for creation of student table. (Refer section 5.1.1)
R
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Programming with Python S-3 Solved Sample Question Paper
R
TECHNICAL PUBLICATIONS - An up thrust for knowledge