Unit 5 PHP Basic Full Notes
Unit 5 PHP Basic Full Notes
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.
Tip: echo is marginally faster compared to print as echo does not return any value.
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
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 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.
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)
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.
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";
}
}
?>
</body>
</html>
The NULL value identifies whether a variable is empty or not. Also useful to differentiate
between the empty string and null values of databases.
<!DOCTYPE html>
<html>
<body>
<?php
$x="Hello world!";
$x=null;
var_dump($x);
?>
</body>
</html>
NULL
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).
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.
<!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
The example below shows the different results of using the different arithmetic operators:
<!DOCTYPE html>
<html>
<body>
<?php
$x=10;
$y=6;
</body>
</html>
16
4
60
1.6666666666667
4
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
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!
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
The example below shows the different results of using some of the comparison operators:
Example
<!DOCTYPE html>
<html>
<body>
<?php
$x=100;
$y="100";
$a=50;
$b=90;
</body>
</html>
bool(true)
bool(false)
bool(false)
bool(true)
bool(false)
bool(true)
PHP Logical Operators
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)
Conditional statements are used to perform different actions based on different conditions.
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>
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>
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>
The switch statement is used to perform different actions based on different conditions.
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>
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.
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>
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>
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>
Syntax
for (init counter; test counter; increment counter)
{
code to be executed;
}
Parameters:
Example
<!DOCTYPE html>
<html>
<body>
<?php
for ($x=0; $x<=10; $x++)
{
echo "The number is: $x <br>";
}
?>
</body>
</html>
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.
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!
Example
<!DOCTYPE html>
<html>
<body>
<?php
function writeMsg()
{
echo "Hello world!";
}
writeMsg();
?>
</body>
</html>
Hello world!
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>
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>
Example
<!DOCTYPE html>
<html>
<body>
<?php
function sum($x,$y)
{
$z=$x+$y;
return $z;
}
</body>
</html>
5 + 10 = 15
7 + 13 = 20
2+4=6
PHP Arrays
Example
<!DOCTYPE html>
<html>
<body>
<?php
$cars=array("Volvo","BMW","Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
?>
</body>
</html>
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?
An array can hold many values under a single name, and you can access the values by referring
to an index number.
array();
$cars=array("Volvo","BMW","Toyota");
$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>
Example
<!DOCTYPE html>
<html>
<body>
<?php
$cars=array("Volvo","BMW","Toyota");
echo count($cars);
?>
</body>
</html>
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
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
or:
$age['Peter']="35";
$age['Ben']="37";
$age['Joe']="43";
Example
<!DOCTYPE html>
<html>
<body>
<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
echo "Peter is " . $age['Peter'] . " years old.";
?>
</body>
</html>
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
Function Description
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_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_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_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_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
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)
each() Returns the current key and value pair from an array
extract() Imports variables into the current symbol table from an array
in_array() Checks if a specified value exists in an array
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
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
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
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
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
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.
$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>
<?php
$name = $_REQUEST['fname'];
echo $name;
?>
</body>
</html>
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>
<?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".
<html>
<body>
</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.
Example
<!DOCTYPE html>
<html>
<body>
</body>
</html>
Test $GET
The PHP superglobals $_GET and $_POST are used to collect form-data.
Example
<!DOCTYPE HTML>
<html>
<body>
</body>
</html>
Name:
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>
</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>
</body>
</html>
Name:
<html>
<body>
</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.
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.
Note: GET should NEVER be used for sending passwords or other sensitive information!
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.
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:
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:
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
When the form is submitted, the form data is sent with method="post".
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.
The htmlspecialchars() function converts special characters to HTML entities. This means
that it will replace HTML characters like < and > with < and >. This prevents
attackers from exploiting the code by injecting HTML or Javascript code (Cross-site
Scripting attacks) in forms.
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.
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
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.
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/"><script>alert('hacked')</script>">
<script>location.href('http://www.hacked.com')</script>
- this would not be executed, because it would be saved as HTML escaped code, like this:
<script>location.href('http://www.hacked.com')</script>
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).
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;
}
?>
<?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:
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.
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"]);}
}
?>
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;
}
?>
<?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>
Website:
Comment:
Submit Query
Your Input:
The preg_match() function searches a string for pattern, returning true if the pattern exists, and
false otherwise.
$email = test_input($_POST["email"]);
if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/",$email))
{
$emailErr = "Invalid email format";
}
$website = test_input($_POST["website"]);
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/
%=~_|]/i",$website))
{
$websiteErr = "Invalid URL";
}
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;
}
?>
<?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.
Website:
Comment:
Submit Query
Your Input:
This chapter show how to keep the values in the input fields when the user hits the submit
button.
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):
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;
}
?>
<?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>
Use the PHP mysqli_connect() function to open a new connection to the MySQL server.
Syntax
mysqli_connect(host,username,password,dbname);
Parameter Description
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);
?>
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.
<?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).
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:
Syntax
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:
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_close($con);
?>
<html>
<body>
</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.
<?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();
}
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
mysqli_close($con);
?>
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();
}
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']).
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();
}
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);
?>
Firstname Lastname
Glenn Quagmire
Peter Griffin
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();
}
while($row = mysqli_fetch_array($result))
{
echo $row['FirstName'] . " " . $row['LastName'];
echo "<br>";
}
?>
Peter Griffin
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();
}
while($row = mysqli_fetch_array($result))
{
echo $row['FirstName'];
echo " " . $row['LastName'];
echo " " . $row['Age'];
echo "<br>";
}
mysqli_close($con);
?>
Glenn Quagmire 33
Peter Griffin 35
SELECT column_name(s)
FROM table_name
ORDER BY column1, column2
PHP MySQL Update
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:
Peter Griffin 35
Glenn Quagmire 33
<?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);
?>
After the update, the "Persons" table will look like this:
Peter Griffin 36
Glenn Quagmire 33
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
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);
?>
ODBC is an Application Programming Interface (API) that allows you to connect to a data
source (e.g. an MS Access database).
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 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)
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");
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>