Ite Unit 2
Ite Unit 2
INFORMATION
TECHNOLOGY ESSENTIALS
NOTES
SEMESTER III-II
MAHESH BABU
ASSISTANT PROFESSOR
CSE DEPARTMENT
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.
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.
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;
?>
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
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
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.
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.
<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>
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.
<html>
<body>
<?php
$i=10;
$j=20;
$i++;
$j++;
echo $i."<br/>";
echo $j."<br/>";
$k=$i++;
$l=++$j;
echo $k."<br/>"; echo $l;
?>
</body>
</html>
11
21
11
22
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>";
?>
Output:
0
1
1
0
<html>
<body>
<?php
$a = "Hello";
$b = $a . " Friend!";
echo $b;
echo "<br/>";
$c="Good";
$c .= " Day!";
echo $c;
?>
</body>
</html>
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
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
$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.
Syntax:
if (condition) {
code to be executed if condition is true;
}
<html>
<body>
<?php
$i=0;
/* If condition is true, statement is executed*/
if($i==0)
echo "i is 0";
?>
<body>
</html>
i is 0
Syntax:
if (condition)
{
code to be executed if condition is true;
}
else
{
code to be executed if condition is false;
}
<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>
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;
}
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;
}
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.
Syntax:
for (initialization; test condition; increment/decrement)
{
code to be executed;
}
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
Syntax:
while (condition)
{
code to be executed;
}
i is = 1
i is = 2
i is = 3
i is = 4
Syntax:
do {
code to be executed;
} while (condition );
<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>
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
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
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>
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>
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>
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>
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>
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”;
?>
</body>
</html>
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>
$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
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
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 “”;
}
?>
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.
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/>”);
?>
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.
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
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.
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.
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);
?>
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/>”;
?>
The value of a = 20
The value of a =15
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
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.
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.
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.
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/>”;
}
Output:
Line
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
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)
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>
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”;
?>
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;?>
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
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
?>
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
?>
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.
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>
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 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();
}
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>
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
</body>
</html>
Create.php:
<html>
<body bgcolor="cyan">
<h2>Add a user</h2>
// 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);