Akul PHP Practical File (Edited Version) - Page - Number
Akul PHP Practical File (Edited Version) - Page - Number
Akul PHP Practical File (Edited Version) - Page - Number
CGC Landran
Bachelor of Computer Applications
Landran, Mohali (Punjab)
(Pin- 140307)
2
INDEX
Sign &
Sr.No. Title Page No Date
Remarks
2. Error Management 5
3. Comments in PHP 6
Date :- ___/___/_____
Topic 1
What is PHP?
<html>
<body>
<?php
// Use echo to print on console echo
‚Hello World!‛;
?>
</body>
</html>
Date :- ___/___/_____
Topic 2
Error Management
Compile-time errors:
o Compile-time errors are detected by the parser while it is
compiling a script.
o The compile-time errors cannot be trapped from within the script itself
Fatal errors:
o Fatal errors are the errors that halt the execution of a script.
o The fatal errors cannot be trapped.
Recoverable errors:
o Recoverable errors that represent significant failures, but can
still be handled in a safe way.
Warnings:
o Warnings are recoverable errors that indicate a run-time fault.
o Warnings do not halt the execution of the script.
Notices:
o Notices indicate that an error condition occurred, but is not
necessarily significant.
o Notices do not halt the execution of the script
<html>
<body>
<php
echo “Hello World!;
// here ? is missing
>
</body>
</html>
Date :- ___/___/_____
Topic 3
Comments in PHP
Date :- ___/___/_____
Topic 4
$var_name = value;
8
Date :- ___/___/_____
Topic 5
<html>
<body>
<?php
$a = 25; // Numerical variable
$b = ‚Hello‛; // String variable
$c = 5.7; // Float variable echo ‚Number is :
‛.$a.‚<br/>‛; echo ‚String is : ‛.$b.‚<br/>‛; echo ‚Float value : ‛.$c;
</body>
</html>
Number is : 25
Date :- ___/___/_____
Topic 6
<html>
<body>
<?php
$x=24; // global scope
Variable y is: 59
Test variables outside the function: Variable x is: 24
Variable y is:
10
Date :- ___/___/_____
Topic 7
<html>
<body>
<?php
// Function definition function myFunction() {
static $x=45; echo $x; echo "<br/>";
$x++;
}
// Function call
myFunction(); myFunction(); myFunction(); myFunction(); myFunction();
?>
<body>
<html>
45
46
47
48
49
11
Date :- ___/___/_____
Topic 8
Example:
echo 50;
print (50);
<html>
<body>
<?php
// Use ‘print’ to print on console print "Hello world!<br>***********";
?>
</body>
</html>
Hello world!
***********
12
Date :- ___/___/_____
Topic 9
String Functions in PHP
strlen() function
strpos() function
1. strlen() function
<html>
<body>
<?php
// Displays the length of the string echo
strlen("Hello world!");
?>
</body>
</html>
12
2. strpos() function
<html>
<body>
<?php
/* Displays the position of ‘world’ in
the text ‘Hello world*/
echo strpos("Hello world!","world");
?>
</body>
</html>
Date :- ___/___/_____
Topic 10
Constant in PHP
<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>
Hello Friend
<html>
<body>
<?php
// defining constant value PI = 3.14
define(“PI”,”3.14”);
$radius=15;
$area=PI*$radius;
echo “Area=”.$area;
?>
</body>
</html>
Area = 706.5
14
Date :- ___/___/_____
Topic 11
Arithmetic Operators
+ Addition $a = 2 + 5; $a=7
- Subtraction $a = 10 - 2; $a=8
* Multiplication $a = 2 * 5; $a=10
/ Division $a = 15 / 5; $a=3
% Modulus $a = 23 % 7; $a=3.28
$a ++;
$a --;
15
<html>
<body>
<?php
// Add 20, 10 and sum is stored in $i
$i=(20 + 10);
// Subtract $i, 5 and difference is stored in $j
$j=($i - 5);
// Multiply $j, 5 and difference is stored in $j
$j=($i - 5);
// Multiply $j, 4 and result is stored in $k
$k=($j * 4);
// Divide $k, 2 and result is stored in $l
$l=($k / 2);
// Divide $l, 5 and remainder is stored in $m
$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
16
<html>
<body>
<?php
$i=10;
$j=20;
$i++;
$j++;
echo $i."<br/>"; echo $j."<br/>";
// Post increment
$k=$i++;
// Pre increment
$l=++$j;
echo $k."<br/>"; echo
?>
</body>
</html>
11
21
11
2
17
= x=y x=y
+= x+=y x=x+y
-= x-=y x=x-y
*= x*=y x=x*y
/= x/=y x=x/y
.= x.=y x=x.y
%= x%=y x=x%y
<html>
<body>
<?php
$a=5;
echo "a=".$a; echo "<br/>";
$b=10;
$b += 20;
echo "b=".$b; echo "<br/>";
$c=15;
$c -= 5;
echo "c=".$c; echo "<br/>";
$d=20;
$d *= 2; echo "d=".$d; echo "<br/>";
$e=25;
$e /= 5;
echo "e=".$e; echo "<br/>";
$f=30;
$f %= 4;
echo "f=".$f;
?>
18
</body>
</html>
<?php
$x="Hello";
$y=" ";
$z="PHP";
$n="\n";
$str=$x . $y . $z . $n;
echo $str;
?>
<?php
$x="Hello ";
$y="PHP";
$x .= $y;
echo $x;
?>
Date :- ___/___/_____
Topic 12
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>
as follows:
i is 0
20
Date :- ___/___/_____
Topic 13
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;
}
<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>
i is not 0
21
Date :- ___/___/_____
Topic 14
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;
}
<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
?>
<body>
</html>
else
echo "numbers are equal"; //Statement3
Date :- ___/___/_____
Topic 15
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;
}
<html>
<body>
<?php
$favcolor = "red";
switch ($favcolor) {
case "red":
echo "Your favorite color is red!";
break;
case "blue":
echo "Your favorite color is blue!";
break;
case "green":
echo "Your favorite color is green!";
break;
default:
echo "Your favorite color is neither red, blue, nor green!";
}
?>
</body>
</html>
Date :- ___/___/_____
Topic 16
Syntax:
<html>
<body>
<?php
/*in for loop, initialization usually declares a loop variable, condition is a Boolean
expression such that if the condition is true, loop body will be executed and after each
iteration of loop body, expression is executed which usually increase or decrease loop
variable*/
<html>
<body>
<?php
/* Multiple variables can be declared in declaration block of for loop */
for ($x=0,$y=1,$z=2;$x<=3;$x++) {
echo "x = $x, y = $y, z = $z <br>";
}
24
?>
</body>
</html>
x = 0, y = 1, z = 2
x = 1, y = 1, z = 2
x = 2, y = 1, z = 2
x = 3, y = 1, z = 2
25
Date :- ___/___/_____
Topic 17
While loop, loops through a block of code as long as the specified condition is true
Syntax:
while (condition)
{ code to be executed;
}
<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>
i is = 1
i is = 2
i is = 3
i is = 4
26
Date :- ___/___/_____
Topic 18
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;
} 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
Syntax:
function functionName()
{ code to be executed;
27
}
User Defined Function Example
<html>
<body>
<?php
// Function definition function myFunction()
{
echo "Hello world";
}
// Function call myFunction();
?>
</body>
</html>
Hello world
28
Date :- ___/___/_____
Topic 19
<html>
<body>
<?php
$num1=10;
$num2=20;
echo "Numbers before swapping:<br/>"; echo "Num1=".$num1;
echo "<br/>Num2=".$num2;
// Function call
swap($num1,$num2);
// Function definition
function swap($n1,$n2)
{
$temp=$n1;
$n1=$n2;
$n2=$temp;
echo "<br/><br/>Numbers after
swapping:<br/>"; echo "Num1=".$n1;
echo "<br/>Num2=".$n2;
}
?>
</body>
</html>
Date :- ___/___/_____
Topic 20
<html>
<body>
<?php
// Function definition function writeName($fname)
{
echo $fname . " Refsnes.<br />";
}
echo "My name is ";
writeName("Kai Jim"); //Function call
echo "My sister's name is "; writeName("Hege"); // Function call
echo "My brother's name is "; writeName("Stale"); // Function call
?>
</body>
</html>
<html>
<body>
<?php
// Function definition function add($x,$y)
{
$total=$x+$y; return $total;
}
// Function call
echo "1 + 16 = " . add(1,16);
?>
</body>
</html>
1 + 16 = 17
30
Date :- ___/___/_____
Topic 21
Statements in PHP
Break statement
<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 :
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.
<html>
<body>
<?php
/* when $i value becomes 3, it will skip the particular of the loop*/
31
for($i=0;$i<=5;$i++)
{
if($i==3)
continue;
else
echo "$i ";
}
?>
</body>
</html>
01245
32
Date :- ___/___/_____
Topic 22
Superglobals
$GLOBALS
$GLOBALS is a PHP super global variable which is used to access global variables
from anywhere in the PHP script (also from within functions or methods)
PHP stores all global variables in an array called $GLOBALS[index].
The index holds the name of the variable
Example:
<html>
<body>
<?php
$a = 20;
$b = 40;
function addition()
{
$GLOBALS['c'] = $GLOBALS['a'] + $GLOBALS['b'];
}
addition(); echo $c;
?>
</body>
</html>
33
$_SERVER
$_SERVER is a PHP super global variable which holds information about headers,
paths, and script locations
Example
<html>
<body>
<?php
echo $_SERVER['PHP_SELF'];
echo "<br>";
echo $_SERVER['SERVER_NAME'];
echo "<br>";
echo $_SERVER['HTTP_HOST'];
echo "<br>";
echo $_SERVER['HTTP_USER_AGENT'];
echo "<br>";
echo $_SERVER['SCRIPT_NAME'];
?>
</body>
</html>
Date :- ___/___/_____
Topic 23
Array in PHP
<html>
<body>
<?php
/* An array $flower_shop is created with three Values - rose, daisy,orchid */
$flower_shop = array (
"rose",
"daisy", "orchid"
);
/* Values of array $flower_shop is displayed based on index. The starting index of an
array is Zero */ echo "Flowers: ".$flower_shop[0].",
".$flower_shop[1].", ".$flower_shop[2]."";
?>
</body>
</html>
<html>
<body>
<?php
/* Here rose, daisy and orchid indicates ID key and 5.00, 4.00, 2.00 indicates their values
respectively
*/
$flower_shop = array (
"rose" => "5.00",
"daisy" => "4.00",
"orchid" => "2.00"
);
// Display the array values echo "rose costs
.$flower_shop['rose'].",daisy costs ".$flower_shop['daisy'].",and orchild costs
".$flower_shop['orchild']."";
?>
</body>
</html>
<html>
<body>
<?php
$flower_shop=array("rose"=>"5.00", "daisy"=>"4.00","orchid"=>"2.00");
/* for each loop works only on arrays, and is used to loop through each key/value
pair in an array */
foreach($flower_shop as $x=>$x_value) { echo "Flower=" . $x .
", Value=" . $x_value; echo "<br>";
}
?>
</body>
</html>
<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].
", and you get ".$flower_shop['rose'][1].".<br>";
echo "daisy costs ".$flower_shop['daisy'][0].
", and you get ".$flower_shop['daisy'][1].".<br>";
echo "orchid costs ".$flower_shop['orchid'][0].
", and you get ".$flower_shop['orchid'][1].".<br>";
?>
</body>
</html>
Date :- ___/___/_____
Topic 24
PHP Forms
Scripts will interact with their clients using one of the two HTTP methods. The
methods are GET and POST
When a form is submitted using the GET method, its values are encoded directly in
the query string portion of the URL
When a form is submitted using the POST method, its values will not be displayed the
query string portion of the URL
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 built-in $_POST function is used to collect values from a form sent with
method="post"
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)
<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>
38
</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>
<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>
<html>
<head>
<title>Process the HTML form data with the POST method</title>
</head>
<body>
/* form submitted using ‘post’ method, action specifies next page which is to be
loaded when button is clicked */
<form name="myform" action="process.php" method="POST">
39
// Use ‘select’ tag to display the various options Select something from the list:
<select name="Seasons">
<option value="Spring" selected="selected">Spring</option>
<option value="Summer">Summer</option>
<option value="Autumn">Autumn</option>
<option value="Winter">Winter</option>
</select><br /><br />
Choose one:
//This will create radio buttons
<input type="radio" name="Country" value="USA" /> USA
<input type="radio" name="Country" value="Canada" /> Canada
<input type="radio" name="Country" value="Other" /> Other
<br />
Process.php
<html>
<body>
<?php
if (array_key_exists('check_submit', $_POST)) {
/*Converts the new line characters (\n) in the text area into HTML line breaks (the
<br /> tag) */
$_POST['Comments'] = nl2br($_POST['Comments']);
40
//Let's now print out the received values in the browser echo "Your name:
{$_POST['Name']}<br />";
echo "Your password: {$_POST['Password']}<br />"; echo "Your favourite season:
{$_POST['Seasons']}
<br/><br />";
echo "You are from: {$_POST['Country']}<br />"; echo "Colors you chose:
{$_POST['Colors']}<br />";
}
else
{
echo "You can't see this page without submitting the form.";
}
?>
</body>
</html>
The PHP date() function formats a timestamp to a more readable date and time
A timestamp is a sequence of characters, denoting the date and/or time at which a
certain event occurred
Some characters that are commonly used for date and time:
o d - Represents the day of the month (01 to 31)
o m - Represents a month (01 to 12)
o Y - Represents a year (in four digits)
o l (lowercase 'L') - Represents the day of the week
o h - 12-hour format of an hour with leading zeros (01 to 12)
o i - Minutes with leading zeros (00 to 59)
o s - Seconds with leading zeros (00 to 59)
o a - Lowercase Ante meridiem and Post meridiem (am or pm)
Example
<html>
<body>
<?php
// display the date in the format YYYY/MM/DD echo "Today is " . date("Y/m/d") .
"<br>";
// ‘l’ is used to display the day echo "Today is " . date("l"). "<br>";
// display the time in the format HH:MM:SS echo "The time is " . date("h:i:sa");
?>
</body>
</html>
Today is 2014/08/19
Today is Tuesday
The time is 09:13:22am
42
Date :- ___/___/_____
Topic 25
To insert values in the field, go to insert and enter the values. Then click on Go
To insert the values, go to SQL and write the query to insert the values and click on Go
43
Syntax:
Example:
To update the values, go to SQL and write the query to update the values and click on Go
Syntax:
Example:
To delete the values, go to SQL and write the query to delete the values and click on go
44
45
Date :- ___/___/_____
Topic 26
1. 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.
2. mysql_select_db():
This tells PHP that any queries we make are against the mydb database.
3. 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.
4. 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.
5. mysql_result($result,0,"position")):
This should be treated as a string and printed.
46
Date :- ___/___/_____
Topic 27
<html>
<body>
<?php
// Open MYSQL server connection
$db = mysql_connect("localhost", "root","q1w2e3r4/");
// Select the database using MYSQL server connection
mysql_select_db("mydb",$db);
/* Using the database connection identifier, it sends a line of SQL to the MySQL
server to be processed and the results are stored in the variable
$result. */
$result = mysql_query("SELECT * FROM employees",$db);
// Displaying the details in a table echo "<table border=1>";
echo "<tr><th>Name</th><th>Position</th></tr>"; while ($myrow =
mysql_fetch_row($result)) {
printf("<tr><td>%s %s</td><td>%s</td></tr>",
$myrow[1], $myrow[2],$myrow[4]);
}
echo "</table>";
?>
</body>
</html>
Date :- ___/___/_____
Topic 28
<html>
<body>
<?php
if ($submit) {
// Open MYSQL server connection
$db = mysql_connect("localhost", "root","q1w2e3r4/");
// Select the database using MYSQL server connection
mysql_select_db("mydb",$db);
/* Write insert query and assign the query in $sql Variable */
$sql = "INSERT INTO employees (first,last,address,position)
VALUES('$first','$last','$address','$position')";
// Execute the query
$result = mysql_query($sql);
echo "Thank you! Information entered.";
}
else
{
// display form
?>
<form method="post" action="<?php echo $PHP_SELF?>">
First name:<input type="Text" name="first"><br> Last name:<input type="Text"
name="last"><br> Address:<input type="Text" name="address"><br>
Position:<input type="Text" name="position"><br>
<input type="Submit" name="submit" value="Enter information">
</form>
<?php
} // end if
?>
</body>
</html>
Date :- ___/___/_____
Topic 29
<html>
<body>
<?php
// Open MYSQL server connection
$db = mysql_connect("localhost", "root","q1w2e3r4/");
// Select the database using MYSQL server connection
mysql_select_db("mydb",$db);
if ($id) {
if ($submit) {
// Write UPDATE query and assign to $sql Variable
$sql = "UPDATE employees SET
first='$first', last='$last', address='$address',
position='$position' WHERE id=$id";
// Execute the query
$result = mysql_query($sql);
echo "Thank you! Information updated.";
}
else
{
Date :- ___/___/_____
Topic 30
<html>
<body>
<?php
// Open MYSQL server connection
$db = mysql_connect("localhost", "root","q1w2e3r4/");
// Select the database using MYSQL server connection
mysql_select_db("mydb",$db);
if ($id) {
if ($submit) {
// Write DELETE query to delete data from table based on ID
$sql = "DELETE FROM employees WHERE id=$id";
// Execute the query
$result = mysql_query($sql);
echo "Thank you! Information deleted.";
}
else
{
// Write SELECT query to select data from table based on ID
$sql = "SELECT * FROM employees WHERE id=$id";
$result = mysql_query($sql);
$myrow = mysql_fetch_array($result);
?>
<form method="post" action="<?php echo $PHP_SELF?>">
<input type=hidden name="id" value="<?php echo $myrow["id"] ?>">
First name:<input type="Text" name="first" readonly="readonly"
value="<?php echo $myrow["first"] ?>"><br> Last name:<input type="Text"
name="last"
readonly="readonly"
value="<?php echo $myrow["last"] ?>"><br> Address:<input type="Text"
name="address"
readonly="readonly"
value="<?php echo $myrow["address"]?>"><br> Position:<input type="Text"
name="position"
value="<?php echo $myrow["position"]?>"><br>
<input type="Submit" name="submit" value="Delete information">
</form>
<?php
}
}
else
{
// display list of employees
$result = mysql_query("SELECT * FROM employees",$db);
52