0% found this document useful (0 votes)
455 views

Unit 5 PHP Basic Full Notes

This document provides an overview of basic PHP functions for outputting strings and variables using echo and print statements. It explains the differences between echo and print, and provides examples of displaying strings and variables with each statement.
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
455 views

Unit 5 PHP Basic Full Notes

This document provides an overview of basic PHP functions for outputting strings and variables using echo and print statements. It explains the differences between echo and print, and provides examples of displaying strings and variables with each statement.
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 84

PHP BASIC

In PHP there is two basic ways to get output: echo and print.

In this tutorial we use echo (and print) in almost every example. So, this chapter contains a little
more info about those two output statements.

PHP echo and print Statements


There are some differences between echo and print:

 echo - can output one or more strings


 print - can only output one string, and returns always 1

Tip: echo is marginally faster compared to print as echo does not return any value.

The PHP echo Statement


echo is a language construct, and can be used with or without parentheses: echo or echo().

Display Strings

The following example shows how to display different strings with the echo command (also
notice that the strings can contain HTML markup):

<!DOCTYPE html>
<html>
<body>

<?php
echo "<h2>PHP is fun!</h2>";
echo "Hello world!<br>";
echo "I'm about to learn PHP!<br>";
echo "This", " string", " was", " made", " with multiple parameters.";
?>

</body>
</html>

PHP is fun!
Hello world!
I'm about to learn PHP!
This string was made with multiple parameters.

----------------------------------

Display Variables

The following example shows how to display strings and variables with the echo command:

<!DOCTYPE html>
<html>
<body>

<?php
$txt1="Learn PHP";
$txt2="W3Schools.com";
$cars=array("Volvo","BMW","Toyota");
echo $txt1;
echo "<br>";
echo "Study PHP at $txt2";
echo "<br>";
echo "My car is a {$cars[0]}";
?>

</body>
</html>

Learn PHP
Study PHP at W3Schools.com
My car is a Volvo

The PHP print Statement


print is also a language construct, and can be used with or without parentheses: print or print().

Display Strings

The following example shows how to display different strings with the print command (also
notice that the strings can contain HTML markup):

<!DOCTYPE html>
<html>
<body>

<?php
print "<h2>PHP is fun!</h2>";
print "Hello world!<br>";
print "I'm about to learn PHP!";
?>
</body>
</html>

PHP is fun!
Hello world!
I'm about to learn PHP!

Display Variables

The following example shows how to display strings and variables with the print command:

<!DOCTYPE html>
<html>
<body>

<?php
$txt1="Learn PHP";
$txt2="W3Schools.com";
$cars=array("Volvo","BMW","Toyota");
print $txt1;
print "<br>";
print "Study PHP at $txt2";
print "<br>";
print "My car is a {$cars[0]}";
?>

</body>
</html>

Learn PHP
Study PHP at W3Schools.com
My car is a Volvo

PHP Data Types

String, Integer, Floating point numbers, Boolean, Array, Object, NULL.

PHP Strings
A string is a sequence of characters, like "Hello world!".

A string can be any text inside quotes. You can use single or double quotes:

<!DOCTYPE html>
<html>
<body>
<?php
$x = "Hello world!";
echo $x;
echo "<br>";
$x = 'Hello world!';
echo $x;
?>

</body>
</html>

Hello world!
Hello world!

PHP Integers
An integer is a number without decimals.

Rules for integers:

 An integer must have at least one digit (0-9)


 An integer cannot contain comma or blanks
 An integer must not have a decimal point
 An integer can be either positive or negative
 Integers can be specified in three formats: decimal (10-based), hexadecimal (16-based -
prefixed with 0x) or octal (8-based - prefixed with 0)

In the following example we will test different numbers. The PHP var_dump() function returns
the data type and value of variables:

<!DOCTYPE html>
<html>
<body>

<?php
$x = 5985;
var_dump($x);
echo "<br>";
$x = -345; // negative number
var_dump($x);
echo "<br>";
$x = 0x8C; // hexadecimal number
var_dump($x);
echo "<br>";
$x = 047; // octal number
var_dump($x);
?>

</body>
</html>
int(5985)
int(-345)
int(140)
int(39)

PHP Floating Point Numbers


A floating point number is a number with a decimal point or a number in exponential form.

In the following example we will test different numbers. The PHP var_dump() function returns
the data type and value of variables:

<!DOCTYPE html>
<html>
<body>

<?php
$x = 10.365;
var_dump($x);
echo "<br>";
$x = 2.4e3;
var_dump($x);
echo "<br>";
$x = 8E-5;
var_dump($x);
?>

</body>
</html>

float(10.365)
float(2400)
float(8.0E-5)

PHP Booleans
Booleans can be either TRUE or FALSE.

$x=true;
$y=false;

Booleans are often used in conditional testing. You will learn more about conditional testing in a
later chapter of this tutorial.

PHP Arrays
An array stores multiple values in one single variable.
In the following example we create an array, and then use the PHP var_dump() function to return
the data type and value of the array:

<!DOCTYPE html>
<html>
<body>

<?php
$cars=array("Volvo","BMW","Toyota");
var_dump($cars);
?>

</body>
</html>

array(3) { [0]=> string(5) "Volvo" [1]=> string(3) "BMW" [2]=> string(6) "Toyota" }

PHP Objects
An object is a data type which stores data and information on how to process that data.

In PHP, an object must be explicitly declared.

First we must declare a class of object. For this, we use the class keyword. A class is a structure
that can contain properties and methods.

We then define the data type in the object class, and then we use the data type in instances of that
class:

<!DOCTYPE html>
<html>
<body>

<?php
class Car
{
var $color;
function Car($color="green")
{
$this->color = $color;
}
function what_color()
{
return $this->color;
}
}

function print_vars($obj)
{
foreach (get_object_vars($obj) as $prop => $val)
{
echo "\t$prop = $val\n";
}
}

// instantiate one object


$herbie = new Car("white");

// show herbie properties


echo "\herbie: Properties\n";
print_vars($herbie);

?>

</body>
</html>

\herbie: Properties color = white

PHP NULL Value


The special NULL value represents that a variable has no value. NULL is the only possible value
of data type NULL.

The NULL value identifies whether a variable is empty or not. Also useful to differentiate
between the empty string and null values of databases.

Variables can be emptied by setting the value to NULL:

<!DOCTYPE html>
<html>
<body>

<?php
$x="Hello world!";
$x=null;
var_dump($x);
?>

</body>
</html>

NULL

PHP String Functions

A string is a sequence of characters, like "Hello world!".

PHP String Functions


In this chapter we will look at some commonly used functions to manipulate strings.
The PHP strlen() function
The strlen() function returns the length of a string, in characters.

The example below returns the length of the string "Hello world!":

<!DOCTYPE html>
<html>
<body>

<?php
echo strlen("Hello world!");
?>

</body>
</html>

12

Tip: strlen() is often used in loops or other functions, when it is important to know when a string
ends. (i.e. in a loop, we might want to stop the loop after the last character in a string).

The PHP strpos() function


The strpos() function is used to search for a specified character or text within a string.

If a match is found, it will return the character position of the first match. If no match is found, it
will return FALSE.

The example below searches for the text "world" in the string "Hello world!":

<!DOCTYPE html>
<html>
<body>

<?php
echo strpos("Hello world!","world");
?>

</body>
</html>

Tip: The position of the string "world" in the example above is 6. The reason that it is 6 (and not
7), is that the first character position in the string is 0, and not 1.
Function Description
addcslashes() Returns a string with backslashes in front of the specified characters
addslashes() Returns a string with backslashes in front of predefined characters
bin2hex() Converts a string of ASCII characters to hexadecimal values
Removes whitespace or other characters from the right end of a
chop()
string
chr() Returns a character from a specified ASCII value
chunk_split() Splits a string into a series of smaller parts
convert_cyr_string() Converts a string from one Cyrillic character-set to another
convert_uudecode() Decodes a uuencoded string
convert_uuencode() Encodes a string using the uuencode algorithm
count_chars() Returns information about characters used in a string
crc32() Calculates a 32-bit CRC for a string
crypt() One-way string encryption (hashing)
echo() Outputs one or more strings
explode() Breaks a string into an array
fprintf() Writes a formatted string to a specified output stream
Returns the translation table used by htmlspecialchars() and
get_html_translation_table()
htmlentities()
hebrev() Converts Hebrew text to visual text
hebrevc() Converts Hebrew text to visual text and new lines (\n) into <br>
hex2bin() Converts a string of hexadecimal values to ASCII characters
html_entity_decode() Converts HTML entities to characters
htmlentities() Converts characters to HTML entities
htmlspecialchars_decode() Converts some predefined HTML entities to characters
htmlspecialchars() Converts some predefined characters to HTML entities
implode() Returns a string from the elements of an array
join() Alias of implode()
lcfirst() Converts the first character of a string to lowercase
levenshtein() Returns the Levenshtein distance between two strings
localeconv() Returns locale numeric and monetary formatting information
Removes whitespace or other characters from the left side of a
ltrim()
string
md5() Calculates the MD5 hash of a string
md5_file() Calculates the MD5 hash of a file
metaphone() Calculates the metaphone key of a string
money_format() Returns a string formatted as a currency string
nl_langinfo() Returns specific local information
nl2br() Inserts HTML line breaks in front of each newline in a string
number_format() Formats a number with grouped thousands
ord() Returns the ASCII value of the first character of a string
parse_str() Parses a query string into variables
print() Outputs one or more strings
printf() Outputs a formatted string
quoted_printable_decode() Converts a quoted-printable string to an 8-bit string
quoted_printable_encode() Converts an 8-bit string to a quoted printable string
quotemeta() Quotes meta characters
Removes whitespace or other characters from the right side of a
rtrim()
string
setlocale() Sets locale information
sha1() Calculates the SHA-1 hash of a string
sha1_file() Calculates the SHA-1 hash of a file
similar_text() Calculates the similarity between two strings
soundex() Calculates the soundex key of a string
sprintf() Writes a formatted string to a variable
sscanf() Parses input from a string according to a format
str_getcsv() Parses a CSV string into an array
str_ireplace() Replaces some characters in a string (case-insensitive)
str_pad() Pads a string to a new length
str_repeat() Repeats a string a specified number of times
str_replace() Replaces some characters in a string (case-sensitive)
str_rot13() Performs the ROT13 encoding on a string
str_shuffle() Randomly shuffles all characters in a string
str_split() Splits a string into an array
str_word_count() Count the number of words in a string
strcasecmp() Compares two strings (case-insensitive)
Finds the first occurrence of a string inside another string (alias of
strchr()
strstr())
strcmp() Compares two strings (case-sensitive)
strcoll() Compares two strings (locale based string comparison)
Returns the number of characters found in a string before any part
strcspn()
of some specified characters are found
strip_tags() Strips HTML and PHP tags from a string
stripcslashes() Unquotes a string quoted with addcslashes()
stripslashes() Unquotes a string quoted with addslashes()
Returns the position of the first occurrence of a string inside another
stripos()
string (case-insensitive)
Finds the first occurrence of a string inside another string (case-
stristr()
insensitive)
strlen() Returns the length of a string
Compares two strings using a "natural order" algorithm (case-
strnatcasecmp()
insensitive)
Compares two strings using a "natural order" algorithm (case-
strnatcmp()
sensitive)
strncasecmp() String comparison of the first n characters (case-insensitive)
strncmp() String comparison of the first n characters (case-sensitive)
strpbrk() Searches a string for any of a set of characters
Returns the position of the first occurrence of a string inside another
strpos()
string (case-sensitive)
strrchr() Finds the last occurrence of a string inside another string
strrev() Reverses a string
Finds the position of the last occurrence of a string inside another
strripos()
string (case-insensitive)
Finds the position of the last occurrence of a string inside another
strrpos()
string (case-sensitive)
Returns the number of characters found in a string that contains
strspn()
only characters from a specified charlist
Finds the first occurrence of a string inside another string (case-
strstr()
sensitive)
strtok() Splits a string into smaller strings
strtolower() Converts a string to lowercase letters
strtoupper() Converts a string to uppercase letters
strtr() Translates certain characters in a string
substr() Returns a part of a string
Compares two strings from a specified start position (binary safe
substr_compare()
and optionally case-sensitive)
substr_count() Counts the number of times a substring occurs in a string
substr_replace() Replaces a part of a string with another string
trim() Removes whitespace or other characters from both sides of a string
ucfirst() Converts the first character of a string to uppercase
ucwords() Converts the first character of each word in a string to uppercase
vfprintf() Writes a formatted string to a specified output stream
vprintf() Outputs a formatted string
vsprintf() Writes a formatted string to a variable
wordwrap() Wraps a string to a given number of characters

PHP Constants

Constants are like variables except that once they are defined they cannot be changed or
undefined.

PHP Constants
A constant is an identifier (name) for a simple value. The value cannot be changed during the
script.

A valid constant name starts with a letter or underscore (no $ sign before the constant name).

Note: Unlike variables, constants are automatically global across the entire script.

Set a PHP Constant


To set a constant, use the define() function - it takes three parameters: The first parameter defines
the name of the constant, the second parameter defines the value of the constant, and the optional
third parameter specifies whether the constant name should be case-insensitive. Default is false.
The example below creates a case-sensitive constant, with the value of "Welcome to
W3Schools.com!":

<!DOCTYPE html>
<html>
<body>

<?php
// define a case-sensitive constant
define("GREETING", "Welcome to W3Schools.com!");
echo GREETING;
echo "<br>";
// will not output the value of the constant
echo greeting;
?>

</body>
</html>

Welcome to W3Schools.com!
greeting

The example below creates a case-insensitive constant, with the value of "Welcome to
W3Schools.com!":

<!DOCTYPE html>
<html>
<body>

<?php
// define a case-insensitive constant
define("GREETING", "Welcome to W3Schools.com!", true);
echo GREETING;
echo "<br>";
// will also output the value of the constant
echo greeting;
?>

</body>
</html>

Welcome to W3Schools.com!
Welcome to W3Schools.com!

PHP Operators

This chapter shows the different operators that can be used in PHP scripts.
PHP Arithmetic Operators
Operator Name Example Result

+ Addition $x + $y Sum of $x and $y

- Subtraction $x - $y Difference of $x and $y

* Multiplication $x * $y Product of $x and $y

/ Division $x / $y Quotient of $x and $y

% Modulus $x % $y Remainder of $x divided by $y

The example below shows the different results of using the different arithmetic operators:

<!DOCTYPE html>
<html>
<body>

<?php
$x=10;
$y=6;

echo ($x + $y);


echo "<br>";
echo ($x - $y);
echo "<br>";
echo ($x * $y);
echo "<br>";
echo ($x / $y);
echo "<br>";
echo ($x % $y);
?>

</body>
</html>

16
4
60
1.6666666666667
4

PHP Assignment Operators


The PHP assignment operators is used to write a value to a variable.
The basic assignment operator in PHP is "=". It means that the left operand gets set to the value of the
assignment expression on the right.

Assignment Same as... Description


The left operand gets set to the value of the expression on the
x=y x=y
right
x += y x=x+y Addition
x -= y x=x-y Subtraction
x *= y x=x*y Multiplication
x /= y x=x/y Division
x %= y x=x%y Modulus

The example below shows the different results of using the different assignment operators:

<!DOCTYPE html>
<html>
<body>

<?php
$x=10;
echo $x;
echo "<br>";

$y=20;
$y += 100;
echo $y;
echo "<br>";

$z=50;
$z -= 25;
echo $z;
echo "<br>";

$i=5;
$i *= 6;
echo $i;
echo "<br>";

$j=10;
$j /= 5;
echo $j;
echo "<br>";

$k=15;
$k %= 4;
echo $k;
?>
</body>
</html>

10
120
25
30
2
3

PHP String Operators

Operator Name Example Result


$txt1 = "Hello" Now $txt2 contains "Hello
. Concatenation
$txt2 = $txt1 . " world!" world!"
Concatenation $txt1 = "Hello" Now $txt1 contains "Hello
.=
assignment $txt1 .= " world!" world!"

The example below shows the results of using the string operators:

Example
<!DOCTYPE html>
<html>
<body>

<?php
$a = "Hello";
$b = $a . " world!";
echo $b; // outputs Hello world!

echo "<br>";

$x="Hello";
$x .= " world!";
echo $x; // outputs Hello world!
?>

</body>
</html>

Hello world!
Hello world!

PHP Increment / Decrement Operators

Operator Name Description


++$x Pre-increment Increments $x by one, then returns $x
$x++ Post-increment Returns $x, then increments $x by one
--$x Pre-decrement Decrements $x by one, then returns $x
$x-- Post-decrement Returns $x, then decrements $x by one

The example below shows the different results of using the different increment/decrement
operators:

Example
<!DOCTYPE html>
<html>
<body>

<?php
$x=10;
echo ++$x;
echo "<br>";

$y=10;
echo $y++;
echo "<br>";

$z=5;
echo --$z;
echo "<br>";

$i=5;
echo $i--;
?>

</body>
</html>

11
10
4
5

PHP Comparison Operators


The PHP comparison operators are used to compare two values (number or string):

Operator Name Example Result


== Equal $x == $y True if $x is equal to $y
True if $x is equal to $y, and they
=== Identical $x === $y
are of the same type
!= Not equal $x != $y True if $x is not equal to $y
<> Not equal $x <> $y True if $x is not equal to $y
True if $x is not equal to $y, or
!== Not identical $x !== $y
they are not of the same type
> Greater than $x > $y True if $x is greater than $y
< Less than $x < $y True if $x is less than $y
True if $x is greater than or equal
>= Greater than or equal to $x >= $y
to $y
True if $x is less than or equal to
<= Less than or equal to $x <= $y
$y

The example below shows the different results of using some of the comparison operators:

Example
<!DOCTYPE html>
<html>
<body>

<?php
$x=100;
$y="100";

var_dump($x == $y); // returns true because values are equal


echo "<br>";
var_dump($x === $y); // returns false because types are not equal
echo "<br>";
var_dump($x != $y); // returns false because values are equal
echo "<br>";
var_dump($x !== $y); // returns true because types are not equal
echo "<br>";

$a=50;
$b=90;

var_dump($a > $b);


echo "<br>";
var_dump($a < $b);
?>

</body>
</html>

bool(true)
bool(false)
bool(false)
bool(true)
bool(false)
bool(true)
PHP Logical Operators

Operator Name Example Result


and And $x and $y True if both $x and $y are true
or Or $x or $y True if either $x or $y is true
True if either $x or $y is true, but
xor Xor $x xor $y
not both
&& And $x && $y True if both $x and $y are true
|| Or $x || $y True if either $x or $y is true
! Not !$x True if $x is not true

PHP Array Operators


The PHP array operators are used to compare arrays:

Operator Name Example Result


Union of $x and $y (but duplicate
+ Union $x + $y
keys are not overwritten)
True if $x and $y have the same
== Equality $x == $y
key/value pairs
True if $x and $y have the same
=== Identity $x === $y key/value pairs in the same order
and of the same types
!= Inequality $x != $y True if $x is not equal to $y
<> Inequality $x <> $y True if $x is not equal to $y
!== Non-identity $x !== $y True if $x is not identical to $y

The example below shows the different results of using the different array operators:

Example
<!DOCTYPE html>
<html>
<body>

<?php
$x = array("a" => "red", "b" => "green");
$y = array("c" => "blue", "d" => "yellow");
$z = $x + $y; // union of $x and $y
var_dump($z);
echo "<br>";
var_dump($x == $y);
echo "<br>";
var_dump($x === $y);
echo "<br>";
var_dump($x != $y);
echo "<br>";
var_dump($x <> $y);
echo "<br>";
var_dump($x !== $y);
?>

</body>
</html>

array(4) { ["a"]=> string(3) "red" ["b"]=> string(5) "green" ["c"]=> string(4) "blue" ["d"]=> string(6)
"yellow" }
bool(false)
bool(false)
bool(true)
bool(true)
bool(true)

PHP if...else...elseif Statements

Conditional statements are used to perform different actions based on different conditions.

PHP Conditional Statements


Very often when you write code, you want to perform different actions for different decisions.
You can use conditional statements in your code to do this.

In PHP we have the following conditional statements:

 if statement - executes some code only if a specified condition is true


 if...else statement - executes some code if a condition is true and another code if the condition
is false

 if...elseif....else statement - selects one of several blocks of code to be executed

 switch statement - selects one of many blocks of code to be executed

PHP - The if Statement


The if statement is used to execute some code only if a specified condition is true.

Syntax
if (condition)
{
code to be executed if condition is true;
}
The example below will output "Have a good day!" if the current time (HOUR) is less than 20:

Example
<!DOCTYPE html>
<html>
<body>

<?php
$t=date("H");
if ($t<"20")
{
echo "Have a good day!";
}
?>

</body>
</html>

PHP - The if...else Statement


Use the if....else statement to execute some code if a condition is true and 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 example below will output "Have a good day!" if the current time is less than 20, and "Have
a good night!" otherwise:

Example
<!DOCTYPE html>
<html>
<body>

<?php
$t=date("H");
if ($t<"20")
{
echo "Have a good day!";
}
else
{
echo "Have a good night!";
}
?>

</body>
</html>

Have a good night!

PHP - The if...elseif....else Statement


Use the if....elseif...else statement to select 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 example below will output "Have a good morning!" if the current time is less than 10, and
"Have a good day!" if the current time is less than 20. Otherwise it will output "Have a good
night!":

Example
<!DOCTYPE html>
<html>
<body>

<?php
$t=date("H");
if ($t<"10")
{
echo "Have a good morning!";
}
elseif ($t<"20")
{
echo "Have a good day!";
}
else
{
echo "Have a good night!";
}
?>

</body>
</html>

Have a good night!

PHP switch Statement

The switch statement is used to perform different actions based on different conditions.

The PHP switch Statement


Use the switch statement to select one of many 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;
case label3:
code to be executed if n=label3;
break;
...
default:
code to be executed if n is different from all labels;
}

This is how it works: First we have a single expression n (most often a variable), that is
evaluated once. The value of the expression is then compared with the values for each case in the
structure. If there is a match, the block of code associated with that case is executed. Use break
to prevent the code from running into the next case automatically. The default statement is used
if no match is found.
Example
<!DOCTYPE html>
<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, or green!";
}
?>

</body>
</html>

Your favorite color is red!

PHP while Loops


« Previous

Next Chapter »

PHP while loops execute a block of code while the specified condition is true.

PHP Loops
Often when you write code, you want the same block of code to run over and over again in a
row. Instead of adding several almost equal code-lines in a script, we can use loops to perform a
task like this.

In PHP, we have the following looping statements:


 while - loops through a block of code as long as the specified condition is true
 do...while - loops through a block of code once, and then repeats the loop as long as the
specified condition is true

 for - loops through a block of code a specified number of times

 foreach - loops through a block of code for each element in an array

The PHP while Loop


The while loop executes a block of code as long as the specified condition is true.

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

The example below first sets a variable $x to 1 ($x=1;). Then, the while loop will continue to run
as long as $x is less than, or equal to 5. $x will increase by 1 each time the loop runs ($x++;):

Example
<!DOCTYPE html>
<html>
<body>

<?php
$x=1;
while($x<=5)
{
echo "The number is: $x <br>";
$x++;
}
?>

</body>
</html>

The number is: 1


The number is: 2
The number is: 3
The number is: 4
The number is: 5

The PHP do...while Loop


The do...while loop will always execute the block of code once, it will then check the condition,
and repeat the loop while the specified condition is true.

Syntax
do
{
code to be executed;
}
while (condition is true);

The example below first sets a variable $x to 1 ($x=1;). Then, the do while loop will write some
output, and then increment the variable $x with 1. Then the condition is checked (is $x less than,
or equal to 5?), and the loop will continue to run as long as $x is less than, or equal to 5:

Example
<!DOCTYPE html>
<html>
<body>

<?php
$x=1;
do
{
echo "The number is: $x <br>";
$x++;
}
while ($x<=5)
?>

</body>
</html>

The number is: 1


The number is: 2
The number is: 3
The number is: 4
The number is: 5

Notice that in a do while loop the condition is tested AFTER executing the statements within the
loop. This means that the do while loop would execute its statements at least once, even if the
condition fails the first time.

The example below sets the $x variable to 6, then it runs the loop, and then the condition is
checked:

Example
<!DOCTYPE html>
<html>
<body>

<?php
$x=6;
do
{
echo "The number is: $x <br>";
$x++;
}
while ($x<=5)
?>

</body>
</html>

The number is: 6

PHP for Loops

PHP for loops execute a block of code a specified number of times.

The PHP for Loop


The for loop is used when you know in advance how many times the script should run.

Syntax
for (init counter; test counter; increment counter)
{
code to be executed;
}

Parameters:

 init counter: Initialize the loop counter value


 test counter: Evaluated for each loop iteration. If it evaluates to TRUE, the loop continues. If it
evaluates to FALSE, the loop ends.

 increment counter: Increases the loop counter value

The example below displays the numbers from 0 to 10:

Example
<!DOCTYPE html>
<html>
<body>
<?php
for ($x=0; $x<=10; $x++)
{
echo "The number is: $x <br>";
}
?>

</body>
</html>

The number is: 0


The number is: 1
The number is: 2
The number is: 3
The number is: 4
The number is: 5
The number is: 6
The number is: 7
The number is: 8
The number is: 9
The number is: 10

The PHP foreach Loop


The foreach loop works only on arrays, and is used to loop through each key/value pair in an
array.

Syntax
foreach ($array as $value)
{
code to be executed;
}

For every loop iteration, the value of the current array element is assigned to $value and the array
pointer is moved by one, until it reaches the last array element.

The following example demonstrates a loop that will output the values of the given array
($colors):

Example
<!DOCTYPE html>
<html>
<body>
<?php
$colors = array("red","green","blue","yellow");
foreach ($colors as $value)
{
echo "$value <br>";
}
?>

</body>
</html>

red
green
blue
yellow

PHP Functions

The real power of PHP comes from its functions; it has more than 1000 built-in functions.

PHP User Defined Functions


Besides the built-in PHP functions, we can create our own functions.

A function is a block of statements that can be used repeatedly in a program.

A function will not execute immediately when a page loads.

A function will be executed by a call to the function.

Create a User Defined Function in PHP


A user defined function declaration starts with the word "function":

Syntax
function functionName()
{
code to be executed;
}

Note: A function name can start with a letter or underscore (not a number).

Tip: Give the function a name that reflects what the function does!

Remember that function names are case-insensitive.


In the example below, we create a function named "writeMsg()". The opening curly brace ( { )
indicates the beginning of the function code and the closing curly brace ( } ) indicates the end of
the function. The function outputs "Hello world!". To call the function, just write its name:

Example
<!DOCTYPE html>
<html>
<body>

<?php
function writeMsg()
{
echo "Hello world!";
}

writeMsg();
?>

</body>
</html>

Hello world!

PHP Function Arguments


Information can be passed to functions through arguments. An argument is just like a variable.

Arguments are specified after the function name, inside the parentheses. You can add as many
arguments as you want, just seperate them with a comma.

The following example has a function with one argument ($fname). When the familyName()
function is called, we also pass along a name (e.g. Jani), and the name is used inside the function,
which outputs several different first names, but an equal last name:

Example
<!DOCTYPE html>
<html>
<body>

<?php
function familyName($fname)
{
echo "$fname Refsnes.<br>";
}

familyName("Jani");
familyName("Hege");
familyName("Stale");
familyName("Kai Jim");
familyName("Borge");
?>

</body>
</html>

Jani Refsnes.
Hege Refsnes.
Stale Refsnes.
Kai Jim Refsnes.
Borge Refsnes.

The following example has a function with two arguments ($fname and $year):

Example
<!DOCTYPE html>
<html>
<body>

<?php
function familyName($fname,$year)
{
echo "$fname Refsnes. Born in $year <br>";
}

familyName("Hege","1975");
familyName("Ståle","1978");
familyName("Kai Jim","1983");
?>

</body>
</html>

Hege Refsnes. Born in 1975


Ståle Refsnes. Born in 1978
Kai Jim Refsnes. Born in 1983

PHP Default Argument Value


The following example shows how to use a default parameter. If we call the function setHeight()
without arguments it takes the default value as argument:

Example
<!DOCTYPE html>
<html>
<body>

<?php
function setHeight($minheight=50)
{
echo "The height is : $minheight <br>";
}

setHeight(350);
setHeight();
setHeight(135);
setHeight(80);
?>

</body>
</html>

The height is : 350


The height is : 50
The height is : 135
The height is : 80

PHP Functions - Returning values


To let a function return a value, use the return statement:

Example
<!DOCTYPE html>
<html>
<body>

<?php
function sum($x,$y)
{
$z=$x+$y;
return $z;
}

echo "5 + 10 = " . sum(5,10) . "<br>";


echo "7 + 13 = " . sum(7,13) . "<br>";
echo "2 + 4 = " . sum(2,4);
?>

</body>
</html>
5 + 10 = 15
7 + 13 = 20
2+4=6

PHP Arrays

An array stores multiple values in one single variable:

Example
<!DOCTYPE html>
<html>
<body>

<?php
$cars=array("Volvo","BMW","Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
?>

</body>
</html>

I like Volvo, BMW and Toyota.

What is an Array?
An array is a special variable, which can hold more than one value at a time.

If you have a list of items (a list of car names, for example), storing the cars in single variables
could look like this:

$cars1="Volvo";
$cars2="BMW";
$cars3="Toyota";

However, what if you want to loop through the cars and find a specific one? And what if you had
not 3 cars, but 300?

The solution is to create an array!

An array can hold many values under a single name, and you can access the values by referring
to an index number.

Create an Array in PHP


In PHP, the array() function is used to create an array:

array();

In PHP, there are three types of arrays:

 Indexed arrays - Arrays with numeric index


 Associative arrays - Arrays with named keys
 Multidimensional arrays - Arrays containing one or more arrays

PHP Indexed Arrays


There are two ways to create indexed arrays:

The index can be assigned automatically (index always starts at 0):

$cars=array("Volvo","BMW","Toyota");

or the index can be assigned manually:

$cars[0]="Volvo";
$cars[1]="BMW";
$cars[2]="Toyota";

The following example creates an indexed array named $cars, assigns three elements to it, and
then prints a text containing the array values:

Example
<!DOCTYPE html>
<html>
<body>

<?php
$cars=array("Volvo","BMW","Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
?>

</body>
</html>

I like Volvo, BMW and Toyota.

Get The Length of an Array - The count() Function


The count() function is used to return the length (the number of elements) of an array:

Example
<!DOCTYPE html>
<html>
<body>

<?php
$cars=array("Volvo","BMW","Toyota");
echo count($cars);
?>

</body>
</html>

Loop Through an Indexed Array


To loop through and print all the values of an indexed array, you could use a for loop, like this:

Example
<!DOCTYPE html>
<html>
<body>

<?php
$cars=array("Volvo","BMW","Toyota");
$arrlength=count($cars);

for($x=0;$x<$arrlength;$x++)
{
echo $cars[$x];
echo "<br>";
}
?>

</body>
</html>

Volvo
BMW
Toyota

PHP Associative Arrays


Associative arrays are arrays that use named keys that you assign to them.

There are two ways to create an associative array:

$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");

or:

$age['Peter']="35";
$age['Ben']="37";
$age['Joe']="43";

The named keys can then be used in a script:

Example
<!DOCTYPE html>
<html>
<body>

<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
echo "Peter is " . $age['Peter'] . " years old.";
?>

</body>
</html>

Peter is 35 years old.

Loop Through an Associative Array


To loop through and print all the values of an associative array, you could use a foreach loop, like
this:

Example
<!DOCTYPE html>
<html>
<body>

<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");

foreach($age as $x=>$x_value)
{
echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";
}
?>

</body>
</html>

Key=Peter, Value=35
Key=Ben, Value=37
Key=Joe, Value=43

PHP 5 Array Functions

PHP 5 Array Functions


The PHP array functions are part of the PHP core. No installation is required to use these
functions

Function Description

array() Creates an array

array_change_key_case() Changes all keys in an array to lowercase or uppercase

array_chunk() Splits an array into chunks of arrays

array_column() Returns the values from a single column in the input array

Creates an array by using the elements from one "keys" array and one "values"
array_combine()
array

array_count_values() Counts all the values of an array

array_diff() Compare arrays, and returns the differences (compare values only)

array_diff_assoc() Compare arrays, and returns the differences (compare keys and values)

array_diff_key() Compare arrays, and returns the differences (compare keys only)

Compare arrays, and returns the differences (compare keys and values, using a
array_diff_uassoc()
user-defined key comparison function)

Compare arrays, and returns the differences (compare keys only, using a user-
array_diff_ukey()
defined key comparison function)

array_fill() Fills an array with values


array_fill_keys() Fills an array with values, specifying keys

array_filter() Filters the values of an array using a callback function

array_flip() Flips/Exchanges all keys with their associated values in an array

array_intersect() Compare arrays, and returns the matches (compare values only)

array_intersect_assoc() Compare arrays and returns the matches (compare keys and values)

array_intersect_key() Compare arrays, and returns the matches (compare keys only)

Compare arrays, and returns the matches (compare keys and values, using a
array_intersect_uassoc()
user-defined key comparison function)

Compare arrays, and returns the matches (compare keys only, using a user-
array_intersect_ukey()
defined key comparison function)

array_key_exists() Checks if the specified key exists in the array

array_keys() Returns all the keys of an array

Sends each value of an array to a user-made function, which returns new


array_map()
values

array_merge() Merges one or more arrays into one array

array_merge_recursive() Merges one or more arrays into one array recursively

array_multisort() Sorts multiple or multi-dimensional arrays

array_pad() Inserts a specified number of items, with a specified value, to an array

array_pop() Deletes the last element of an array

array_product() Calculates the product of the values in an array

array_push() Inserts one or more elements to the end of an array

array_rand() Returns one or more random keys from an array

array_reduce() Returns an array as a string, using a user-defined function

array_replace() Replaces the values of the first array with the values from following arrays

Replaces the values of the first array with the values from following arrays
array_replace_recursive()
recursively

array_reverse() Returns an array in the reverse order

array_search() Searches an array for a given value and returns the key

array_shift() Removes the first element from an array, and returns the value of the
removed element

array_slice() Returns selected parts of an array

array_splice() Removes and replaces specified elements of an array

array_sum() Returns the sum of the values in an array

Compare arrays, and returns the differences (compare values only, using a
array_udiff()
user-defined key comparison function)

Compare arrays, and returns the differences (compare keys and values, using a
array_udiff_assoc() built-in function to compare the keys and a user-defined function to compare
the values)

Compare arrays, and returns the differences (compare keys and values, using
array_udiff_uassoc()
two user-defined key comparison functions)

Compare arrays, and returns the matches (compare values only, using a user-
array_uintersect()
defined key comparison function)

Compare arrays, and returns the matches (compare keys and values, using a
array_uintersect_assoc() built-in function to compare the keys and a user-defined function to compare
the values)

Compare arrays, and returns the matches (compare keys and values, using two
array_uintersect_uassoc()
user-defined key comparison functions)

array_unique() Removes duplicate values from an array

array_unshift() Adds one or more elements to the beginning of an array

array_values() Returns all the values of an array

array_walk() Applies a user function to every member of an array

array_walk_recursive() Applies a user function recursively to every member of an array

arsort() Sorts an associative array in descending order, according to the value

asort() Sorts an associative array in ascending order, according to the value

compact() Create array containing variables and their values

count() Returns the number of elements in an array

current() Returns the current element in an array

each() Returns the current key and value pair from an array

end() Sets the internal pointer of an array to its last element

extract() Imports variables into the current symbol table from an array
in_array() Checks if a specified value exists in an array

key() Fetches a key from an array

krsort() Sorts an associative array in descending order, according to the key

ksort() Sorts an associative array in ascending order, according to the key

list() Assigns variables as if they were an array

natcasesort() Sorts an array using a case insensitive "natural order" algorithm

natsort() Sorts an array using a "natural order" algorithm

next() Advance the internal array pointer of an array

pos() Alias of current()

prev() Rewinds the internal array pointer

range() Creates an array containing a range of elements

reset() Sets the internal pointer of an array to its first element

rsort() Sorts an indexed array in descending order

shuffle() Shuffles an array

sizeof() Alias of count()

sort() Sorts an indexed array in ascending order

uasort() Sorts an array by values using a user-defined comparison function

uksort() Sorts an array by keys using a user-defined comparison function

usort() Sorts an array using a user-defined comparison function

PHP Sorting Arrays

The elements in an array can be sorted in alphabetical or numerical order, descending or


ascending.

PHP - Sort Functions For Arrays


In this chapter, we will go through the following PHP array sort functions:

 sort() - sort arrays in ascending order


 rsort() - sort arrays in descending order
 asort() - sort associative arrays in ascending order, according to the value

 ksort() - sort associative arrays in ascending order, according to the key

 arsort() - sort associative arrays in descending order, according to the value

 krsort() - sort associative arrays in descending order, according to the key

Sort Array in Ascending Order - sort()


The following example sorts the elements of the $cars array in ascending alphabetical order:

Example
<!DOCTYPE html>
<html>
<body>

<?php
$cars=array("Volvo","BMW","Toyota");
sort($cars);

$clength=count($cars);
for($x=0;$x<$clength;$x++)
{
echo $cars[$x];
echo "<br>";
}
?>

</body>
</html>

BMW
Toyota
Volvo

The following example sorts the elements of the $numbers array in ascending numerical order:

Example
<!DOCTYPE html>
<html>
<body>

<?php
$numbers=array(4,6,2,22,11);
sort($numbers);
$arrlength=count($numbers);
for($x=0;$x<$arrlength;$x++)
{
echo $numbers[$x];
echo "<br>";
}
?>

</body>
</html>

2
4
6
11
22

Sort Array in Descending Order - rsort()


The following example sorts the elements of the $cars array in descending alphabetical order:

Example
<!DOCTYPE html>
<html>
<body>

<?php
$cars=array("Volvo","BMW","Toyota");
rsort($cars);

$clength=count($cars);
for($x=0;$x<$clength;$x++)
{
echo $cars[$x];
echo "<br>";
}
?>

</body>
</html>

Volvo
Toyota
BMW

The following example sorts the elements of the $numbers array in descending numerical order:
Example
<!DOCTYPE html>
<html>
<body>

<?php
$numbers=array(4,6,2,22,11);
rsort($numbers);

$arrlength=count($numbers);
for($x=0;$x<$arrlength;$x++)
{
echo $numbers[$x];
echo "<br>";
}
?>

</body>
</html>

22
11
6
4
2

Sort Array in Ascending Order, According to Value - asort()


The following example sorts an associative array in ascending order, according to the value:

Example
<!DOCTYPE html>
<html>
<body>

<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
asort($age);

foreach($age as $x=>$x_value)
{
echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";
}
?>
</body>
</html>

Key=Peter, Value=35
Key=Ben, Value=37
Key=Joe, Value=43

Sort Array in Ascending Order, According to Key - ksort()


The following example sorts an associative array in ascending order, according to the key:

Example
<!DOCTYPE html>
<html>
<body>

<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
ksort($age);

foreach($age as $x=>$x_value)
{
echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";
}
?>

</body>
</html>

Key=Ben, Value=37
Key=Joe, Value=43
Key=Peter, Value=35

Sort Array in Descending Order, According to Value -


arsort()
The following example sorts an associative array in descending order, according to the value:

Example
<!DOCTYPE html>
<html>
<body>

<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
arsort($age);

foreach($age as $x=>$x_value)
{
echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";
}
?>

</body>
</html>

Key=Joe, Value=43
Key=Ben, Value=37
Key=Peter, Value=35

Sort Array in Descending Order, According to Key - krsort()


The following example sorts an associative array in descending order, according to the key:

Example
<!DOCTYPE html>
<html>
<body>

<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
krsort($age);

foreach($age as $x=>$x_value)
{
echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";
}
?>

</body>
</html>

Key=Peter, Value=35
Key=Joe, Value=43
Key=Ben, Value=37
PHP Global Variables - Superglobals

Superglobals were introduced in PHP 4.1.0, and are built-in variables that are always available in
all scopes.

PHP Global Variables - Superglobals


Several predefined variables in PHP are "superglobals", which means that they are always
accessible, regardless of scope - and you can access them from any function, class or file without
having to do anything special.

The PHP superglobal variables are:

 $GLOBALS
 $_SERVER

 $_REQUEST

 $_POST

 $_GET

 $_FILES

 $_ENV

 $_COOKIE

 $_SESSION

This chapter will explain some of the superglobals, and the rest will be explained in later
chapters.

PHP $GLOBAL
$GLOBAL 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.

The example below shows how to use the super global variable $GLOBAL:

Example
<!DOCTYPE html>
<html>
<body>

<?php
$x = 75;
$y = 25;

function addition()
{
$GLOBALS['z'] = $GLOBALS['x'] + $GLOBALS['y'];
}

addition();
echo $z;
?>

</body>
</html>

100

In the example above, since z is a variable present within the $GLOBALS array, it is also
accessible form outside the function!

PHP $_SERVER
$_SERVER is a PHP super global variable which holds information about headers, paths, and
script locations.

The example below shows how to use some of the elements in $_SERVER:

Example
<!DOCTYPE html>
<html>
<body>

<?php
echo $_SERVER['PHP_SELF'];
echo "<br>";
echo $_SERVER['SERVER_NAME'];
echo "<br>";
echo $_SERVER['HTTP_HOST'];
echo "<br>";
echo $_SERVER['HTTP_REFERER'];
echo "<br>";
echo $_SERVER['HTTP_USER_AGENT'];
echo "<br>";
echo $_SERVER['SCRIPT_NAME'];
?>
</body>
</html>

/php/demo_global_server.php
www.w3schools.com
www.w3schools.com
http://www.w3schools.com/php/showphp.asp?filename=demo_global_server
Mozilla/5.0 (Windows NT 6.1; rv:15.0) Gecko/20100101 Firefox/15.0.1
/php/demo_global_server.php

The following table lists the most important elements that can go inside $_SERVER:

Element/Code Description
Returns the filename of the currently executing
$_SERVER['PHP_SELF']
script
Returns the version of the Common Gateway
$_SERVER['GATEWAY_INTERFACE']
Interface (CGI) the server is using
$_SERVER['SERVER_ADDR'] Returns the IP address of the host server
Returns the name of the host server (such as
$_SERVER['SERVER_NAME']
www.w3schools.com)
Returns the server identification string (such as
$_SERVER['SERVER_SOFTWARE']
Apache/2.2.24)
Returns the name and revision of the information
$_SERVER['SERVER_PROTOCOL']
protocol (such as HTTP/1.1)
Returns the request method used to access the page
$_SERVER['REQUEST_METHOD']
(such as POST)
Returns the timestamp of the start of the request
$_SERVER['REQUEST_TIME']
(such as 1377687496)
Returns the query string if the page is accessed via a
$_SERVER['QUERY_STRING']
query string
$_SERVER['HTTP_ACCEPT'] Returns the Accept header from the current request
Returns the Accept_Charset header from the current
$_SERVER['HTTP_ACCEPT_CHARSET']
request (such as utf-8,ISO-8859-1)
$_SERVER['HTTP_HOST'] Returns the Host header from the current request
Returns the complete URL of the current page (not
$_SERVER['HTTP_REFERER']
reliable because not all user-agents support it)
$_SERVER['HTTPS'] Is the script queried through a secure HTTP protocol
Returns the IP address from where the user is
$_SERVER['REMOTE_ADDR']
viewing the current page
Returns the Host name from where the user is
$_SERVER['REMOTE_HOST']
viewing the current page
Returns the port being used on the user's machine to
$_SERVER['REMOTE_PORT']
communicate with the web server
Returns the absolute pathname of the currently
$_SERVER['SCRIPT_FILENAME']
executing script
$_SERVER['SERVER_ADMIN'] Returns the value given to the SERVER_ADMIN
directive in the web server configuration file (if your
script runs on a virtual host, it will be the value
defined for that virtual host) (such as
[email protected])
Returns the port on the server machine being used
$_SERVER['SERVER_PORT']
by the web server for communication (such as 80)
Returns the server version and virtual host name
$_SERVER['SERVER_SIGNATURE']
which are added to server-generated pages
Returns the file system based path to the current
$_SERVER['PATH_TRANSLATED']
script
$_SERVER['SCRIPT_NAME'] Returns the path of the current script
$_SERVER['SCRIPT_URI'] Returns the URI of the current page

PHP $_REQUEST
PHP $_REQUEST is used to collect data after submitting an HTML form.

The example below shows a form with an input field and a submit button. When a user submits
the data by clicking on "Submit", the form data is sent to the file specified in the action attribute
of the <form> tag. In this example, we point to this file itself for processing form data. If you
wish to use another PHP file to process form data, replace that with the filename of your choice.
Then, we can use the super global variable $_REQUEST to collect the value of the input field:

Example
<!DOCTYPE html>
<html>
<body>

<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">


Name: <input type="text" name="fname">
<input type="submit">
</form>

<?php
$name = $_REQUEST['fname'];
echo $name;
?>

</body>
</html>

Name: Submit Query

PHP $_POST
PHP $_POST is widely used to collect form data after submitting an HTML form with
method="post". $_POST is also widely used to pass variables.

The example below shows a form with an input field and a submit button. When a user submits
the data by clicking on "Submit", the form data is sent to the file specified in the action attribute
of the <form> tag. In this example, we point to this file itself for processing form data. If you
wish to use another PHP file to process form data, replace that with the filename of your choice.
Then, we can use the super global variable $_POST to collect the value of the input field:

Example
<!DOCTYPE html>
<html>
<body>

<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">


Name: <input type="text" name="fname">
<input type="submit">
</form>

<?php
$name = $_POST['fname'];
echo $name;
?>

</body>
</html>

Submit Query
Name:

PHP $_GET
PHP $_GET can also be used to collect form data after submitting an HTML form with
method="get".

$_GET can also collect data sent in the URL.

Assume we have an HTML page that contains a hyperlink with parameters:

<html>
<body>

<a href="test_get.php?subject=PHP&web=W3schools.com">Test $GET</a>

</body>
</html>
When a user clicks on the link "Test $GET", the parameters "subject" and "web" is sent to
"test_get.php", and you can then acces their values in "test_get.php" with $_GET.

The example below shows the code in "test_get.php":

Example
<!DOCTYPE html>
<html>
<body>

<a href="test_get.php?subject=PHP&web=W3schools.com">Test $GET</a>

</body>
</html>

Test $GET

Study PHP at W3schools.com


PHP FORM HANDLING

The PHP superglobals $_GET and $_POST are used to collect form-data.

PHP - A Simple HTML Form


The example below displays a simple HTML form with two input fields and a submit button:

Example
<!DOCTYPE HTML>
<html>
<body>

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


Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>

</body>
</html>

Name:

E-mail: Submit Query

When the user fills out the form above and clicks the submit button, the form data is sent for
processing to a PHP file named "welcome.php". The form data is sent with the HTTP POST
method.

To display the submitted data you could simply echo all the variables. The "welcome.php" looks
like this:

<html>
<body>

Welcome <?php echo $_POST["name"]; ?><br>


Your email address is: <?php echo $_POST["email"]; ?>

</body>
</html>
The output could be something like this:

Welcome John
Your email address is [email protected]

The same result could also be achieved using the HTTP GET method:

Example
<!DOCTYPE HTML>
<html>
<body>

<form action="welcome_get.php" method="get">


Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>

</body>
</html>

Name:

E-mail: Submit Query

and "welcome_get.php" looks like this:

<html>
<body>

Welcome <?php echo $_GET["name"]; ?><br>


Your email address is: <?php echo $_GET["email"]; ?>

</body>
</html>

The code above is quite simple. However, the most important thing is missing. You need to validate form
data to protect your script from malicious code.

Think SECURITY when processing PHP forms!

This page does not contain any form validation, it just shows how you can send and retrieve
form data.

However, the next pages will show how to process PHP forms with security in mind!
Proper validation of form data is important to protect your form from hackers and
spammers!
GET vs. POST
Both GET and POST create an array (e.g. array( key => value, key2 => value2, key3 =>
value3, ...)). This array holds key/value pairs, where keys are the names of the form controls and
values are the input data from the user.

Both GET and POST are treated as $_GET and $_POST. These are superglobals, which means
that they are always accessible, regardless of scope - and you can access them from any function,
class or file without having to do anything special.

$_GET is an array of variables passed to the current script via the URL parameters.

$_POST is an array of variables passed to the current script via the HTTP POST method.

When to use GET?


Information sent from a form with the GET method is visible to everyone (all variable names
and values are displayed in the URL). GET also has limits on the amount of information to send.
The limitation is about 2000 characters. However, because the variables are displayed in the
URL, it is possible to bookmark the page. This can be useful in some cases.

GET may be used for sending non-sensitive data.

Note: GET should NEVER be used for sending passwords or other sensitive information!

When to use POST?


Information sent from a form with the POST method is invisible to others (all names/values are
embedded within the body of the HTTP request) and has no limits on the amount of information
to send.

Moreover POST supports advanced functionality such as support for multi-part binary input
while uploading files to server.

However, because the variables are not displayed in the URL, it is not possible to bookmark the page.

Developers prefer POST for sending form data.

PHP Form Validation

Think SECURITY when processing PHP forms!


These pages will show how to process PHP forms with security in mind. Proper validation
of form data is important to protect your form from hackers and spammers!

The HTML form we will be working at in these chapters, contains various input fields: required
and optional text fields, radio buttons, and a submit button:
The validation rules for the form above are as follows:

Field Validation Rules


Name Required. + Must only contain letters and whitespace
E-mail Required. + Must contain a valid email address (with @ and .)
Website Optional. If present, it must contain a valid URL
Comment Optional. Multi-line input field (textarea)
Gender Required. Must select one

First we will look at the plain HTML code for the form:

Text Fields
The name, email, and website fields are text input elements, and the comment field is a textarea.
The HTML code looks like this:

Name: <input type="text" name="name">


E-mail: <input type="text" name="email">
Website: <input type="text" name="website">
Comment: <textarea name="comment" rows="5" cols="40"></textarea>

Radio Buttons
The gender fields are radio buttons and the HTML code looks like this:

Gender:
<input type="radio" name="gender" value="female">Female
<input type="radio" name="gender" value="male">Male

The Form Element


The HTML code of the form looks like this:

<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">

When the form is submitted, the form data is sent with method="post".

What is the $_SERVER["PHP_SELF"] variable?

The $_SERVER["PHP_SELF"] is a super global variable that returns the filename of the
currently executing script.

So, the $_SERVER["PHP_SELF"] sends the submitted form data to the page itself, instead of jumping to a
different page. This way, the user will get error messages on the same page as the form.

What is the htmlspecialchars() function?

The htmlspecialchars() function converts special characters to HTML entities. This means
that it will replace HTML characters like < and > with &lt; and &gt;. This prevents
attackers from exploiting the code by injecting HTML or Javascript code (Cross-site
Scripting attacks) in forms.

Big Note on PHP Form Security


The $_SERVER["PHP_SELF"] variable can be used by hackers!

If PHP_SELF is used in your page then a user can enter a slash (/) and then some Cross Site Scripting (XSS)
commands to execute.

Cross-site scripting (XSS) is a type of computer security vulnerability typically found


in Web applications. XSS enables attackers to inject client-side script into Web pages
viewed by other users.

Assume we have the following form in a page named "test_form.php":

<form method="post" action="<?php echo $_SERVER["PHP_SELF"];?>">


Now, if a user enters the normal URL in the address bar like
"http://www.example.com/test_form.php", the above code will be translated to:

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

So far, so good.

However, consider that a user enters the following URL in the address bar:

http://www.example.com/test_form.php/%22%3E%3Cscript%3Ealert('hacked')%3C/script%3E

In this case, the above code will be translated to:

<form method="post" action="test_form.php"/><script>alert('hacked')</script>

This code adds a script tag and an alert command. And when the page loads, the JavaScript code
will be executed (the user will see an alert box). This is just a simple and harmless example how
the PHP_SELF variable can be exploited.

Be aware of that any JavaScript code can be added inside the <script> tag! A hacker can
redirect the user to a file on another server, and that file can hold malicious code that can alter the
global variables or submit the form to another address to save the user data, for example.

How To Avoid $_SERVER["PHP_SELF"] Exploits?


$_SERVER["PHP_SELF"] exploits can be avoided by using the htmlspecialchars() function.

The form code should look like this:

<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">

The htmlspecialchars() function converts special characters to HTML entities. Now if the user
tries to exploit the PHP_SELF variable, it will result in the following output:

<form method="post"
action="test_form.php/&quot;&gt;&lt;script&gt;alert('hacked')&lt;/script&gt;">

The exploit attempt fails, and no harm is done!

Validate Form Data With PHP


The first thing we will do is to pass all variables through PHP's htmlspecialchars() function.
When we use the htmlspecialchars() function; then if a user tries to submit the following in a text
field:

<script>location.href('http://www.hacked.com')</script>

- this would not be executed, because it would be saved as HTML escaped code, like this:

&lt;script&gt;location.href('http://www.hacked.com')&lt;/script&gt;

The code is now safe to be displayed on a page or inside an e-mail.

We will also do two more things when the user submits the form:

1. Strip unnecessary characters (extra space, tab, newline) from the user input data (with the
PHP trim() function)
2. Remove backslashes (\) from the user input data (with the PHP stripslashes() function)

The next step is to create a function that will do all the checking for us (which is much more
convenient than writing the same code over and over again).

We will name the function test_input().

Now, we can check each $_POST variable with the test_input() function, and the script look like
this:

Example
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>

<?php
// define variables and set to empty values
$name = $email = $gender = $comment = $website = "";

if ($_SERVER["REQUEST_METHOD"] == "POST")
{
$name = test_input($_POST["name"]);
$email = test_input($_POST["email"]);
$website = test_input($_POST["website"]);
$comment = test_input($_POST["comment"]);
$gender = test_input($_POST["gender"]);
}

function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>

<h2>PHP Form Validation Example</h2>


<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">

Name: <input type="text" name="name">


<br><br>
E-mail: <input type="text" name="email">
<br><br>
Website: <input type="text" name="website">
<br><br>
Comment: <textarea name="comment" rows="5" cols="40"></textarea>
<br><br>
Gender:
<input type="radio" name="gender" value="female">Female
<input type="radio" name="gender" value="male">Male
<br><br>
<input type="submit" name="submit" value="Submit">
</form>

<?php
echo "<h2>Your Input:</h2>";
echo $name;
echo "<br>";
echo $email;
echo "<br>";
echo $website;
echo "<br>";
echo $comment;
echo "<br>";
echo $gender;
?>

</body>
</html>

OUTPUT
PHP Form Validation Example
ARUN
Name:

A
E-mail:

B
Website:

Comment:

Gender: Female Male

Submit Query

Your Input:
ARUN

A
B

Male

Notice that at the start of the script, we check whether the form has been submitted using
$_SERVER["REQUEST_METHOD"]. If the REQUEST_METHOD is POST, then the form has
been submitted - and it should be validated. If it has not been submitted, skip the validation and
display a blank form.

However, in the example above, all input fields are optional. The script works fine even if the
user do not enter any data.

PHP - Required Fields


From the validation rules table on the previous page, we see that the "Name", "E-mail", and "Gender"
fields are required. These fields cannot be empty and must be filled out in the HTML form.

Field Validation Rules


Name Required. + Must only contain letters and whitespace
E-mail Required. + Must contain a valid email address (with @ and .)
Website Optional. If present, it must contain a valid URL
Comment Optional. Multi-line input field (textarea)
Gender Required. Must select one

In the previous chapter, all input fields were optional.

In the following code we have added some new variables: $nameErr, $emailErr, $genderErr, and
$websiteErr. These error variables will hold error messages for the required fields. We have also
added an if else statement for each $_POST variable. This checks if the $_POST variable is
empty (with the PHP empty() function). If it is empty, an error message is stored in the different
error variables, and if it is not empty, it sends the user input data through the test_input()
function:

<?php
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $gender = $comment = $website = "";

if ($_SERVER["REQUEST_METHOD"] == "POST")
{

if (empty($_POST["name"]))
{$nameErr = "Name is required";}
else
{$name = test_input($_POST["name"]);}

if (empty($_POST["email"]))
{$emailErr = "Email is required";}
else
{$email = test_input($_POST["email"]);}

if (empty($_POST["website"]))
{$website = "";}
else
{$website = test_input($_POST["website"]);}

if (empty($_POST["comment"]))
{$comment = "";}
else
{$comment = test_input($_POST["comment"]);}

if (empty($_POST["gender"]))
{$genderErr = "Gender is required";}
else
{$gender = test_input($_POST["gender"]);}
}
?>

PHP - Display The Error Messages


Then in the HTML form, we add a little script after each required field, which generates the
correct error message if needed (that is if the user tries to submit the form without filling out the
required fields):

Example
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>

<?php
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $gender = $comment = $website = "";

if ($_SERVER["REQUEST_METHOD"] == "POST")
{

if (empty($_POST["name"]))
{$nameErr = "Name is required";}
else
{$name = test_input($_POST["name"]);}
if (empty($_POST["email"]))
{$emailErr = "Email is required";}
else
{$email = test_input($_POST["email"]);}

if (empty($_POST["website"]))
{$website = "";}
else
{$website = test_input($_POST["website"]);}

if (empty($_POST["comment"]))
{$comment = "";}
else
{$comment = test_input($_POST["comment"]);}

if (empty($_POST["gender"]))
{$genderErr = "Gender is required";}
else
{$gender = test_input($_POST["gender"]);}

function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>

<h2>PHP Form Validation Example</h2>


<p><span class="error">* required field.</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">

Name: <input type="text" name="name">


<span class="error">* <?php echo $nameErr;?></span>
<br><br>
E-mail: <input type="text" name="email">
<span class="error">* <?php echo $emailErr;?></span>
<br><br>
Website: <input type="text" name="website">
<span class="error"><?php echo $websiteErr;?></span>
<br><br>
Comment: <textarea name="comment" rows="5" cols="40"></textarea>
<br><br>
Gender:
<input type="radio" name="gender" value="female">Female
<input type="radio" name="gender" value="male">Male
<span class="error">* <?php echo $genderErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>

<?php
echo "<h2>Your Input:</h2>";
echo $name;
echo "<br>";
echo $email;
echo "<br>";
echo $website;
echo "<br>";
echo $comment;
echo "<br>";
echo $gender;
?>

</body>
</html>

PHP Form Validation Example


* required field.

Name: * Name is required

E-mail: * Email is required

Website:

Comment:

Gender: Female Male * Gender is required

Submit Query

Your Input:

PHP Forms - Validate E-mail and URL

This chapter show how to validate names, e-mails, and URLs.

PHP - Validate Name


The code below shows a simple way to check if the name field only contains letters and
whitespace. If the value of the name field is not valid, then store an error message:
$name = test_input($_POST["name"]);
if (!preg_match("/^[a-zA-Z ]*$/",$name))
{
$nameErr = "Only letters and white space allowed";
}

The preg_match() function searches a string for pattern, returning true if the pattern exists, and
false otherwise.

PHP - Validate E-mail


The code below shows a simple way to check if an e-mail address syntax is valid. If the e-mail
address syntax is not valid, then store an error message:

$email = test_input($_POST["email"]);
if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/",$email))
{
$emailErr = "Invalid email format";
}

PHP - Validate URL


The code below shows a way to check if a URL address syntax is valid (this regular expression
also allows dashes in the URL). If the URL address syntax is not valid, then store an error
message:

$website = test_input($_POST["website"]);
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/
%=~_|]/i",$website))
{
$websiteErr = "Invalid URL";
}

PHP - Validate Name, E-mail, and URL


Now, the script looks like this:

Example
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>

<?php
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $gender = $comment = $website = "";

if ($_SERVER["REQUEST_METHOD"] == "POST")
{
if (empty($_POST["name"]))
{$nameErr = "Name is required";}
else
{
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name))
{
$nameErr = "Only letters and white space allowed";
}
}

if (empty($_POST["email"]))
{$emailErr = "Email is required";}
else
{
$email = test_input($_POST["email"]);
// check if e-mail address syntax is valid
if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/",$email))
{
$emailErr = "Invalid email format";
}
}

if (empty($_POST["website"]))
{$website = "";}
else
{
$website = test_input($_POST["website"]);
// check if URL address syntax is valid (this regular expression also allows dashes in the
URL)
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-
9+&@#\/%=~_|]/i",$website))
{
$websiteErr = "Invalid URL";
}
}

if (empty($_POST["comment"]))
{$comment = "";}
else
{$comment = test_input($_POST["comment"]);}

if (empty($_POST["gender"]))
{$genderErr = "Gender is required";}
else
{$gender = test_input($_POST["gender"]);}
}

function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>

<h2>PHP Form Validation Example</h2>


<p><span class="error">* required field.</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">

Name: <input type="text" name="name">


<span class="error">* <?php echo $nameErr;?></span>
<br><br>
E-mail: <input type="text" name="email">
<span class="error">* <?php echo $emailErr;?></span>
<br><br>
Website: <input type="text" name="website">
<span class="error"><?php echo $websiteErr;?></span>
<br><br>
Comment: <textarea name="comment" rows="5" cols="40"></textarea>
<br><br>
Gender:
<input type="radio" name="gender" value="female">Female
<input type="radio" name="gender" value="male">Male
<span class="error">* <?php echo $genderErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>

<?php
echo "<h2>Your Input:</h2>";
echo $name;
echo "<br>";
echo $email;
echo "<br>";
echo $website;
echo "<br>";
echo $comment;
echo "<br>";
echo $gender;
?>

</body>
</html>
PHP Form Validation Example
* required field.

Name: * Name is required

E-mail: * Email is required

Website:

Comment:

Gender: Female Male * Gender is required

Submit Query

Your Input:

PHP Complete Form Example

This chapter show how to keep the values in the input fields when the user hits the submit
button.

PHP - Keep The Values in The Form


To show the values in the input fields after the user hits the submit button, we add a little PHP
script inside the value attribute of the following input fields: name, email, and website. In the
comment textarea field, we put the script between the <textarea> and </textarea> tags. The little
script outputs the value of the $name, $email, $website, and $comment variables.

Then, we also need to show which radio button that was checked. For this, we must manipulate
the checked attribute (not the value attribute for radio buttons):

Name: <input type="text" name="name" value="<?php echo $name;?>">

E-mail: <input type="text" name="email" value="<?php echo $email;?>">

Website: <input type="text" name="website" value="<?php echo $website;?>">

Comment: <textarea name="comment" rows="5" cols="40"><?php echo $comment;?></textarea>


Gender:
<input type="radio" name="gender"
<?php if (isset($gender) && $gender=="female") echo "checked";?>
value="female">Female
<input type="radio" name="gender"
<?php if (isset($gender) && $gender=="male") echo "checked";?>
value="male">Male

PHP - Complete Form Example


Here is the complete code for the PHP Form Validation Example:

Example
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>

<?php
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $gender = $comment = $website = "";

if ($_SERVER["REQUEST_METHOD"] == "POST")
{
if (empty($_POST["name"]))
{$nameErr = "Name is required";}
else
{
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name))
{
$nameErr = "Only letters and white space allowed";
}
}

if (empty($_POST["email"]))
{$emailErr = "Email is required";}
else
{
$email = test_input($_POST["email"]);
// check if e-mail address syntax is valid
if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/",$email))
{
$emailErr = "Invalid email format";
}
}

if (empty($_POST["website"]))
{$website = "";}
else
{
$website = test_input($_POST["website"]);
// check if URL address syntax is valid (this regular expression also allows dashes in the
URL)
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-
9+&@#\/%=~_|]/i",$website))
{
$websiteErr = "Invalid URL";
}
}

if (empty($_POST["comment"]))
{$comment = "";}
else
{$comment = test_input($_POST["comment"]);}

if (empty($_POST["gender"]))
{$genderErr = "Gender is required";}
else
{$gender = test_input($_POST["gender"]);}
}

function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>

<h2>PHP Form Validation Example</h2>


<p><span class="error">* required field.</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">

Name: <input type="text" name="name" value="<?php echo $name;?>">


<span class="error">* <?php echo $nameErr;?></span>
<br><br>
E-mail: <input type="text" name="email" value="<?php echo $email;?>">
<span class="error">* <?php echo $emailErr;?></span>
<br><br>
Website: <input type="text" name="website" value="<?php echo $website;?>">
<span class="error"><?php echo $websiteErr;?></span>
<br><br>
Comment: <textarea name="comment" rows="5" cols="40"><?php echo $comment;?
></textarea>
<br><br>
Gender:
<input type="radio" name="gender" <?php if (isset($gender) && $gender=="female")
echo "checked";?> value="female">Female
<input type="radio" name="gender" <?php if (isset($gender) && $gender=="male")
echo "checked";?> value="male">Male
<span class="error">* <?php echo $genderErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>

<?php
echo "<h2>Your Input:</h2>";
echo $name;
echo "<br>";
echo $email;
echo "<br>";
echo $website;
echo "<br>";
echo $comment;
echo "<br>";
echo $gender;
?>

</body>
</html>

PHP Connect to the MySQL Server

Use the PHP mysqli_connect() function to open a new connection to the MySQL server.

Open a Connection to the MySQL Server


Before we can access data in a database, we must open a connection to the MySQL server.

In PHP, this is done with the mysqli_connect() function.

Syntax
mysqli_connect(host,username,password,dbname);

Parameter Description

host Optional. Either a host name or an IP address

username Optional. The MySQL user name

password Optional. The password to log in with

dbname Optional. The default database to be used when performing queries

Note: There are more available parameters, but the ones listed above are the most important.

In the following example we store the connection in a variable ($con) for later use in the script:
<?php
// Create connection
$con=mysqli_connect("example.com","peter","abc123","my_db");

// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>

Close a Connection
The connection will be closed automatically when the script ends. To close the connection
before, use the mysqli_close() function:

<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");

// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

mysqli_close($con);
?>

PHP Create Database and Tables

A database holds one or more tables.

Create a Database
The CREATE DATABASE statement is used to create a database in MySQL.

We must add the CREATE DATABASE statement to the mysqli_query() function to execute the
command.

The following example creates a database named "my_db":

<?php
$con=mysqli_connect("example.com","peter","abc123");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

// Create database
$sql="CREATE DATABASE my_db";
if (mysqli_query($con,$sql))
{
echo "Database my_db created successfully";
}
else
{
echo "Error creating database: " . mysqli_error($con);
}
?>

Create a Table
The CREATE TABLE statement is used to create a table in MySQL.

We must add the CREATE TABLE statement to the mysqli_query() function to execute the
command.

The following example creates a table named "Persons", with three columns: "FirstName",
"LastName" and "Age":

<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

// Create table
$sql="CREATE TABLE Persons(FirstName CHAR(30),LastName CHAR(30),Age INT)";

// Execute query
if (mysqli_query($con,$sql))
{
echo "Table persons created successfully";
}
else
{
echo "Error creating table: " . mysqli_error($con);
}
?>

Note: When you create a field of type CHAR, you must specify the maximum length of the field,
e.g. CHAR(50).

Primary Keys and Auto Increment Fields


Each table in a database should have a primary key field.

A primary key is used to uniquely identify the rows in a table. Each primary key value must be
unique within the table. Furthermore, the primary key field cannot be null because the database
engine requires a value to locate the record.

The following example sets the PID field as the primary key field. The primary key field is often
an ID number, and is often used with the AUTO_INCREMENT setting. AUTO_INCREMENT
automatically increases the value of the field by 1 each time a new record is added. To ensure
that the primary key field cannot be null, we must add the NOT NULL setting to the field:

$sql = "CREATE TABLE Persons


(
PID INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY(PID),
FirstName CHAR(15),
LastName CHAR(15),
Age INT
)";

PHP MySQL Insert Into

The INSERT INTO statement is used to insert new records in a table.

Insert Data Into a Database Table


The INSERT INTO statement is used to add new records to a database table.

Syntax

It is possible to write the INSERT INTO statement in two forms.

The first form doesn't specify the column names where the data will be inserted, only their
values:
INSERT INTO table_name
VALUES (value1, value2, value3,...)

The second form specifies both the column names and the values to be inserted:

INSERT INTO table_name (column1, column2, column3,...)


VALUES (value1, value2, value3,...)

To get PHP to execute the statements above we must use the mysqli_query() function. This
function is used to send a query or command to a MySQL connection.

Example

In the previous chapter we created a table named "Persons", with three columns; "FirstName",
"LastName" and "Age". We will use the same table in this example. The following example adds
two new records to the "Persons" table:

<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

mysqli_query($con,"INSERT INTO Persons (FirstName, LastName, Age)


VALUES ('Peter', 'Griffin',35)");

mysqli_query($con,"INSERT INTO Persons (FirstName, LastName, Age)


VALUES ('Glenn', 'Quagmire',33)");

mysqli_close($con);
?>

Insert Data From a Form Into a Database


Now we will create an HTML form that can be used to add new records to the "Persons" table.

Here is the HTML form:

<html>
<body>

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


Firstname: <input type="text" name="firstname">
Lastname: <input type="text" name="lastname">
Age: <input type="text" name="age">
<input type="submit">
</form>

</body>
</html>

When a user clicks the submit button in the HTML form, in the example above, the form data is
sent to "insert.php".

The "insert.php" file connects to a database, and retrieves the values from the form with the PHP
$_POST variables.

Then, the mysqli_query() function executes the INSERT INTO statement, and a new record will
be added to the "Persons" table.

Here is the "insert.php" page:

<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$sql="INSERT INTO Persons (FirstName, LastName, Age)


VALUES
('$_POST[firstname]','$_POST[lastname]','$_POST[age]')";

if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "1 record added";

mysqli_close($con);
?>

PHP MySQL Select

The SELECT statement is used to select data from a database.

Select Data From a Database Table


The SELECT statement is used to select data from a database.

Syntax
SELECT column_name(s)
FROM table_name

To get PHP to execute the statement above we must use the mysqli_query() function. This
function is used to send a query or command to a MySQL connection.

Example

The following example selects all the data stored in the "Persons" table (The * character selects
all the data in the table):

<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$result = mysqli_query($con,"SELECT * FROM Persons");

while($row = mysqli_fetch_array($result))
{
echo $row['FirstName'] . " " . $row['LastName'];
echo "<br>";
}

mysqli_close($con);
?>

The example above stores the data returned by the mysqli_query() function in the $result
variable.

Next, we use the mysqli_fetch_array() function to return the first row from the recordset as an
array. Each call to mysqli_fetch_array() returns the next row in the recordset. The while loop
loops through all the records in the recordset. To print the value of each row, we use the PHP
$row variable ($row['FirstName'] and $row['LastName']).

The output of the code above will be:

Peter Griffin
Glenn Quagmire
Display the Result in an HTML Table
The following example selects the same data as the example above, but will display the data in
an HTML table:

<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$result = mysqli_query($con,"SELECT * FROM Persons");

echo "<table border='1'>


<tr>
<th>Firstname</th>
<th>Lastname</th>
</tr>";

while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['FirstName'] . "</td>";
echo "<td>" . $row['LastName'] . "</td>";
echo "</tr>";
}
echo "</table>";

mysqli_close($con);
?>

The output of the code above will be:

Firstname Lastname
Glenn Quagmire
Peter Griffin

PHP MySQL The Where Clause

The WHERE clause is used to filter records.

The WHERE clause


The WHERE clause is used to extract only those records that fulfill a specified criterion.
Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name operator value

To get PHP to execute the statement above we must use the mysqli_query() function. This
function is used to send a query or command to a MySQL connection.

Example

The following example selects all rows from the "Persons" table where "FirstName='Peter'":

<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$result = mysqli_query($con,"SELECT * FROM Persons


WHERE FirstName='Peter'");

while($row = mysqli_fetch_array($result))
{
echo $row['FirstName'] . " " . $row['LastName'];
echo "<br>";
}
?>

The output of the code above will be:

Peter Griffin

PHP MySQL Order By Keyword

The ORDER BY keyword is used to sort the data in a recordset.

The ORDER BY Keyword


The ORDER BY keyword is used to sort the data in a recordset.

The ORDER BY keyword sort the records in ascending order by default.

If you want to sort the records in a descending order, you can use the DESC keyword.
Syntax
SELECT column_name(s)
FROM table_name
ORDER BY column_name(s) ASC|DESC

Example

The following example selects all the data stored in the "Persons" table, and sorts the result by
the "Age" column:

<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$result = mysqli_query($con,"SELECT * FROM Persons ORDER BY age");

while($row = mysqli_fetch_array($result))
{
echo $row['FirstName'];
echo " " . $row['LastName'];
echo " " . $row['Age'];
echo "<br>";
}

mysqli_close($con);
?>

The output of the code above will be:

Glenn Quagmire 33
Peter Griffin 35

Order by Two Columns


It is also possible to order by more than one column. When ordering by more than one column,
the second column is only used if the values in the first column are equal:

SELECT column_name(s)
FROM table_name
ORDER BY column1, column2
PHP MySQL Update

The UPDATE statement is used to modify data in a table.

Update Data In a Database


The UPDATE statement is used to update existing records in a table.

Syntax
UPDATE table_name
SET column1=value, column2=value2,...
WHERE some_column=some_value

Note: Notice the WHERE clause in the UPDATE syntax. The WHERE clause specifies which record or
records that should be updated. If you omit the WHERE clause, all records will be updated!

To get PHP to execute the statement above we must use the mysqli_query() function. This
function is used to send a query or command to a MySQL connection.

Example

Earlier in the tutorial we created a table named "Persons". Here is how it looks:

FirstName LastName Age

Peter Griffin 35

Glenn Quagmire 33

The following example updates some data in the "Persons" table:

<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

mysqli_query($con,"UPDATE Persons SET Age=36


WHERE FirstName='Peter' AND LastName='Griffin'");

mysqli_close($con);
?>
After the update, the "Persons" table will look like this:

FirstName LastName Age

Peter Griffin 36

Glenn Quagmire 33

PHP MySQL Delete

The DELETE statement is used to delete records in a table.

Delete Data In a Database


The DELETE FROM statement is used to delete records from a database table.

Syntax
DELETE FROM table_name
WHERE some_column = some_value

Note: Notice the WHERE clause in the DELETE syntax. The WHERE clause specifies which
record or records that should be deleted. If you omit the WHERE clause, all records will be
deleted!

To get PHP to execute the statement above we must use the mysqli_query() function. This
function is used to send a query or command to a MySQL connection.

Example

Look at the following "Persons" table:

FirstName LastName Age

Peter Griffin 35

Glenn Quagmire 33

The following example deletes all the records in the "Persons" table where LastName='Griffin':

<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_query($con,"DELETE FROM Persons WHERE LastName='Griffin'");

mysqli_close($con);
?>

After the deletion, the table will look like this:

FirstName LastName Age


Glenn Quagmire 33

PHP Database ODBC

ODBC is an Application Programming Interface (API) that allows you to connect to a data
source (e.g. an MS Access database).

Create an ODBC Connection


With an ODBC connection, you can connect to any database, on any computer in your network,
as long as an ODBC connection is available.

Here is how to create an ODBC connection to a MS Access Database:

1. Open the Administrative Tools icon in your Control Panel.


2. Double-click on the Data Sources (ODBC) icon inside.

3. Choose the System DSN tab.

4. Click on Add in the System DSN tab.

5. Select the Microsoft Access Driver. Click Finish.

6. In the next screen, click Select to locate the database.

7. Give the database a Data Source Name (DSN).

8. Click OK.

Note that this configuration has to be done on the computer where your web site is located. If
you are running Internet Information Server (IIS) on your own computer, the instructions
above will work, but if your web site is located on a remote server, you have to have physical
access to that server, or ask your web host to to set up a DSN for you to use.

Connecting to an ODBC
The odbc_connect() function is used to connect to an ODBC data source. The function takes
four parameters: the data source name, username, password, and an optional cursor type.

The odbc_exec() function is used to execute an SQL statement.


Example

The following example creates a connection to a DSN called northwind, with no username
and no password. It then creates an SQL and executes it:

$conn=odbc_connect('northwind','','');
$sql="SELECT * FROM customers";
$rs=odbc_exec($conn,$sql);

Retrieving Records
The odbc_fetch_row() function is used to return records from the result-set. This function
returns true if it is able to return rows, otherwise false.

The function takes two parameters: the ODBC result identifier and an optional row number:

odbc_fetch_row($rs)

Retrieving Fields from a Record


The odbc_result() function is used to read fields from a record. This function takes two
parameters: the ODBC result identifier and a field number or name.

The code line below returns the value of the first field from the record:

$compname=odbc_result($rs,1);

The code line below returns the value of a field called "CompanyName":

$compname=odbc_result($rs,"CompanyName");

Closing an ODBC Connection


The odbc_close() function is used to close an ODBC connection.

odbc_close($conn);

An ODBC Example
The following example shows how to first create a database connection, then a result-set, and
then display the data in an HTML table.

<html>
<body>

<?php
$conn=odbc_connect('northwind','','');
if (!$conn)
{exit("Connection Failed: " . $conn);}
$sql="SELECT * FROM customers";
$rs=odbc_exec($conn,$sql);
if (!$rs)
{exit("Error in SQL");}
echo "<table><tr>";
echo "<th>Companyname</th>";
echo "<th>Contactname</th></tr>";
while (odbc_fetch_row($rs))
{
$compname=odbc_result($rs,"CompanyName");
$conname=odbc_result($rs,"ContactName");
echo "<tr><td>$compname</td>";
echo "<td>$conname</td></tr>";
}
odbc_close($conn);
echo "</table>";
?>

</body>
</html>

You might also like