Akul PHP Practical File (Edited Version) - Page - Number

Download as pdf or txt
Download as pdf or txt
You are on page 1of 52

Chandigarh College of Technology

SUBJECT:- PROGRAMMING IN PHP LABORATORY


SUBJECT CODE: UGCA1930
BCA –5th Semester

Chandigarh College of Technology

Submitted By :- Akul Sharma Submitted To :- Mr Raj Kumar


Roll no. :- 2110367 Designation :- Assistant Professor
Semester :- 5th Department :- DCA, Landran

CGC Landran
Bachelor of Computer Applications
Landran, Mohali (Punjab)
(Pin- 140307)
2

INDEX

Sign &
Sr.No. Title Page No Date
Remarks

1. What is PHP? Basic Syntax 4

2. Error Management 5

3. Comments in PHP 6

4. PHP is a Loosely Typed Language 7

5. PHP Variables Example 8

6. Global and locally-scoped variables 9

7. Static Keyword in PHP 10

ECHO and PRINT statements in 11


8.
PHP

9. String Functions in PHP 12

10. Constant in PHP 13

11. PHP Operators 14 - 18

12. The if Statement in PHP 19

13. The if…else Statement in PHP 20

The if…elseif…else Statement in 21


14.
PHP

15. Switch Statement in PHP 22

16. For loop in PHP 23 – 24

17. While Loop in PHP 25

18. Do While loop in PHP 26 – 27

19. Swap Numbers PHP Example 28

20. PHP Functions 29

21. Statements in PHP 30 – 31

22. PHP Global Variables 32 – 33


3

23. Array in PHP 34 – 36

24. PHP Forms 37 - 41

How to connect to MYSQL database 42 - 44


25.
using PHP

The functions used to connect web 45


26.
form to the MYSQL database

Display the data from MYSQL 46


27.
database in web form

Insert the data into MYSQL database 47 - 48


28.
using web form

Update the data present in MYSQL 49 – 50


29.
database using web form

Delete the data from MYSQL 51 - 52


30.
database using web form
4

Date :- ___/___/_____

Topic 1

What is PHP?

 PHP stands for PHP: Hypertext Preprocessor


 PHP is a server-side scripting language
 PHP scripts are executed on the server
 PHP supports many databases (MySQL, Informix, Oracle, Sybase,
Solid, PostgreSQL, Generic ODBC, etc.)
 PHP is an open source software
 PHP is free to download and use

Basic PHP Syntax

 A PHP script starts with <?php and ends with ?>


 The default file extension for PHP files is ".php"
 A PHP file normally contains HTML tags, and some PHP scripting code
 PHP statements are terminated by semicolon (;)
 In PHP, all user-defined functions, classes, and keywords (e.g. if, else, while, echo,
etc.) are not case-sensitive

Hello World example

<html>
<body>
<?php
// Use echo to print on console echo
‚Hello World!‛;
?>
</body>
</html>

Go to htdocs folder which is present in the apache2triad installed folder. There


create a folder and save this program with .php extension such as Hello.php.

To execute hello world program, type in the address bar as


follows: http://localhost/MyPHPProgram/hello.php
5

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

Finding errors present in the program

<html>
<body>
<php
echo “Hello World!;
// here ? is missing
>
</body>
</html>

To find the errors present in the program go to:

Start  All programs  Apache2triad  Apache2TriadCP


6

Date :- ___/___/_____
Topic 3
Comments in PHP

 // Single line comment (C++ and Java-style comment)


 # Single line comment (Shell-style comments)
 /* Multiple line comment
(C-style comments) */
7

Date :- ___/___/_____
Topic 4

PHP is a Loosely Typed Language

▪ In PHP, a variable does not need to be declared before adding a value to it


▪ PHP automatically converts the variable to the correct data type,
depending on its value
▪ In PHP, the variable is declared automatically when you use it
▪ PHP variables must begin with a “$” sign
▪ Variables are used for storing values, like text strings, numbers or arrays
▪ The correct way of declaring a variable in PHP:

$var_name = value;
8

Date :- ___/___/_____
Topic 5

PHP Variables Example

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

OUTPUT of the above given Example is as follows:

Number is : 25

String is : Hello Float value : 5.7


9

Date :- ___/___/_____
Topic 6

Global and locally-scoped variables

 Global variables can be used anywhere


 Local variables restricted to a function or class

Example for Global and locally-scoped variables

<html>
<body>
<?php
$x=24; // global scope

// Function definition function myFunction() {


$y=59; // local scope
echo "Variable x is: $x <br>"; echo "Variable y is: $y";
}

myFunction();// Function call

echo "Variable x is: $x"; echo "<br>";


echo "Variable y is: $y";
?>
</body>
</html>

OUTPUT of the above given Example is as follows: Variable x is:

Variable y is: 59
Test variables outside the function: Variable x is: 24

Variable y is:
10

Date :- ___/___/_____
Topic 7

Static Keyword in PHP

 Static keyword is used when you first declare the variable


 Each time the function is called, that variable will still have the information it
contained from the last time the function was called

Static Keyword Example

<html>
<body>
<?php
// Function definition function myFunction() {
static $x=45; echo $x; echo "<br/>";
$x++;
}
// Function call
myFunction(); myFunction(); myFunction(); myFunction(); myFunction();
?>
<body>
<html>

OUTPUT of the above given Example is as follows:

45
46
47
48
49
11

Date :- ___/___/_____
Topic 8

ECHO and PRINT statements in PHP

 ECHO - It can output one or more strings


 PRINT – It can only output one string, and returns always 1
 ECHO is faster compared to PRINT as echo does not return any value
 ECHO is not a function and, as such, it does not have a return value
 If you need to output data through a function, you can use PRINT() instead:

Example:

echo 50;
print (50);

PRINT Statement Example in PHP

<html>
<body>
<?php
// Use ‘print’ to print on console print "Hello world!<br>***********";
?>
</body>
</html>

OUTPUT of the above given Example is as follows:

Hello world!
***********
12

Date :- ___/___/_____
Topic 9
String Functions in PHP

 strlen() function
 strpos() function

1. strlen() function

The strlen() function returns the length of a string, in characters

<html>
<body>
<?php
// Displays the length of the string echo
strlen("Hello world!");
?>
</body>
</html>

OUTPUT of the above given Example is as


follows:

12

2. strpos() function

The strpos() function is used to search for a


specified character or text within a string

<html>
<body>
<?php
/* Displays the position of ‘world’ in
the text ‘Hello world*/
echo strpos("Hello world!","world");
?>
</body>
</html>

OUTPUT of the above given Example is as


follows:
6
13

Date :- ___/___/_____
Topic 10
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;
$area=PI*$radius;
echo “Area=”.$area;
?>
</body>
</html>

OUTPUT of the above given Example is as follows:

Area = 706.5
14

Date :- ___/___/_____
Topic 11

Arithmetic Operators

Arithmetic operators allow performing basic mathematical operations

Operator Description Example Result

+ 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

++ Increment $a =5; $a=6

$a ++;

-- Decrement $a =5; $a=4

$a --;
15

Arithmetic Operators Example:

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

OUTPUT of the above given Example is as follows:

i = 30
j = 25
k = 100
l = 50
m=0
16

Increment and Decrement Operators

Operator Name Description

++$a Pre-increment Increments $a by one, then returns $a

$a++ Post-increment Returns $a, then increments $a by one

--$a Pre-decrement Decrements $a by one, then returns $a

$a-- Post-decrement Returns $a, then decrements $a by one

Increment and Decrement Operators Example

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

OUTPUT of the above given Example is as follows:

11
21
11
2
17

Assignment Operators in PHP

Assignment operator is used to write a value to a variable

Operator Example Is the same as

= 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

Assignment Operators Example

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

OUTPUT of the above given Example is as follows:

a=5 b=30 c=10 d=40


e=5 f=2

String Operators in PHP

Operator Name Example Result

. Concatenation $a = "Hello" $b = "Hello world!"


$b = $a . " world!"

.= Concatenation $a = "Hello" $a = "Hello world!"


Assignment $a .= " world!"

String Operators Example

<?php
$x="Hello";
$y=" ";
$z="PHP";
$n="\n";
$str=$x . $y . $z . $n;
echo $str;
?>

OUTPUT of the above given Example is as follows:


Hello PHP

String Operators Example 2

<?php
$x="Hello ";
$y="PHP";
$x .= $y;
echo $x;
?>

OUTPUT of the above given Example is as follows:


Hello PHP
19

Date :- ___/___/_____
Topic 12

The if Statement in PHP

If statement executes some code only if a specified condition is true

Syntax:

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

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
20

Date :- ___/___/_____
Topic 13

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>

The Output for the given example is...

i is not 0
21

Date :- ___/___/_____

Topic 14

The if…elseif…else Statement in PHP

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

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
?>
<body>
</html>
else
echo "numbers are equal"; //Statement3

OUTPUT of the above given Example is as follows:

numbers are equal


22

Date :- ___/___/_____
Topic 15

Switch Statement in PHP

Switch statement selects one from multiple blocks of code to be executed

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;
}

Switch Statement Example

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

OUTPUT of the above given Example is as follows:


Your favorite color is red!
23

Date :- ___/___/_____
Topic 16

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>";

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

for ($x=0; $x<=20; $x++) { echo "$x ";


}
?>
</body>
</html>

OUTPUT of the above given Example is as follows:

Numbers from 1 to 20 are:


0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20

Declaring multiple variables in for loop Example

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

OUTPUT of the above given Example is as follows:

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 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
26

Date :- ___/___/_____
Topic 18

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;
} 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

User Defined Function in PHP

Functions are group of statements that can perform a task

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>

OUTPUT of the above given Example is as follows:

Hello world
28

Date :- ___/___/_____
Topic 19

Swap Numbers PHP Example

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

OUTPUT of the above given Example is as follows:

Numbers before swapping:


Num1=10
Num2=20

Numbers after swapping:


Num1=20
Num2=10
29

Date :- ___/___/_____
Topic 20

PHP Functions - Adding parameters

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

OUTPUT of the above given Example is as follows:

My name is Kai Jim Refsnes.


My sister's name is Hege Refsnes. My brother's name is Stale Refsnes.

PHP Functions - Return values

<html>
<body>
<?php
// Function definition function add($x,$y)
{
$total=$x+$y; return $total;
}
// Function call
echo "1 + 16 = " . add(1,16);
?>
</body>
</html>

OUTPUT of the above given Example is as follows:

1 + 16 = 17
30

Date :- ___/___/_____
Topic 21

Statements in PHP

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 :

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.

Continue statement example

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

OUTPUT of the above given Example is as follows:

01245
32

Date :- ___/___/_____
Topic 22

PHP Global Variables

Superglobals

 "Superglobals" are predefined variables in PHP


 They are always accessible, regardless of scope - and can access them from any
function, class or file

The PHP superglobal variables are:


1. $GLOBALS
2. $_SERVER
3. $_REQUEST
4. $_POST
5. $_GET
6. $_ENV
7. $_COOKIE
8. $_SESSION
9. $_FILES

$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

OUTPUT of the above given Example is as follows : 60

$_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>

OUTPUT of the above given Example is as follows:

/User/server.php localhost localhost


Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0; GTB7.5; SLCC2;
.NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC
6.0; InfoPath.2; .NET CLR 1.1.4322)
/User/server.php
34

Date :- ___/___/_____
Topic 23

Array in PHP

An array stores multiple values in one single variable

In PHP, there are three kinds of arrays:


 Numeric array
 Associative array
 Multidimensional array

Numeric Array in PHP

Numeric array is an array with a numeric index

Numeric Array Example

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

OUTPUT of the above given Example is as follows:

Flowers: rose, daisy, orchid

Associative array in PHP

Associative array is an array where each ID key is associated with a value

Associative array Example


35

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

OUTPUT of the above given Example is as follows:

rose costs 5.00,daisy costs 4.00,and orchild costs

Loop through an Associative Array

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

OUTPUT of the above given Example is as follows:

Flower=rose, Value=5.00 Flower=daisy, Value=4.00 Flower=orchid, Value=2.00


36

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].
", 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>

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

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 $_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"
 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>
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>

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>

Another Example for PHP form Form.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

// create an hidden textbox


<input type="hidden" name="check_submit" value="1" />

// textbox is to take user input


Name: <input type="text" name="Name" /><br /> Password: <input type="password"
name="Password"
maxlength="10" /><br />

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

Choose the colors:


//This will create checkbox
<input type="checkbox" name="Colors[]" value="green" checked="checked" />
Green
<input type="checkbox" name="Colors[]" value="yellow"
/> Yellow
<input type="checkbox" name="Colors[]" value="red" /> Red

<input type="checkbox" name="Colors[]" value="gray" /> Gray


<br />

// Submit button is to submit the value to next page


<input type="submit" />
</form>
</body>
</html>

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

//Check whether a $_GET['Languages'] is set if ( isset($_POST['Colors']) ) {


$_POST['Colors'] = implode(', ', $_POST['Colors']);
//Converts an array into a single string
}

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

OUTPUT of the above given Example is as follows:


41

Date() and time() function in PHP

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

OUTPUT of the above given Example is as follows:

Today is 2014/08/19
Today is Tuesday
The time is 09:13:22am
42

Date :- ___/___/_____
Topic 25

How to connect to MYSQL database using PHP

1. To connect MYSQL using PHP go to:


http://localhost//phpmyadmin
2. Enter the username and password
3. Give the database name in the field ‘create new database’

To insert values in the field, go to insert and enter the values. Then click on Go

To view the created table, go to browse

To insert the values, go to SQL and write the query to insert the values and click on Go
43

SQL query for insert:

Syntax:

Insert into table_name values(‘value1’,’value2’,…);

Example:

Insert into Login values(‘Radha’,’hello’);

To update the values, go to SQL and write the query to update the values and click on Go

SQL query for update:

Syntax:

Update table_name set field_name=’value’ where field_name=’value’;

Example:

Update Login set password=’abcde’ where name=’Radha’;

To delete the values, go to SQL and write the query to delete the values and click on go
44
45

Date :- ___/___/_____
Topic 26

The functions used to connect web form to the MYSQL database:

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

Display the data from MYSQL database in web form

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

OUTPUT of the above given Example would be:


47

Date :- ___/___/_____
Topic 28

Insert the data into MYSQL database using web form

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

OUTPUT of the above given Example would be:


48
49

Date :- ___/___/_____
Topic 29

Update the data present in MYSQL database using web form

<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
{

// Write query to SELECT data from table


$sql = "SELECT * FROM employees WHERE id=$id";
// Execute the query
$result = mysql_query($sql);
// Fetch the values
$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" value="<?php echo $myrow["first"]
?>"><br>
Last name:<input type="Text" name="last" value="<?php echo $myrow["last"]
?>"><br>
Address:<input type="Text" name="address" value="<?php echo
$myrow["address"]?>"><br>
Position:<input type="Text" name="position" value="<?php echo
$myrow["position"]?>"><br>
<input type="Submit" name="submit" value="Enter information">
</form>
<?php
}
}
else
{
50

// display list of employees


$result = mysql_query("SELECT * FROM
employees",$db);
while ($myrow = mysql_fetch_array($result)) {
printf("<a href=\"%s?id=%s\">%s %s</a><br>",
$PHP_SELF, $myrow["id"],$myrow["first"],
$myrow["last"]);
}
}
?>
</body>
</html>
51

Date :- ___/___/_____
Topic 30

Delete the data from MYSQL database using web form

<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

while ($myrow = mysql_fetch_array($result)) {


printf("<a href=\"%s?id=%s\">%s %s</a><br>",
$PHP_SELF, $myrow["id"],$myrow["first"],
$myrow["last"]);
}
}
?>
</body>
</html>

OUTPUT of the above given Example would be :

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy