0% found this document useful (0 votes)
72 views57 pages

Ite Unit 2

..

Uploaded by

Allu Varshitha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
72 views57 pages

Ite Unit 2

..

Uploaded by

Allu Varshitha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 57

MAHESH BABU ASSISTANT PROFESSOR

INFORMATION
TECHNOLOGY ESSENTIALS
NOTES
SEMESTER III-II

MAHESH BABU

ASSISTANT PROFESSOR

CSE DEPARTMENT

MAHESH BABU ASSISTANT PROFESSOR


MAHESH BABU ASSISTANT PROFESSOR

UNIT II- SCRIPTING ESSENTIALS

Need for Scripting languages - Types of scripting languages - Client side scripting - Server
side scripting - PHP - Working principle of PHP - PHP Variables - Constants - Operators –
Flow Control and Looping - Arrays - Strings - Functions - File Handling - PHP and MySQL -
PHP and HTML - Cookies - Simple PHP scripts.

NEED FOR SCRIPTING LANGUAGES


Definition of Scripting Language: A scripting language is a programming language designed for
integrating and communicating with other programming languages. Some of the most widely used
scripting languages are HTML, JavaScript, VBScript, PHP, Perl, Python, Ruby, and ASP and so on.
 In general, scripting languages are easier to learn and faster to code in more structured and
compiled languages such as C and C++.
 Scripting languages are useful tools for developing interactive web pages with minimum
efforts.
 Scripting Languages are often interpreted (rather than compiled).
 The scripting languages are useful for producing dynamic web contents. That means web
page can be changed using user input.
Advantages of Scripting Languages:
 Scripting languages are easy to learn.
 It requires minimum programming knowledge or experience to develop the web pages using
scripting languages.
 The scripting languages allow simple creation and editing in variety of text editors.
 Using scripting languages we can develop dynamic and interactive web pages.
 There are some scripting languages that validate the information entered by the user.
TYPES OF SCRIPTING LANGUAGES
There are two types of scripting languages – Client side scripting language and server side scripting
language.
Client Side Scripting Language:
The client side scripting is used to create the web pages as a request or response to server. These
pages are displayed to the user on web browser. For example: HTML, CSS, JavaScript, PHP.
Server Side Scripting Language:
Server side scripting is used to create web pages that provide some services. These scripts generally
run on web servers. For example: ASP, JSP, Servlet, PHP.
Difference between Client side and Server side scripting languages
Server Side Scripting Client Side Scripting
The server side scripting is used to The client side scripting is used to create the web pages
create the web pages that provide some as a request or response to server. These pages are
services. displayed to the user on web browser.
A user’s request is fulfilled by running a The processing of these scripts takes place on the end
script directly on the web server to user’s computer. The source code is transferred from the
generate dynamic HTML pages. This user’s computer over the internet and run directly in the
HTML is then sent to the client browser. browser.
Uses: processing of user request, Uses: making interactive web pages, for interacting with
accessing to databases. temporary storages such as cookies or local storage,
sending request to server and getting the response and
displaying that response in web browser.
These scripts generally run on web These scripts generally run on web browser.
servers.

MAHESH BABU ASSISTANT PROFESSOR


MAHESH BABU ASSISTANT PROFESSOR

Example: PHP, ASP.NET, C++, java Example: HTML, CSS, JavaScript.


and C#.

PHP

PHP was developed in 1994 by Apache group. PHP stands for PHP: Hypertext Pre-
processor. PHP is a server-side scripting language. It is mainly used for form handling and database
access. It is free to download and use.

WORKING PRINCIPLE OF PHP

PHP is a server side scripting language embedded in XHTML. It is an alternative to CGI,


ASP, ASP.NET and JSP. The extension to PHP files are .php, .php3 or .phtml. The PHP processor
works in two modes. If the PHP processor finds XHTML tags in the PHP script then the code is
simply copied to the output file. But when the PHP processor finds the PHP code in the script then
that code is simply interpreted and the output is copied to the output file.
If you click the view source on the web browser you can never see the PHP script because
the output of the PHP script is send directly to the browser but you can see the XHTML tags. PHP
makes use of dynamic typing that means there is no need to declare variables in PHP.
The type of variable gets set only when it is assigned with some value. PHP has large
number of library functions which makes it flexible to develop the code in PHP.

Installation of PHP
For installing PHP either PHP installer is preferred or all in package like XAMPP/WAMPP is
preferred. Before installing PHP, install Apache web server on your PC. The PHP installer can be
downloadable from www.php.net/download.
Exercise: Explain how can you create a web based application using XAMPP. Give all the steps
required in detail.

Solution:
XAMPP is a free distribution package that makes it easy to install Apache web server,
Mysql, PHP, PERL. Here in XAMPP(The X stands for any OS) or WAMPP(the W stands for
Windows OS).
Step 1:Go to the site : https://www.apachefriends.og/index.html
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 Tomact.
Step 6: Write a PHP script and save it in C:\XAMPP\htdocs\php-examples folder by giving the
filename and extension as .php.
Step 7: Open the web browser and type http://localhost/php-examples/yourfilename.php
Step 8: The web application will be executed within your web browser.

For example:
<? php
$s=”I like PHP”;
echo $s;
?>

MAHESH BABU ASSISTANT PROFESSOR


MAHESH BABU ASSISTANT PROFESSOR

GENERAL SYNTACTIC CHARACTERISTICS OF PHP


 PHP code can be embedded in the XHMTL 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. The variable names in PHP begin, with the $ sign. Following are some
reserved keywords that are used in PHP.

And Default False If Or This


Break Do For Include Require True
Case Else Foreach List Return Var
Class Elseif Function New Static Virtual
Continue Extends Global Not Switch While
Xor
 The comments in PHP can be #, //, /, /*....*/ .
 The PHP statements are terminated by semicolon.

How to write and execute PHP document?


Open some suitable text editor like Notepad and type the following code. Save the code by
the extension .php. It is expected that the PHP code must be stored in htdocs folder of Apache.
As I have installed xampp, I have got the directory c:\xampp\htdocs. I have created a folder
named php-examples inside the htdocs and stored all my PHP documents in that folder.
Hence, when i want to get the output of the PHP code I always give the URL.

Example:
<html>
<head>
<title>PHP DEMO</title>
</head>
<body>
<?php
$i=10;
echo “<h3>WELCOME </h3>”;
echo “ The value of the variable is =$i”;
?>
</body>
</html>
PHP Variable
 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
the 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 variables. If 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:
 The variable must start with letter or underscore but it should not begin with a number.
 It consists of alphanumeric characters or underscore.
 There should not be space in the name of the variable

MAHESH BABU ASSISTANT PROFESSOR


MAHESH BABU ASSISTANT PROFESSOR

 While assigning the values to the variables the variable must start with the $. For example,
$marks=100;
 Using the function IsSet the value of the variable can be tested. That means if isSet($marks)
function returns TRUE then that means some value is assigned to the variable marks.
 If the unbound variable gets referenced then the error reporting can be done with the help of
function error_reporting(7). The default error reporting level is 7.

Variable Scope

Local variables
Local variables are variables that are created within, and can only be accessed by, a
function. They are generally temporary variables that are used to store partially processed
results prior to the function’s return.
One set of local variables is the list of arguments to a function.
Example:
<?php
$i=10;
Function add()
{
$i=20;
$j=$i+10;
Echo “Value of j is:”.$j;
}
Add();
?>
Output:
//it takes the value $i=20 (Locally Scoped)
Value of j is :30

Global variables
There are cases when you need a variable to have global scope, because you want all
your code to be able to access it. To declare a variable as having global scope, use the keyword
global.
Syntax:
Global var_name; //This will access the clobal values of the variable.
Example:
<?php
$i=10;
Function add()
{
$i=20;
global $i;
$j=$i+10;
Echo “Value of j is:”.$j;
}
Add();
?>
Output:
//$i is declared as a global variable so it takes the value $i=10
Value of j is :20

MAHESH BABU ASSISTANT PROFESSOR


MAHESH BABU ASSISTANT PROFESSOR

Static variables
Static variables can be initialized only once. The static variable will be initialized for the first time.
Static variable will not be initialized whenever it is declared.
<?php
function test()
{
static $count = 0;
echo $count;
$count++;
}
for($i=0;$i<5;$i++)
test();//function is called 5 times
?>

Data Types
There are four scalar types that are used in PHP and those are Integer, Boolean, Double and String.
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 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.
 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 literal 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 sequence 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 $mark 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.
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 identifier is specified in upper case. The valid constant name must
start with letters or underscore. It may then be followed by digits.
 Using define function we can assign value to the constant. The first parameter is define
function is the name of the constant and the second parameter is the value which is to be
assigned.

MAHESH BABU ASSISTANT PROFESSOR


MAHESH BABU ASSISTANT PROFESSOR

Example:
<?
//valid constants names
define(“MYVALUE”,”10”);
echo “MYVALUE”;
//invalid constant names
define(“1MYVALUE”,”SOMETHING”)
echo “1MYVALUE”;
?>

OPERATORS
Arithmetic Operators and Operations
 PHP supports the collection of arithmetic operators such as +, _, *, /,%,++ and – with their
usual meaning.
 While using the arithmetic operators if both the operands 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.
Ceil The smallest integer less than or equal to the parameter is
returned.
Round Nearest integer is returned
Abs Returns the absolute value of the parameter
Min It returns the smallest element.
Max It returns the largest element.

MAHESH BABU ASSISTANT PROFESSOR


MAHESH BABU ASSISTANT PROFESSOR

Arithmetic Operators Example

<html>
<body>
<?php
$i=(20 + 10);
$j=($i - 5);
$k=($j * 4);
$l=($k / 2);
$m=($l % 5);
echo "i = ".$i."<br/>"; echo "j = ".$j."<br/>"; echo "k = ".$k."<br/>"; echo "l = ".$l."<br/>"; echo
"m = ".$m."<br/>";
?>
</body>
</html>

OUTPUT of the above given Example is as follows:

i = 30
j = 25
k = 100
l = 50
m=0
Increment and Decrement Operators:
It is also called as the unary operator. It usually increments or decrements the value by one.

Increment and Decrement Operators Example

<html>
<body>
<?php
$i=10;
$j=20;
$i++;
$j++;
echo $i."<br/>";
echo $j."<br/>";
$k=$i++;

MAHESH BABU ASSISTANT PROFESSOR


MAHESH BABU ASSISTANT PROFESSOR

$l=++$j;
echo $k."<br/>"; echo $l;
?>
</body>
</html>

OUTPUT of the above given Example is as follows:

11
21
11
22

Assignment Operators in PHP


Assignment operator is used to assign a value to a variable

Logical operators
Logical operators produce true-or-false results, and therefore are also known as Boolean
operators. There are four of them.

<?php
$a = 1; $b = 0;
echo ($a AND $b) . "<br>";
echo ($a or $b) . "<br>";
echo ($a XOR $b) . "<br>";
echo !$a . "<br>";
?>

MAHESH BABU ASSISTANT PROFESSOR


MAHESH BABU ASSISTANT PROFESSOR

Output:
0
1
1
0

Relational Operators or Comparison Operator


Relational operators test two operands and return a Boolean result of either TRUE or
FALSE. There are three types of relational operators: equality, comparison, and logical. It is also
called as comparison operator.
Comparison operators are generally used inside a construct such as an if statement in which you
need to compare two items. For example, you may wish to know whether a variable you have been
incrementing has reached a specific value, or whether another variable is less than a set value, and
so on
Note the difference between = and ==. The first is an assignment operator, and the second is a
comparison operator.
Operator Description
== Equality
=== Identity(Checks both value
and type)
!= Not Equal
< Less than
<= Less than or equal
> Greater than
>= Greater than or equal
Example:
<?php
$a = "1000";
$b = "+1000";
if ($a == $b) echo "1";//both will converted to same type and the it will compare.
if ($a === $b) echo "2";// this will not be executed. Because $a and $b are of different type
?>
Output:
1
Example2:
<?php
$a=22;
$b=25;
$c=30;
if(($a>$b)&($a>$c))
echo "A is greater";
elseif($b>$c)
echo "B is greater";
else
echo "C is greater";
?>
Output:
C is greater

MAHESH BABU ASSISTANT PROFESSOR


MAHESH BABU ASSISTANT PROFESSOR

String Operators in PHP

String Operators Example

<html>
<body>
<?php
$a = "Hello";
$b = $a . " Friend!";
echo $b;
echo "<br/>";
$c="Good";
$c .= " Day!";
echo $c;
?>
</body>
</html>

OUTPUT of the above given Example is as follows:

Hello Friend!
Good Day!

Boolean Operators
Boolean operators AND, OR, and NOT are used to manipulate logical statements. Boolean
operators are the core operators used in digital control systems as well as computer systems. AND
and OR are binary operators, while NOT is a unary operator.

Operator Meaning
And && The binary AND operation is
performed
Or || The binary OR operation is performed
Xor The XOR operation will be performed

Displaying Messages on the Web page


 The PHP is a server side scripting language and is used to submit the web page to the client
browser. Hence it is a standard method of embedding the PHP code within the XHTML
document. That means we can use the XHTML tags in PHP while displaying the output.
 The print function is used to create simple unformatted output. For example : The string can
be displayed as follows: print “I am proud of my <b>country</b>
 The numeric value can also be displayed using the print. For example : print(100);

MAHESH BABU ASSISTANT PROFESSOR


MAHESH BABU ASSISTANT PROFESSOR

 PHP also makes use of the printf function used in C. For example: printf(“The student %d
has %f marks”, $roll_no, $marks);
Example:
<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);
print “<br/><b>”;
printf(“ The name :%s”,$name);
print “</b>”;
?>
</body>
</html>

CONSTANTS
Constants are similar to variables, holding information to be accessed later, except that they are
what they sound like—constant. In other words, once you have defined one, its value is set for the
remainder of the program and cannot be altered.
Constant in PHP - define() function is used to set a
constant It takes three parameters they are:
◦ Name of the constant
◦ Value of the constant
◦ Third parameter is optional. It specifies whether the constant name should be case-
insensitive. Default is false

Constant string Example


<html>
<body>
<?php
/* Here constant name is ‘Hai’ and ‘Hello Friend’ is its constant value and true indicates the
constant value is case-insensitive */
define("Hai","Hello Friend",true);
echo hai;
?>
</body>
</html>
OUTPUT of the above given Example is as follows:
Hello Friend
PHP Example to calculate the area of the circle
<html>
<body>
<?php
// defining constant value PI = 3.14
define("PI","3.14");
$radius=15;

MAHESH BABU ASSISTANT PROFESSOR


MAHESH BABU ASSISTANT PROFESSOR

$area=PI*$radius*$radius;
echo "Area=".$area;
?>
</body>
</html>
OUTPUT of the above given Example is as follows:
Area=706.5
Predefined Constants
PHP comes ready-made with dozens of predefined constants that you generally will be
unlikely to use as a beginner to PHP. However, there are a few—known as the magic
constants—that you will find useful. The names of the magic constants always have two
underscores at the beginning and two at the end.

Example:
<?php
echo "This is line " . LINE . " of file " . FILE ;
?>
Output:
This is line 2 of file sample.php
This causes the current program line in the current file (including the path) being executedto be
output to the web browser.

FLOW CONTROL AND LOOP


The if Statement in PHP
 The if statement, the if...else statement or if....elseif statements are used as selection
statements. The selection is based on some condition.
 If statement executes some code only if a specified condition is true

Syntax:
if (condition) {
code to be executed if condition is true;
}

MAHESH BABU ASSISTANT PROFESSOR


MAHESH BABU ASSISTANT PROFESSOR

The if Statement Example

<html>
<body>
<?php
$i=0;
/* If condition is true, statement is executed*/
if($i==0)
echo "i is 0";
?>
<body>
</html>

OUTPUT of the above given Example is as follows:

i is 0

The if…else Statement in PHP


If…else statement executes some code if a condition is true and some another code if the condition
is false

Syntax:
if (condition)
{
code to be executed if condition is true;
}
else
{
code to be executed if condition is false;
}

The if…else Statement Example

<html>
<body>
<?php
$i=1;
/* If condition is true, statement1 is executed, else statement2 is executed*/
if($i==0)
echo "i is 0"; //statement1
else
echo "i is not 0"; //statement2
?>
<body>
</html>

OUTPUT of the above given Example is as follows:


i is not 0

The if…elseif…else Statement in PHP


If…elseif…else statement selects one of several blocks of code to be executed

MAHESH BABU ASSISTANT PROFESSOR


MAHESH BABU ASSISTANT PROFESSOR

Syntax:

if (condition)
{
code to be executed if condition is true;
}
elseif (condition)
{
code to be executed if condition is true;
}
else
{
code to be executed if condition is false;
}

The if…elseif…else Statement Example (Comparing two numbers)


<html>
<body>
<?php
$i=22;
$j=22;
/* If condition1 is true, statement1 is executed, if condition1 is false and condition2 is true,
statement2 is executed, if both the conditions are false statement3 is executed */
if($i>$j)
echo "i is greater"; //statement1 elseif($i<$j)
echo "j is greater"; //statement2
else
echo "numbers are equal"; //Statement3
?>
<body>
</html>

OUTPUT of the above given Example is as follows:


numbers are equal

Switch Statements
Similar to if statement the switch statement can also be used for selection. Following is a
simple PHP script for demonstrating switch statements
Syntax:

switch (n) {
case label1:
code to be executed if n=label1;
break;
case label2:
code to be executed if n=label2;
break;
...
default:
code to be executed if n is different from all labels;
}

MAHESH BABU ASSISTANT PROFESSOR


MAHESH BABU ASSISTANT PROFESSOR

PHP Program
<?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”;
break;
case “Sunday”: print “Today is Sunday”;
break;
default: print “Invalid Input”;
}
?>

Loop Statements
 The while, for and do-while statements of PHP are similar to Javascript.
 Following is a simple PHP script which displays the first 10 number.

For loop in PHP


PHP for loop executes a block of code, a specified number of times

Syntax:
for (initialization; test condition; increment/decrement)
{
code to be executed;
}

For loop Example


<html>
<body>
<?php
echo "Numbers from 1 to 20 are: <br>";
for ($x=1; $x<=20; $x++) {
echo "$x ";
}
?>
</body>
</html>

OUTPUT of the above given Example is as follows:


Numbers from 1 to 20 are:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20

MAHESH BABU ASSISTANT PROFESSOR


MAHESH BABU ASSISTANT PROFESSOR

Example 2:
<?php
$sum=0;
$n=10;
for($i=1;$i<=$n;$i++)
{
$sum=$sum+$i;
}
echo "The sum of ".$n." Natural numbers is: ". $sum;
?>
Output:
The sum of 10 Natural numbers is: 55

While Loop in PHP


While loop, loops through a block of code as long as the specified condition is true

Syntax:
while (condition)
{
code to be executed;
}

While Loop Example


<html>
<body>
<?php
$i=1;
/* here <condition> is a Boolean expression. Loop body is executed as long as condition is true*/
while($i<5){
echo "i is = $i <br>";
$i++;
}
?>
</body>
</html>

OUTPUT of the above given Example is as follows:

i is = 1
i is = 2
i is = 3
i is = 4

Do While loop in PHP


Do while loop will always execute the block of code once, it will then check the condition, and if
the condition is true then it repeats the loop

Syntax:

do {
code to be executed;

MAHESH BABU ASSISTANT PROFESSOR


MAHESH BABU ASSISTANT PROFESSOR

} while (condition );

Do While loop Example

<html>
<body>
<?php
$i=1;
/* here <condition> is a Boolean expression. Please note that the condition is evaluated after
executing the loop body. So loop will be executed at least once even if the condition is false*/
do
{
echo "i is = $i <br>";
$i++;
}while($i<5);
?>
</body>
</html>

OUTPUT of the above given Example is as follows:

i is = 1
i is = 2
i is = 3
i is = 4

Break statement
Break statement is used to terminate the loop. After the break statement is executed the control goes
to the statement immediately after the loop containing break statement

Break statement example


<html>
<body>
<?php
/* when $i value becomes 3, the loop is Terminated*/
for($i=0;$i<5;$i++)
{
if($i==3)
break;
else
echo "$i ";
}
?>
</body>
</html>

OUTPUT of the above given Example is as follows:


012

Continue statement
There are cases in which, rather than terminating a loop, you simply want to skip over the
remainder of iteration and immediately skip over to the next. Continue statement is used to skip a
particular iteration of the loop.
MAHESH BABU ASSISTANT PROFESSOR
MAHESH BABU ASSISTANT PROFESSOR

Continue statement example


<html>
<body>
<?php
/* when $i value becomes 3, it will skip the particular of the loop*/
for($i=0;$i<=5;$i++)
{
if($i==3)
continue;
else
echo "$i ";
}
?>
</body>
</html>

OUTPUT of the above given Example is as follows:


01245

Examples based on Control Statement


Write a PHP script to display the squares and cubes of 1 to 10 numbers.

Sol :
<html>
<head>
<title> Square and cube Table </title>
</head>
<body>
<center>
<?php
print “<table border=1”>”;
print “<tr>”;
print “<th> Numbers</th>”;
print “<th> Squares</th>”;
print “<th> Cube</th>”;
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>
MAHESH BABU ASSISTANT PROFESSOR
MAHESH BABU ASSISTANT PROFESSOR

Example Programs:
Write a PHP Script to compute the sum and average of N numbers.

PHP Program
<html>
<head>
<title> Sum and Average </title>
</head>
<body>
<center>
<?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>

Write PHP programs to print whether current year is leap year or not.
Sol :
<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>

Write PHP programs to print whether given number is odd or even.

Sol :
<html>
<head>
<title> Even Odd Demo</title>
MAHESH BABU ASSISTANT PROFESSOR
MAHESH BABU ASSISTANT PROFESSOR

</head>
<body>
<?php
for($i=1;$i<=10;$i++)
{
$num=$i;
print “<br/>”;
if($num%2==1)
{
print(“Number %d is Odd”,$num);
}
else
{
print(“Number %d is Even”,$num);
}
}
?>
</body>
</html>

Write PHP Script to compute the sum of positive integer upto 30 using do-while statement.
Sol:
<html>
<head>
<title> Sum of Integer</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>

Write PHP Script to compute factorial of ‘n’ using while or for loop construct.
Sol:
<html>
<head>
<title> Factorial Program </title>
</head>
<body>
<?php
$n=5;
$factorial=1;
for($i=$n;$i>=1;$i--)
{
$factorial=$factorial*$i;
MAHESH BABU ASSISTANT PROFESSOR
MAHESH BABU ASSISTANT PROFESSOR

}
echo “Factorial of $n is $factorial”;
?>
</body>
</html>

Write PHP Script to display Fibonacci of length 10.


Sol:
<html>
<head>
<title>Fibonacci Series</title>
</head>
<body>
<?php
$i=1;
$j=1;
print “<b> Fibonacci Series <br/> </b> “;
printf(“%d,%d”,$i,$j);
for($count=1;$count<9;$count++)
{
$k=$i+$j;
$i=$j;
$j=$k;
printf(“%d”,$k);
}
?>
</body>
</html>

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</b><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><th>$count</th><th>$sq</th><th>$cube</th><th>$quad</th></tr>”;
}
print “</table>”;
?>
</body>
</html>

MAHESH BABU ASSISTANT PROFESSOR


MAHESH BABU ASSISTANT PROFESSOR

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:
<html>
<body>
<?php
echo “Today date is”. date(“d/m/y”).”<br/>”;
if(date(“d”)<3) || (date(“d”)>10))
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>

Write a PHP code to display the following pattern

1
01
101
0101
10101

Sol:
<html>
<head>
</head>
<body>
<?php
for($i=0;$i<7;$i++)
{
for($j=1;$j<$i;$j++)
{
if($i+$j)%2==0)
{
printf(“0”);
}
else
{
printf(“1”);
}}
print “<br/>”;
MAHESH BABU ASSISTANT PROFESSOR
MAHESH BABU ASSISTANT PROFESSOR

}
?>
</body>
</html>

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.
 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.

Array Creation
In PHP there are two types of arrays -
1. Indexed Array: Indexed array are the arrays with numeric index. The array values can be stored
from index 0. For example -

<html>
<head>
<title> PHP Indexed arrays</title>
</head>
<body>
<?php
$names=array(“AAA”,”BBB”,”CCC”);
print_r($names);//print array structure
?>
</body>
</html>

Here values gets stored at corresponding index as follows -


$mylist[0]=10;
$mylist[1]=20;
$mylist[2]=30;
$mylist[3]=40;
$mylist[4]=50;
We can directly assign some value at specific index.
$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 Associated Array</title>
</head>
<body>
<?php
$city[“AAA”]=”Pune”;
$city[“BBB”]=”Mumbai”;
$city[“CCC”]=”Chennai”;

//printing array structures


print_r($city);
MAHESH BABU ASSISTANT PROFESSOR
MAHESH BABU ASSISTANT PROFESSOR

?>
</body>
</html>

Accessing Array Elements


 Using an array subscript we can access the array element. The value of subscript is enclosed
within the square brackets. For example -
 $citycode[‘Pune’]=005;
 $Name[0]=”Chitra”;
 Multiple values can be set to a single scalar variable using array. For example -
$people = array(“Meena”,”Teena”,”Heena”); list($operator,$accountant,
$manager)=$people;
 By this assignment Meena become operator, Teena becomes accountant and Heena becomes
manager.

Consider an associative array called person_age with name and age of 10 person. Write a
PHP program to calculate the average age of this associative array.

Sol:
<html>
<head>
<title> PHP Associative array</title>
</head>
<body>
<?php
$person_age=array(
‘AAA’ => 10, ‘BBB’ => 22, ‘CCC’ => 45, ‘DDD’ => 31, ‘EEE’ => 33, ‘FFF’ =>
25, ‘GGG’ => 56 , ‘HHH’ => 73, ‘III’ => 35, ‘JJJ’ => 47);
$sum=array_sum($person_age);
print(“The sum of all the ages is $sum”);
$avg=$sum/10;
print(“<br/> The average is $avg”);
?>
</body>
</html>

Multidimensional array in PHP


Multidimensional array is an array containing one or more arrays

Multidimensional array Example


<html>
<body>
<?php
/* Here $flower_shop is an array, where rose, daisy and orchid are the ID key which indicates rows
and points to array which have column values. */

$flower_shop = array(

"rose" => array( "5.00", "7 items", "red" ), "daisy" => array( "4.00", "3 items", "blue" ), "orchid" =>
array( "2.00", "1 item", "white" ), );
/* in the array $flower_shop['rose'][0], ‘rose’ indicates row and ‘0’ indicates column */
echo "rose costs ".$flower_shop['rose'][0]."items: ".$flower_shop['rose'][1]."<br>";
echo "rose costs ".$flower_shop['daisy'][0]."items: ".$flower_shop[' daisy '][1]."<br>";
MAHESH BABU ASSISTANT PROFESSOR
MAHESH BABU ASSISTANT PROFESSOR

echo "rose costs ".$flower_shop['orchid'][0]."items: ".$flower_shop[‘orchid '][1]."<br>";


?>
</body>
</html>

OUTPUT of the above given Example is as follows:

rose costs 5.00, and you get 7 items.


daisy costs 4.00, and you get 3 items.
orchid costs 2.00, and you get 1 item.

Functions Dealing with Arrays

1.is_array
check whether a variable is an array
if(is_array($array)
{
Return true;
}
Else
Return false;

2. Count
count all the elements in the top level of an array.
echo count($fred);

3. sort
Sorting is so common that PHP provides a built-in function.
sort($fred);

4. shuffle
elements of an array to be put in random order
shuffle($cards);

5. explode
Sveral items separated by a single character (or string of characters) and then place each of these
items into an array.
<?php
$temp = explode('***', "A***sentence***with***asterisks");
print_r($temp);
?>
Output:
Array
(
[0] => A
[1] => sentence
[2] => with
[3] => asterisks
)

6. Reset
It reset the array pointer to the first elemet of the array.
reset($fred); // Throw away return value
MAHESH BABU ASSISTANT PROFESSOR
MAHESH BABU ASSISTANT PROFESSOR

$item = reset($fred); // Keep first element of the array in $item

7. End
It moves the pointer to the end of the array.
end($fred);
$item = end($fred);

8. Unset
The unset function is used to remove particular element from the array. For example consider
following PHP document

Example:
<?php
$mylist=array(10,20,30,40,50);
unset($mylist[1]);
for($i=0;$i<=4;$i++)
{
print $mylist[$i];
print “”;
}
?>

Sequential Access to Array Elements


 The array element references start at the first element and every array maintains an internal
pointer using which the next element can be easily accessible. This helps to access the array
elements in sequential manner.
 The pointer current is used to point to the current element in the array. Using the next
function the next subsequent element can be accessed. Following PHP code illustrates this
idea .

PHP Program
<?php
$mylist=array(“Hello”,”PHP”,”You”,”Are”,”Wonderful!”);
$myval=current($mylist);
print(“The current value of the array is <b>$myval</b>”);
print “<br/>”;
$myval=next($mylist);
print(“The next value of the array is <b>$myval</b>”);
print “<br/>”;
$myval=next($mylist);
print(“The next value of the array is <b>$myval</b>”);
print “<br/>”;
$myval=next($mylist);
print(“The next value of the array is <b>$myval</b>”);
print “<br/>”;
$myval=next($mylist);
print(“The next value of the array is <b>$myval</b>”);
?>

1. Each
Using each function we can iterate through the array elements.

MAHESH BABU ASSISTANT PROFESSOR


MAHESH BABU ASSISTANT PROFESSOR

PHP Program
<?php
$mylist=array(“Hello”,”PHP”,”You”,”Are”,”Wonderfull!”);
while($myval=each($mylist)
{
$val=$myval[“value”];
print(“The current value of the array is <b>$val</b>”);
print “<br/>”;
}
?>

2. foreach
The foreach function is used to iterate through all the elements of the loop. The syntax of foreach
statement is as follows -
foreach($array as $value)
{
statements to be executed
}
The above code can be modified and written as follows -

PHP Program
<?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/>”;
}
?>

Sorting Arrays
 Sorting is the process in which the element of arrays in some specific order. There are two
types of ordering which are followed in sorting – ascending order and descending order.
Basically PHP uses sort function for sorting the array elements. There are some other
functions that are also available for sorting the arrays in desired manner.
 The sort function sorts the array based on the values. After applying the sort function this
function assigns new keys to the values of the array.Following PHP document illustrates
these functions -

PHP Program
<?php
$A=array(“A” => “Supriya”, “B” => “Monika”, “C” => “Kumar”, “D” => “Archana”);
print “<b> Original Array:</b><br/>”;
foreach($A as $key => $value)
print (“[$key] => $value <br/>”);
sort($A);
print “<br/>”;
print “<b> Sorted
Array:<b><br/>”: foreach($A as
$key => $value) print (“[$key] =>
$value <br/>”);
?>

MAHESH BABU ASSISTANT PROFESSOR


MAHESH BABU ASSISTANT PROFESSOR

 The asort() function sorts an array by the values. But the original keys are kept.
 The ksort() function sorts the array by keys but each value’s original key is retained.

Example Programs:
1. Use an array to store student information such as enrolment no, name, semester and
percentage. Output the data to a web page using PHP.

Sol:
<html>
<head></head>
<body>
<?php
$a=array(array(10,”AAA”,”II”,60),array(20,”BBB”,”III”,80),array(30,”CCC”,”IV”,40));
echo “<table border=’1’>”;
echo “<tr>”;
echo “<td>ENo</td><td>Name</td><td>Sem</td><td>Marks</td>”;
echo “<tr/>”;
for($i=0;$i<3;$i++)
{
echo “<tr>”;
for($j=0;$j<4;$j++)
{
echo”<td>”;
echo $a[$i]{$j];
echo”</td>”;
}
echo “</tr>”;
}
echo “</table>”;
?>
</body>
</html>

Strings
PHP String Manipulation
PHP provides a rich set of functions to manipulate strings. In this topic, we will discuss some
common functions used by PHP developers to remove spaces from a string, count the number of
characters of a string, convert a string to contain upper case or lower case letters, split a string or
join strings, get substrings from a string, compare strings, search for a substring in a string, and
replace and old substring with a new substring of a string, etc.

trim, ltrim, and rtrim functions


trim, ltrim, and rtrim functions are used to remove space from a string.
-trim(String) removes leading and trailing space from the string.
-ltrim(String) removes leading spaces.
-rtrim(String) removes trailing spaces.

strlen() function
The strlen(String) function is used to count the number of characters of a string.
strtolower, strtoupper, ucfirst, ucwords function
The strtolower, strtoupper, ucfirst, and ucwords functions are used to change change cases of a
string:
MAHESH BABU ASSISTANT PROFESSOR
MAHESH BABU ASSISTANT PROFESSOR

 strtolower(String) changes a string to lowercase.


 strtoupper(String) changes a string to uppercase.
 ucfirst(String) capitalizes the first character of a string.
 ucwords(String) capitalizes the first character of each word in a string.

strcmp() and strcasecmp() functions


The strcmp(String1,String2) compares String1 with String2. It returns less than zero if String1 is
less than String2. If String1 is greater than String2 it return greater than zero. If both strings are
equal, it returns 0.This function compares two strings in case-sensitive manner. If you want to
compare two strings without case-sensitivity, you can use strcasecmp() instead.

split() and join() functions


The split(Separator_char, String) function is used to split a string in to an array of strings by a
separating character.

substr() function
The substr() method has two main forms:
 substr(String, Start) returns a substring from the Start position to the end of the string.
 substr(String,Start,Length) returns a substring from the Start position in which the length of
the substring is equal to Length.

strpos() and str_replace() functions


The strpos(String, String_to_find) returns the position of the String_to_find in the String. The
str_replace(Old_string,New_string,String) is used to replace the Old_string with the New_string.

Example:
<?php
echo strlen("Hello world!")."<br>";
echo str_word_count("Hello world!")."<br>";
echo strrev("Hello world!")."<br>";
echo strpos("Hello world!", "world")."<br>";
echo str_replace("world", "Dolly", "Hello world!")."<br>";
echo substr("Hello World",2)."<br>";
$arr=split("l","Hello")
Echo $arr[0]."<br>";
echo strtoupper("Hello")."<br>";
echo strtolower("HELLO")."<br>";
echo trim(" Hello")."<br>";
?>

Output:
12
2
!dlrow olleH
6
Hello Dolly!
llo World
He
HELLO
hello
Hello
Note that the variable s is assigned with the string. The string is given in double quotes. Then using
the echo whatever string is stored in the variable s is displayed on the console.
MAHESH BABU ASSISTANT PROFESSOR
MAHESH BABU ASSISTANT PROFESSOR

Functions
The functions in PHP are very much similar to the functions in C. Let us discuss it in details
-
General Characteristics of Functions
 The syntax of the function definition is as follows -
function name_of_function(parameter list)
{
statements to be executed in function-name
.....
.....
}
 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 Program
<?php
function myfun()
{
print “<i> This statement is in myfun()</i>”;
}
print “<b> The Function Demo Program</b>”;
print “<br/>”;
myfun();
?>
 The return statement is used for returning some value from the function body. Following
PHP script shows this idea.

PHP Program
<?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();
?>

Parameters
 The parameter that we pass to the function during the call is called the actual parameter.
These parameter are generally the expressions.
 The parameters that we pass to the function while defining it is called the formal
parameter. 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.

MAHESH BABU ASSISTANT PROFESSOR


MAHESH BABU ASSISTANT PROFESSOR

 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

PHP Program
<?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);
?>

There are two ways to pass parameters by reference.

1. Add & at the beginning of the name of the actual parameter. For example -
<?php
function add_some_extra($string)
{
$string=’This is a string”;
$str1=&$str;//adding & at the beginning of the name of actual paramater.
print “Before function call: $str<br/>”;
add_some_extra($str1);
print “After function call: $str<br/>”;
?>

2. Add & to actual parameter in the function call. For example -


<?php
function add_some_extra(&$string)
{
$string = “This string is replaced”;
}
$str=”This is a string”;
print “Before function call :$str<br/>”;
add_some_extra($str);
print “After function call:$str<br/>”;
?>

SCOPE OF THE VARIABLES:


In PHP the scope of the variable is local. That means we can define a variable within a function and
by the same name another variable can be defined outside the function. These two variables are
considered to be different entities.
Example:
<?php
function myfun()
{
$a=10;
MAHESH BABU ASSISTANT PROFESSOR
MAHESH BABU ASSISTANT PROFESSOR

print “The value of a = $a”;


}
myfun();
print “<br>”;
$a=20;
print “the value of a=$a”;
?>
Output:
The value of a =10
The value of a =20
We can define the global variable also. Following is the PHP script
<?php
$a=10;
function myfun()
{
global $a;
$a+=10;
print “The value of a=$a”;
}
myfun();
print “<br>”;
$a=$a-5;
print “the value of a =$a”;
?>
Output

The value of a = 20
The value of a =15

LIFETIME OF THE VARIABLES:


The lifetime of a variable can be defined as the time from which it is used first to the end of
function execution. In PHP the static variable is used to remember the previous values.
The lifetime of static variable is the time when the variable if first used and it ends when the script
terminates its execution.
For the declaration of the static variable the keyword static variable, the keyword static is used.

function myfun()
{
static $count = 0;
count ++;
print “The number of times you have visited this page is $count <br/>”;
}

FUNCTION
Functions are group of statements that can perform a task

Defining a Function
The general syntax for a function is:
function function_name([parameter [, ...]])
{
// Statements
}
• A definition starts with the word function.
MAHESH BABU ASSISTANT PROFESSOR
MAHESH BABU ASSISTANT PROFESSOR

• A name follows, which must start with a letter or underscore, followed by


any number of letters, numbers, or underscores.
• The parentheses are required.
• One or more parameters, separated by commas, are optional.

PHP Functions - Return values


Functions can also return the valuese to the point where they have called.
Return statement is used to return the value.
Syntax:
function func_name()
{
….
return $variable;
}
echo func_name();

Example:
<?php
function add($x,$y)
{
$total=$x+$y; return $total;
}
echo "1 + 16 = " . add(1,16);
?>

Call by Value:
The changes made in the formal arguments will not be reflected back to the actual arguments.
Example:
Swap Numbers PHP Example (Call by value)
<?php
$num1=10;
$num2=20;
echo "Numbers before swapping:<br/>"; echo "Num1=".$num1;
echo "<br/>Num2=".$num2;
swap($num1,$num2); //call by value
function swap($n1,$n2)
{
$temp=$n1;
$n1=$n2;
$n2=$temp;
echo "<br/><br/>Numbers after swapping:<br/>";
echo "Num1=".$n1;
echo "<br/>Num2=".$n2;
}
?>

Call by Reference:
The changes made in the formal arguments will be reflected back to the actual arguments.

Swap Numbers PHP Example (Call by Reference)


<?php
$num1=10;
$num2=20;
MAHESH BABU ASSISTANT PROFESSOR
MAHESH BABU ASSISTANT PROFESSOR

echo "Numbers before swapping:<br/>"; echo "Num1=".$num1;


echo "<br/>Num2=".$num2;
swap($num1,$num2);
function swap(&$n1,&$n2) //Call by reference
{
$temp=$n1;
$n1=$n2;
$n2=$temp;
echo "<br/><br/>Numbers after swapping:<br/>";
echo "Num1=".$n1;
echo "<br/>Num2=".$n2;
}
?>

Recursive Function:
A recursive function is a function that calls itself during its execution. This enables the function to
repeat itself several times, outputting the result and the end of each iteration.
Example:

<?php
function factorial($number)
{
if ($number == 0)
return 1;
return $number * factorial($number - 1);
}
echo factorial(5);
?>
Output:
120

FILE HANDLING:
PHP is known as a server side scripting language. Hence file handling functions suc as create, read,
write, append are some file related operations that are supported by PHP.
Opening and closing files:
The first step in file handling is opening of the file.
It takes two parameters- The first parameter of this function contains the name of the file to be
opened and the second parameter specifies in which mode the file should be opened.

Modes Description
r Read only. Starts reading from the beginning of the file.
r+ Read/Write. Starts reading from the beginning of the file
w Write only. Opens and clears the contents of the file; or creates a new file if it
is not created.
w+ Read/ Write. Opens and clears the contents of the file; or creates a new file if
it is not created.
a Append. Opens and writes to the end of the file or creates a new file of it is
not created.
a+ Read/Append. Preserves the file content by writing to the end of the file.

MAHESH BABU ASSISTANT PROFESSOR


MAHESH BABU ASSISTANT PROFESSOR

For example:
$my_file=’file.txt’;
$file_handle=fopen($my_file,’a’) or die(‘Cannot open file: ’.$my_file);
The fopen function returns TRUE if the required file is opened.

Reading from file:


The fread is the function which is used to read the file. It takes two parameters. The first parameter
is the handle to the file and the second parameter is the number of bytes to be read. The filesize is
the function which takes the filename as the parameter.

For example: $mystring = fread($file_handle, filesize(“file.txt”));

There is another function named file_get_contents using which the contents of the file can be
obtained.
The fgets() function is used to read a single line from the file. For example, following code displays
the contents of the file line by line.
while(!feof($file_handle))
{
echo fgets($file_handle).”<br/>”;
}

Example Reading a file with fgets


<?php
$fh = fopen("testfile.txt", 'r') or
die("File does not exist or you lack permission to open it");
$line = fgets($fh);
fclose($fh);
echo $line;
?>

Output:
Line

Example - Reading a file with fread


<?php
$fh = fopen("testfile.txt", 'r') or
die("File does not exist or you lack permission to open it");
$text = fread($fh, 3);
fclose($fh);
echo $text;
?>

Output:
lin

Exercise: Write a PHP program to read a text file line by line and to display it on screen.

Solution:
Step-1: Create a input file Myfile.txt as follows.
Hello
everybody
how are
you?
MAHESH BABU ASSISTANT PROFESSOR
MAHESH BABU ASSISTANT PROFESSOR

Step-2: Create a PHP script for reading the input file line by line as follows.
<?php
$file = fopen(“Myfile.txt”,”r”)
while(!feof($file))
{
echo fgets($file).”<br/>”;
}
fclose($file);
?>
Writing to a file:
The fwrite is the function which is used to write the contents to the file. It takes two parameters –
The first parameter is the handle to the file and the second parameter is the number of bytes to be
written. For example -
$written_string = fread($file_handle, $my_data);
Locking Files:
Multiple PHP scripts can access the same file at a time. But this causes conflict problems. That
means there can be the situation in which one script is reading the file and at the same time the other
script is writing to that file. Sometimes there can be a situation in which two scripts are trying to
write different data to the same file. These are totally undesirable in the file handling technique. The
solution to this problem is to lock the file when one script is accessing it. Due to locking of the file,
simultaneous access can be avoided. The PHP uses flock function for locking the files.
Syntax of flock is
flock(file, lock, block)
where
file – name of the file which needs to be accessed.
Lock- kind of lock being used. Possible values
are:
LOCK-SH – Shared Lock(reader). Allow other processes to access the file
LOCK_EX – Exclusive Lock(writer). Prevent other processes from accessing the file.
LOCK_UN – Release a shared or exclusive lock
LOCK_NB- Avoids blocking other processes while locking block is optional parameter.
Example
<?php
$file = fopen(“myfile.txt”,”w+”);
flock($file, LOCK_EX)// exclusive lock
fwrite($file, “I am writing this line to file”);
flock($file,LOCK_UN);//release lock
fclose($file);
?>
Copying Files
We can copy one file into another file using copy() function.
Syntax:
Copy(‘source file’,’destination file’);

Copying a file
<?php // copyfile.php
copy('testfile.txt', 'testfile2.txt') or die("Could not copy file");
echo "File successfully copied to 'testfile2.txt'";
?>
MAHESH BABU ASSISTANT PROFESSOR
MAHESH BABU ASSISTANT PROFESSOR

If you check your folder again, you’ll see that you now have the new file testfile2.txt in
it. By the way, if you don’t want your programs to exit on a failed copy attempt, you
could try the alternate syntax.

Moving a File
To move a file, rename it with the rename function.

Example
<?php // movefile.php
rename('testfile2.txt', 'testfile2.new');
else echo "File successfully renamed to 'testfile2.new'";
?>
You can use the rename function on directories, too. To avoid any warning messages, if
the original file doesn’t exist, you can call the file_exists function first to check.

Deleting a File
Deleting a file is just a matter of using the unlink function to remove it from the filesystem,
as in Example 7-10.
Example 7-10. Deleting a file
<?php // deletefile.php
if (!unlink('testfile2.new')) echo "Could not delete file";
else echo "File 'testfile2.new' successfully deleted";
?>

Form Handling
PHP is used for form handling. For that purpose the simple form can be desgined 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 obtain the form via the
$_GET array variable. For forms that are submitted via “POST” method we obtain the form via the
$_POST array variable.
Exercise:Create HTML form with one text box to get user’s name. Also write PHP code to
show length of entered name when, the HTML form is submitted.
Solution:
The $_GET Function

 The built-in $_GET function is used to collect values from a form sent with method="get"
 Information sent from a form with the GET method is visible to everyone (it will be
displayed in the browser's URL) and has limits on the amount of information to send (max.
100 characters)
 This method should not be used when sending passwords or other sensitive information.
However, because the variables are displayed in the URL, it is possible to bookmark the
page
 The get method is not suitable for large variable values; the value cannot exceed 100
characters

The $_POST Function


 The built-in $_POST function is used to collect values from a form sent with method="post"

MAHESH BABU ASSISTANT PROFESSOR


MAHESH BABU ASSISTANT PROFESSOR

 Information sent from a form with the POST method is invisible to others and has no limits
on the amount of information to send
 However, there is an 8 Mb max size for the POST method, by default (can be changed by
setting the post_max_size in the php.ini file)

The $_GET Function Example


Form1.html
<html>
<body>
/* form submitted using ‘get’ method, action specifies next page which is to be loaded when button
is clicked*/
<form action="welcome.php" method="get">
textbox is to take user input Name: <input type="text" name="fname" />
Age: <input type="text" name="age" />
Submit button is to submit the value <input type="submit" />
</form>
</body>
</html>

welcome.php

<html>
<body>
$_GET to receive the data sent from Form1.html Welcome <?php echo $_GET["fname"]; ?>.<br />
You are <?php echo $_GET["age"]; ?> years old!
</body>
</html>
The $_ POST Function Example

form1.html

<html>
<body>
/* form submitted using ‘post’ method, action specifies next page which is to be loaded when
button is clicked */ <form action="welcome1.php" method="post">
textbox is to take user input Name: <input type="text" name="fname" /> Age: <input type="text"
name="age" />
Submit button is to submit the value to next page <input type="submit" />
</form>
</body>
</html>

welcome1.php

<html>
<body>
$_GET to receive the data sent from form1.html Welcome <?php echo $_POST["fname"]; ?>.<br
/>
You are <?php echo $_POST["age"]; ?> years old!
</body>
</html>

MAHESH BABU ASSISTANT PROFESSOR


MAHESH BABU ASSISTANT PROFESSOR

Step 1:
<!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 the submitted name is as written below:
<?php
print “The name is”;
print $_POST[‘myname’];
$len=strlen($_POST[‘myname’]);
print $len;
?>

Exercise: Create HTML form to enter one number. Write PHP code to display the message
about number is odd or even.
Solution
Step1:The HTML form for accepting number is created as below-
<!DOCTYPE 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 odd or even is given below-
<?php
print “The number is:”;
print $_POST[“mynum”];
$a=$_POST[“mynum”]; if($a
%2==1)
print”<br/> The number is odd”;
else
print”<br/> The number is even”;
?>

MAHESH BABU ASSISTANT PROFESSOR


MAHESH BABU ASSISTANT PROFESSOR

EXERCISE: Create a form containing information sl.no,title of the


book,publishers,quantity,price read the data from the form and display it using PHP script.
SOLUTION:
Step 1: Create an HTML page for inputting the data.
HTML Document[input.html]
<!doctype html>
<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>
</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>
<tr>
<td>Quantity</td>
<td><input type= “text” name=”Qty”></td>
</tr>
<tr>
<td><input type= “submit” name=”submit”></td>
<td><input type= “submit” name=”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 :
formdemo.php:
<html>
<head>
<title>Book Information</title>
</head>
<body>
<?php
$Bname=$_POST[‘BName’];
MAHESH BABU ASSISTANT PROFESSOR
MAHESH BABU ASSISTANT PROFESSOR

$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 print (“$Price”);?></td>
<td><?php print (“$Qty”);?></td>
</tr>
</table>
</center>
</body>
</html>

Step 3: Open some suitable web browser and enter the address for the HTML file which you have
created in step 1. Now click on the submit button and the PHP file will be invoked. The output will
then be as follows.
Exercise : 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
<!DOCTYPE html>
<html>
<head>
<title>PHP Demo</title>
</head>
<body>
<form method= “post” action= “getdata.php”>
<input type= “text” name= “num” />
<input type = “submit” value= “Submit” />
</form>
</body>
</html>
<?php
//getting values from HTML form
$n=intval($_POST[‘num’]);
$sum=0;
for($i=1;$i<=$n;$i++)
$sum=$sum+i;
echo “The sum of all numbers from 1 to “.$n.”is”.$sum;?>

MAHESH BABU ASSISTANT PROFESSOR


MAHESH BABU ASSISTANT PROFESSOR

PHP and MySQL:


Benefits of using PHP and 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 the 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 becomes portable. Since HTML can be
embedded within the PHP, there is no need to write seperate 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 PHP has got the support from several content management programs such sa wrodpress,
Joomla, Drupal and so on. It has got a strong support for developing e-commerce applications using
the technologies such as Ecommerce, Drupal and so on. The most popular web sites being
developed using PHP and MySQL technologies are:
1. Facebook
2. WordPress
3. Wikipedia

Structured Query Language(SQL)


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).

Connecting PHP to MySQL:


The PHP function mysql_connect connects to the MySQL Server. There are three parameters that
can be passed to this function. For example-
mysql_connect(“localhost”, “root”, “mypassword”) or die(mysql_error());
where
localhost- Local host on which the MySQL is running
root- Root
mypassword- Password
The database can be selected by using the command mysql_selecet_db.
For example:
mysql_select_db(“test”) will select the database named test.

Requesting MySQL Operations:

1. Creating Database:
We can create a database using the function mysql_query. The mysql_error() function is used to get
the error messages if any command gets failed.
mysql_query function in php is used to pass a sql query to myql 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.
Example
MAHESH BABU ASSISTANT PROFESSOR
MAHESH BABU ASSISTANT PROFESSOR

mysql_query(“CREATE DATABASE mydb”, $con)


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”, “password”);
The mysql_close() function is used to close the database connection.
Syntax:
mysql_close(Connection)
PHP program for Creating the database:
<?php
$conn=mysql_connect(“localhost”, “root”, “password”); //Make a sql connection
if(!$conn)
{
die(‘error in connection’.mysql_error());
}
if(mysql_query(“CREATE DATABASE mydb”, $conn)) //Create a database
{
print “Database Created”;
}
else
{
print “Error Creating database:”.mysql_error();
}
mysql_close($conn); //closing the database
?>

2.Selecting the 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
$conn=mysql_connect(“localhost:3306/mydb”, “root”, “mypassword”);
if(!$conn)
{die(‘error in connection’.mysql_error());
}
//Select a database
mysql_select_db(“mydb”, $conn);
mysql_close($conn); //closing the database
?>

3. Counting Number of Rows:


The numbe rof rows present in the table can be obtained using mysql_num_rows functions.
Syntax:
int mysql_num_rows(resource $result)
This returns number of rows in result on success, or NULL on error.
Example:
<?php
MAHESH BABU ASSISTANT PROFESSOR
MAHESH BABU ASSISTANT PROFESSOR

//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
?>

4. Counting number of fields:


The mysql_num_fields() is used to get number of fields of the table.
Syntax:
mysql_num_fields(resource_name)
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);
mysql_close($conn); //closing the database
?>

5. Creating Table:
Before creating the table a database must be created and within which the table can be created. Note
that before creating a table, desired database must be selected.
Example:
<?php
$conn=mysql_connect(“localhost”, “root”, “password”); //Make a sql connection
if(!$conn)
{die(‘error in connection’.mysql_error());
}
if(mysql_query(“CREATE DATABASE mydb”, $conn)) //Create a database
{print “Database Created”;
}
else
{print “Error Creating database:”.mysql_error();
}
mysql_select_db(“mydb”,$conn); // Before creating a table, database must be selected.
$query=”CREATE TABLE my_table (id INT(4), name VARCHAR(20))”;
mysql_query($query, $conn);
mysql_close($conn); //closing the database
?>

MAHESH BABU ASSISTANT PROFESSOR


MAHESH BABU ASSISTANT PROFESSOR

6. Inserting Data in table:


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
Here is a PHP script in which insert query is used to insert two records in the table
Example:
<?php
//Make a SQL Connection
$conn=mysql_connect(“localhost”, “root”, “password”);
if(!$conn)
{
die(‘error in connection’.mysql_error());
}
mysql_select_db(“mydb”,$conn);
$query= “INSERT INTO my_table(id, name) VALUES (1, ‘SHILPA’)”;
mysql_query($query, $conn);
$query= “INSERT INTO my_table(id, name) VALUES (2, ‘MONIKA’)”;
mysql_query($query, $conn);
mysql_close($conn); //closing the database
?>
Sometimes values that can be inserted in the table can be obtained from someother 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-
Example:
<?php
//Make a SQL Connection
$conn=mysql_connect(“localhost”, “root”, “password”);
if(!$conn)
{
die(‘error in connection’.mysql_error());
}
mysql_select_db(“mydb”,$conn);
$query= “INSERT INTO my_table(id, name) VALUES (‘$_POST[MyId]’, ‘$_POST[MyName]’)”;
mysql_query($query, $conn);
mysql_close($conn); //closing the database
?>

7. Displaying or Retrieving Records:


For displaying the records present in the database table, we use SELECT query. For Example
// Execution of Query for displaying the data
$result=mysql_query(“SELECT * FROM my_table”);
The above execution returns a result handle. Then the mysql_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)
PHP Script for Displaying records:
<?php
//Make a SQL Connection
$conn=mysql_connect(“localhost”, “root”, “password”);
if(!$conn)
{
die(‘error in connection’.mysql_error());
}
MAHESH BABU ASSISTANT PROFESSOR
MAHESH BABU ASSISTANT PROFESSOR

mysql_select_db(“mydb”,$conn);
//Execution of Query for dsiplaying 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
echo “<br/>”;
}
mysql_close($conn); //closing the database
?>

8. Finding the number of affected rows:


The mysql_affected_rows query is used to get number of affected rows in previous MySQL
operation such as INSERT, DELETE, UPDATE queries.

Syntax:
mysql_affected_rows(connection)
Example:
<?php
//Make a SQL Connection
$conn=mysql_connect(“localhost”, “root”, “password”);
if(!$conn)
{
die(‘error in connection’.mysql_error());
}
mysql_select_db(“mydb”,$conn);
$query= “INSERT INTO my_table(id, name) VALUES (1, ‘SHILPA’)”;
mysql_query($query, $conn);
$query= “INSERT INTO my_table(id, name) VALUES (2, ‘MONIKA’)”;
mysql_query($query, $conn);
echo “Number of rows affected are:”.mysql_affected_rows();
mysql_close($conn); //closing the database
?>
MySQL Functions:

mysql_connect():
This function opens a link to a MySQL server on the specified host (in this case it's localhost) along
with a username (root) and password (q1w2e3r4/). The result of the connection is stored in the
variable $db.

mysql_select_db():
This tells PHP that any queries we make are against the mydb database.

mysql_query():
Using the database connection identifier, it sends a line of SQL to the MySQL server to be
processed. The results that are returned are stored in the variable $result.

mysql_result():
This is used to display the values of fields from our query. Using $result, we go to the first row,
which is numbered 0, and display the value of the specified fields.

mysql_result($result,0,"position")):
This should be treated as a string and printed.
MAHESH BABU ASSISTANT PROFESSOR
MAHESH BABU ASSISTANT PROFESSOR

COOKIES

Introduction to cookies:
Cookie is a small file that server embeds in the user’s machine. 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 browsers and server communications.

PHP Support for Cookies:


PHP can be used to create and retrieve the cookies. The cookie can be set in PHP using the
functions called setcookie().
The syntax for setcookie is -
setcookie(name, value,expire_period, path, domain)

Example PHP program to set cookie:


<?php
$cookie_period=time()+60*60*24*30;
setcookie(“Myname”, “Monika”, $cookie_period);
?>
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.

Example: [CookieRead.php]
<html>
<head><title>Reading cookies</title>
<body>
<?php
if(isset($_COOKIE[“Myname”]))
echo “<h3>Welcome”.$_COOKIE[“Myname”]. “!!!</h3>”;
else
echo “Welcome guest!”;
?>
</body>
</html>
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.

Exercise: Write a PHP Script to create a new database table with 4 fields of your choice and
perform following database operations. i)insert ii)update iii)Delete
Solution:
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.

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());
MAHESH BABU ASSISTANT PROFESSOR
MAHESH BABU ASSISTANT PROFESSOR

print”<br/>”;
echo “Table Created”;
//Insert a row of information into tabele “example”
mysql_query(“INSERT INTO mytable(name,phone,emailId)
VALUES(‘abcd’,’1111’,’[email protected]’)”) or die (mysql_error());
mysql_query(“INSERT INTO mytable(name,phone,emailId)
VALUES(‘xyz’,’2222’,’[email protected]’)”) or die (mysql_error());
mysql_query(“INSERT INTO mytable(name,phone,emailId)
VALUES(‘Kumar,’3333’,’[email protected]’)”) or die (mysql_error());
print”<br/>”;
echo “Data Inserted”;
$result=mysql_query(“SELECT * from mytable”)
or die(mysql_error());
print”<br/>”;
print”<b> User Databse</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>”;
$result=mysql_query(“UPDATE mytable SET phone=”5555” where phone=”2222”)
or die(mysql_error());
print”<br/>”;
echo “Data Updated”;
$result=mysql_query(“SELECT * from mytable”)
or die(mysql_error());
print”<br/>”;
print”<b> User Datbase</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 contentsof 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>”;
MAHESH BABU ASSISTANT PROFESSOR
MAHESH BABU ASSISTANT PROFESSOR

}
echo “<table>”;
result=mysql_query(“DELETE from mytable where phone=”3333”)
or die(mysql_error());
print”<br/>”;
echo “Data Deleted”;
$result=mysql_query(“SELECT * from mytable”)
or die(mysql_error());
print”<br/>”;
print”<b> User Datbase</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 contentsof 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>”;

Exercise: 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

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>
</body>
</html>

MAHESH BABU ASSISTANT PROFESSOR


MAHESH BABU ASSISTANT PROFESSOR

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 SQL Connection
$conn=mysql_connect(“localhost”, “root”, “”);
if(!$conn)
{
die(‘error in connection’.mysql_error());
}
mysql_select_db(“mydb”,$conn);
$reg_no = intval($_POST[‘reg_no’]);
$result=mysql_query(“SELECT REG_NO, STATUS FROM result_table where
REG_NO=$reg_no”);
while($row=mysql_fetch_array($result))
{
echo $row[‘REG_NO’]. “is”. $row[‘STATUS’];
echo “<br/>”;
}
mysql_close($conn);
?>

Step 4: Load the HTML form created in Step 2 and click the submit button by entering some
registration number

Exercise : Write a PHP program to delete a record from the result_table:


Solution:
<?php
//Make a SQL Connection
$conn=mysql_connect(“localhost”, “root”, “”);
if(!$conn)
{
die(‘error in connection’.mysql_error());
}
mysql_select_db(“mydb”,$conn);
$reg_no = intval($_POST[‘reg_no’]);
$result=mysql_query(“DELETE FROM result_table where REG_NO=$reg_no”);
while($row=mysql_fetch_array($result))
{
echo $row[‘REG_NO’]. “is”. $row[‘STATUS’];
echo “<br/>”;
}
mysql_close($conn);
?>

Exercise: Write a user defined function ‘CalculateInterest’ using PHP to find the simple
interest to be paid for a loan amount. Read the loan amount, the number of years and the 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.
Solution:
Step 1:
MAHESH BABU ASSISTANT PROFESSOR
MAHESH BABU ASSISTANT PROFESSOR

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 6.9
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()
{
<?php
//Make a SQL Connection
$conn=mysql_connect(“localhost”, “root”, “”);
if(!$conn)
{
die(‘error in connection’.mysql_error());
}
mysql_select_db(“mydb”,$conn);
$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);
return $interest;
}
print “Simple Interest =”.CalculateInterest();
}

Exercise: Consider a table PRODUCT_DETAILS with PID, PNAME and UNIT_PRICE.


Write HTML form to accept PID and QUANTITY_REQUIRED from the user and dsiplay
the total amount to be paid in another textbox. Get the unit price for given PID from a
database table.
Solution:
Bill.php
<!DOCTYPE html>
<html>
<head>
<title>PHP Demo</title>
</head>
<body>
<form method= “post”>
<input type= “text” name= “PRODUCT_ID” />
<input type= “text” name= “QUANTITY” />
<input type = “submit” value= “Submit” />
<?php
//getting values from HTML Form
$id=intval($POST[‘PRODUCT_ID’]);
$qty=intval($POST[‘QUANTITY’]);
//Make a SQL Connection
$conn=mysql_connect(“localhost”, “root”, “”);

MAHESH BABU ASSISTANT PROFESSOR


MAHESH BABU ASSISTANT PROFESSOR

if(!$conn)
{
die(‘error in connection’.mysql_error());
}
mysql_select_db(“mydb”,$conn);
$result=mysql_query(“SELECT UNIT_PRICE FROM product_table where PID=$id”);
$row=mysql_fetch_array($result);
$price=$row[‘UNIT_PRICE’];
$total=$price*$qty;
mysql_close($conn);
?>
<input type= “text” name= “amount” value=”<?php echo @$total;?>”/>
</form>
</body>
</html>

Exercise:Write a Script to insert and delete record from database.

Index.html:
<!DOCTYPE html>
<body bgcolor="#bbffa0">
<center>
<br><h1>Database Application<h1>
<h3>You can Insert, delete and search your data</h3>
<a href="insert.php">Insert</a>
<br><br>
<a href="delete.php">Delete</a>
<br><br>
</center>
<body>

Insert.php:
<!doctype html>
<body bgcolor="#aacb00">
<form method="POST" action="insert_process.php">
<center>
<h1>Insert your Details here</h1>
<h2>
Name:
<br><input type="text" name="name">
<br>
<br>
Register Number:
<br><input type="text" name="reg">
<br><br>
Age:
<br> <input type="text" name="age">
<br><br><br>
<input type="submit" value="Insert" name="insert">
<br><br>
</h2>
</center>
</form>
MAHESH BABU ASSISTANT PROFESSOR
MAHESH BABU ASSISTANT PROFESSOR

</body>
Insertprocess.php
</html>
<?php
// Create connection
$conn = new mysqli("localhost", "root", "", "itessentials");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$name=$_POST['name'];
$regno=$_POST['reg'];
$age=$_POST['age'];
$sql = "INSERT INTO student (name, reg_no, age)VALUES ('$name','$regno','$age')";
if ($conn->query($sql) === TRUE) {
echo "Inserted successfully";
}
?>
<html>
<br>
<a href="database.html">Goto Home</a>
</html>
Delete.php:
<!DOCTYPE html>
<body bgcolor="#bbccf0">
<br>
<center>
<h1>Delete Your Data</h1><h2>
<form method="POST" action="del_process.php">
Enter the Register no :<input type="text" name="reg">
<br>
<br>
<input type="submit" value="DeleteData"></h2>
</center>
</form>
</body>
</html>
Deleteprocess.php:
<?php
$conn = new mysqli("localhost", "root", "", "itessentials");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$regno=$_POST["reg"];
$sql = "DELETE FROM student WHERE reg_no=$regno";
if ($conn->query($sql) === TRUE) {
echo "Record Deleted successfully";
}
?>
<html><br>
<a href="database.html">Goto Home</a>
</html>
MAHESH BABU ASSISTANT PROFESSOR
MAHESH BABU ASSISTANT PROFESSOR

Exercise:Write a database application to insert and search the data.


<!doctype html>
<html lang="en">
<head>
<title>Simple Information Reterival System</title>
</head>
<body background="lighthouse.jpg">
<h1><center>Simple Information Reterival System</center></h1>
<center><ul>
<h2><li><a href="create.php"><strong>Create</strong></a> - add a user</h2></li>
<h2><li><a href="search.php"><strong>Read</strong></a> - find a user</h2></li>
</ul></center>

</body>
</html>
Create.php:
<html>
<body bgcolor="cyan">
<h2>Add a user</h2>

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


<label for="firstname">First Name</label><br>
<input type="text" name="firstname" id="firstname" required><br>
<label for="lastname">Last Name</label><br>
<input type="text" name="lastname" id="lastname" required><br>
<label for="dob">Date of Birth</label><br>
<input type="text" name="dob" id="dob" required><br>
<label for="email">Email Address</label><br>
<input type="email" name="email" id="email" required><br>
<label for="age">Age</label><br>
<input type="number" name="age" id="age" required><br>
<label for="location">Location</label><br>
<input type="text" name="location" id="location" required><br><br>
<input type="submit" name="submit" value="Submit">
</form>
*All feilds are mandate.<br>
<a href="index.php">Back to home</a>
</body>
</html>
Insert.php:
<!dhtml>
<body bgcolor="pink">
<?php
$conn = new mysqli("localhost","root","","itessentials");

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}$firstName=$_POST['firstname'];
$lastName=$_POST['lastname'];
$dob=$_POST['dob'];
$email=$_POST['email'];
MAHESH BABU ASSISTANT PROFESSOR
MAHESH BABU ASSISTANT PROFESSOR

$age=$_POST['age'];
$location=$_POST['location'];
$query="INSERT INTO user_details (first_name, last_name,dob, email, age,location) VALUES (?,
?,?,?,?,?)";
$stmt = mysqli_prepare($conn,$query); mysqli_stmt_bind_param($stmt,"sssiss",$firstName,
$lastName,$dob, $email,$age,$location); mysqli_stmt_execute($stmt);

echo "<h2>Thank You ".$firstName ."You are Registered Successfully</h2>";


echo "<a href='index.php'>Back to home</a>";
mysqli_close($conn); ?>
</body>
Search.php:
</html>
<h1>Search a User</h1>
<form method="post" action="retrieve.php">
<table><tr style="width=100%">
<td>Enter search query <input type="text" name="searchquery" id="se"><br></td></tr>
</tr></table>
<table><tr>
<td> <label for="search">Search by</label><br></td>
<td> <input type="radio" name="searchby" value="first_name" checked> First
Name<br></td>
<td> <input type="radio" name="searchby" value="last_name" > Last Name<br></td>
<td> <input type="radio" name="searchby" value="email"> Email<br></td>
<td> <input type="radio" name="searchby" value="location"> Location<br></td>
</tr> </table>
<input type="submit" name="submit" value="Submit">
</form>
Retrieve.php:
<?php
$host="localhost";
$username = "root";
$password = "";
$dbname = "itessentials";
$conn = new mysqli($host, $username, $password,$dbname);
$searchby=$_POST['searchby'];
$searchquery=$_POST['searchquery'];
$query="SELECT * FROM user_details WHERE ".$searchby ."= '". $searchquery."'";
$result=mysqli_query($conn,$query);
while($row=mysqli_fetch_array($result,MYSQLI_ASSOC)){
echo "<h1>Welcome ".$row['first_name']." ".$row['last_name']."</h1>";
echo "<h3>Age ".$row['age']."</h1>";
echo "<h3>Registered email ".$row['email']."</h1>";
echo "<h3> Location".$row['location']."</h1>";
}// Check connection
if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error);
}
mysqli_close($conn); ?>

MAHESH BABU ASSISTANT PROFESSOR

You might also like