You are on page 1of 78

MODULE 1

(PHP History and Importance)

PHP (recursive acronym for "PHP: Hypertext Preprocessor") is a


widely-used Open Source general-purpose scripting language that is
especially suited for Web development and can be embedded into
HTML.

PHP , now, stands for Hypertext Preprocessor and is a server-side


scripting language. Please remember that there are two types of
scripting languages on web ,

a) Client Side: the languages that helps you perform different tasks
on the client side for example Javascript helps you to validate your
forms and show message accordingly to your users without submitting
page to your server on the client side. VB Script and Client Side XSLT
are other examples.
b) Server Side Languages:
Server side languages make your website dynamic and intelligent. You
can take input from your users and can perform certain operations on
the input to generate desired output. For example Online Shopping
Stores, Online Examination Applications, Online Reservation Systems,
Database driven websites are a few examples of the applications
powered by Server Side Languages.
PHP is a server side language and it helps you to make your site
intelligent to provide dynamic features to your users. Other examples
of server side languages are ASP, PERL, Cold Fusions and Server Side
Java etc.

Simple answer, but what does that mean? An example:

Example 1.1. An introductory example

<html>
<head>
<title>Example</title>
</head>
<body>

<?php
echo "Hi, I'm a PHP script!";
?>

</body>
</html>

1
In 1995 Rasmus Lerdorf made a set of scripts based on PERL
to access his resume and named it as PHP / FI stands for Personal
Home Page / Forms Interpreter. In 1997 Rasmus released PHP / FI 2.0
with a large C-implementation and it received rapid fame due to its
ease of use and C like syntax as it was easy for C programmers to
adopt and its programming rules were comparatively simple than C
language. After some beta versions of PHP / FI 2.0 finally Alpha PHP
3.0 was released later.
In 1997 Andi Gutmans and Zeev Suraski worked together
with Rasmus to completely rewrite the language and introduce a more
powerful language known as PHP 3.0. Shortly after PHP 3.0 in 1998
PHP 4 came on the screen with improved performance for complex
applications and in 2004 finally PHP 5.0 was released with a new
object model and plenty of new features.

Why PHP?

If you are still confused that why you should use PHP then answer is
very straight forward - if you want to make a web application that can
take input from users and can process it to generate certain output
then you will need PHP to work for you on server side and response to
different events generated from client side accordingly. For example if
you want to make an Online Shopping Store for your Video Games
business where people can browse different categories of games and
can shop of their choice and finally can pay you online in real time.

2
MODULE 2

(Basic PHP Syntax)

A PHP file normally contains HTML tags, just like an HTML file, and
some PHP scripting code.

Below, we have an example of a simple PHP script which sends the


text "Hello World" to the browser:

<html>
<body>
<?php echo "Hello World"; ?>
</body>
</html>

A PHP scripting block always starts with <?php and ends with ?>. A
PHP scripting block can be placed anywhere in the document.

Each code line in PHP must end with a semicolon. The semicolon is a
separator and is used to distinguish one set of instructions from
another.

There are two basic statements to output text with PHP: echo and
print. In the example above we have used the echo statement to
output the text "Hello World".

Comments in PHP

In PHP, we use // to make a single-line comment or /* and */ to make


a large comment block.

<html>
<body>
<?php
//This is a comment
/*
This is
a comment
block
*/
# This is a comment
?>
</body>
</html>

3
MODULE 3

(Variables in PHP)

All variables in PHP start with a $ sign symbol. Variables may contain
strings, numbers, or arrays.

There are four major types of variables: integers, floating point


numbers, strings and arrays. Assigning values to variables is easy.
The single and double quotes work the same as the echo statement
above.

Below, the PHP script assigns the string "Hello World" to a variable
called $txt:

<html>
<body>
<?php
$txt="Hello World";
echo $txt;
?>
</body>
</html>

To concatenate two or more variables together, use the dot (.)


operator:

<html>
<body>
<?php
$txt1="Hello World";
$txt2="1234";
echo $txt1 . " " . $txt2 ;
?>
</body>
</html>

The output of the script above will be: "Hello World 1234".

4
MODULE 4

(PHP Form Handling)

The most important thing to notice when dealing with HTML forms and
PHP is that any form element in an HTML page will automatically be
available to your PHP scripts.

The $_GET Variable


The $_GET variable is an array of variable names and values sent by
the HTTP GET method.

The $_GET variable is used to collect values from a form with


method="get". Information sent from a form with the GET method is
visible to everyone (it will be displayed in the browser's address bar)
and it has limits on the amount of information to send (max. 100
characters).

Example:

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


Name: <input type="text" name="name" />
Age: <input type="text" name="age" />
<input type="submit" />

</form>

When the user clicks the "Submit" button, the URL sent could look
something like this:

http://www.w3schools.com/welcome.php?name=Peter&age=37

The "welcome.php" file can now use the $_GET variable to catch the
form data (notice that the names of the form fields will automatically
be the ID keys in the $_GET array):

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


You are <?php echo $_GET["age"]; ?> years old!

Why use $_GET?


Note: When using the $_GET variable all variable names and values
are displayed in the URL. So this method should not be used when
sending passwords or other sensitive information! However, because
the variables are displayed in the URL, it is possible to bookmark the
page. This can be useful in some cases.

Note: The HTTP GET method is not suitable on large variable values;

5
the value cannot exceed 100 characters.

The $_REQUEST Variable

The PHP $_REQUEST variable contains the contents of both $_GET,


$_POST, and $_COOKIE.

The PHP $_REQUEST variable can be used to get the result from form
data sent with both the GET and POST methods.

Example:

Welcome <?php echo $_REQUEST["name"]; ?>.<br />


You are <?php echo $_REQUEST["age"]; ?> years old!

The $_POST Variable


The $_POST variable is an array of variable names and values sent by
the HTTP POST method.

The $_POST variable is used to collect values from a form with


method="post". Information sent from a form with the POST method
is invisible to others and has no limits on the amount of information to
send.

Example:

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


Enter your name: <input type="text" name="name" />
Enter your age: <input type="text" name="age" />
<input type="submit" />
</form>

When the user clicks the "Submit" button, the URL will not contain any
form data, and will look something like this:

http://www.w3schools.com/welcome.php

The "welcome.php" file can now use the $_POST variable to catch the
form data (notice that the names of the form fields will automatically
be the ID keys in the $_POST array):

6
Look at the following example of an HTML form:

<html>
<body>
<form action="welcome.php" method="POST">
Enter your name: <input type="text" name="name" />
Enter your age: <input type="text" name="age" />
<input type="submit" />
</form>
</body>
</html>

The example HTML page above contains two input fields and a submit
button. When the user fills in this form and hits the submit button, the
"welcome.php" file is called.

The "welcome.php" file looks like this:

<html>
<body>
Welcome <?php echo $_POST["name"]; ?>.<br />
You are <?php echo $_POST["age"]; ?> years old!
</body>
</html>

A sample output of the above script may be:

Welcome John.
You are 28 years old!

Here is how it works: The $_POST["name"] and $_POST["age"]


variables are automatically set for you by PHP. The $_POST contains
all POST data.

Note: If the method attribute of the form is GET, then the form
information will be set in $_GET instead of $_POST.

HTML has two methods for passing form variables, POST and GET. GET
displays the input in the URL while POST hides it. Variables passed via
POST are represented by $_POST["{name of input tag}"] GET uses
$_GET[] respectively. Also $_REQUEST[] will take the values of either
POST or GET. $_REQUEST also will return variables passed in a URL
not from a form.

7
MODULE 5

(Conditional Statements)
Conditional statements in PHP are used to perform different
actions based on different conditions.

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 two conditional statements:

• if (...else) statement - use this statement if you want to


execute a set of code when a condition is true (and another if
the condition is not true)
• switch statement - use this statement if you want to select
one of many sets of lines to execute

The If Statement

If you want to execute some code if a condition is true and another


code if a condition is false, use the if....else statement.

Syntax

if (condition)
code to be executed if condition is true;
else
code to be executed if condition is false;

Example

The following example will output "Have a nice weekend!" if the


current day is Friday, otherwise it will output "Have a nice day!":

<html>
<body>
<?php
$d=date("D");
if ($d=="Fri")
echo "Have a nice weekend!";
else

8
echo "Have a nice day!";
?>
</body>
</html>

If more than one line should be executed when a condition is true, the
lines should be enclosed within curly braces:

<html>
<body>
<?php
$x=10;
if ($x==10)
{
echo "Hello<br />";
echo "Good morning<br />";
}
?>
</body>
</html>

The Switch Statement

If you want to select one of many blocks of code to be executed, use


the Switch statement.

Syntax

switch (expression)
{
case label1:
code to be executed if expression = label1;
break;
case label2:
code to be executed if expression = label2;
break;
default:
code to be executed
if expression is different
from both label1 and label2;
}

Example

This is how it works: First we have a single expression (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 none of the cases are
true.

9
<html>
<body>
<?php
switch ($x)
{
case 1:
echo "Number 1";
break;
case 2:
echo "Number 2";
break;
case 3:
echo "Number 3";
break;
default:
echo "No number between 1 and 3";
}
?>
</body>
</html>

10
MODULE 6
(Looping)
Looping statements in PHP are used to execute the same block
of code a specified number of times.

Looping

Very often when you write code, you want the same block of code to
run a number of times. You can use looping statements in your code to
perform this.

In PHP we have the following looping statements:

• while - loops through a block of code if and as long as a


specified condition is true
• do...while - loops through a block of code once, and then
repeats the loop as long as a special 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 while Statement

The while statement will execute a block of code if and as long as a


condition is true.

Syntax

while (condition)
code to be executed;

Example

The following example demonstrates a loop that will continue to run as


long as the variable i is less than, or equal to 5. i will increase by 1
each time the loop runs:

<html>
<body>
<?php
$i=1;
while($i<=5)
{
echo "The number is " . $i . "<br />";
$i++;

11
}
?>
</body>
</html>

The do...while Statement

The do...while statement will execute a block of code at least once -


it then will repeat the loop as long as a condition is true.

Syntax

Do
{
code to be executed;
}
while (condition);

Example

The following example will increment the value of i at least once, and it
will continue incrementing the variable i while it has a value of less
than 5:

<html>
<body>
<?php
$i=0;
do
{
$i++;
echo "The number is " . $i . "<br />";
}
while ($i<5);
?>
</body>
</html>

The for Statement

The for statement is used when you know how many times you want
to execute a statement or a list of statements.

12
Syntax

for (initialization; condition; increment)


{
code to be executed;
}

Note: The for statement has three parameters. The first parameter is
for initializing variables, the second parameter holds the condition, and
the third parameter contains any increments required to implement
the loop. If more than one variable is included in either the
initialization or the increment section, then they should be separated
by commas. The condition must evaluate to true or false.

Example

The following example prints the text "Hello World!" five times:

<html>
<body>
<?php
for ($i=1; $i<=5; $i++)
{
echo "Hello World!<br />";
}
?>
</body>
</html>

The foreach Statement

Loops over the array given by the parameter. On each loop, the value
of the current element is assigned to $value and the array pointer is
advanced by one - so on the next loop, you'll be looking at the next
element.

Syntax

foreach (array as value)


{
code to be executed;
}

Example

The following example demonstrates a loop that will print the values of
the given array:

<html>

13
<body>
<?php
$arr=array("one", "two", "three");
foreach ($arr as $value)
{
echo "Value: " . $value . "<br />";
}
?>
</body>
</html>

14
MODULE 7

(ARRAYS)

An array is a collection of data values, organized as an ordered


collection of key-value pairs.

This module talks about creating an array, adding and removing


elements from an array, and looping over the contents of an
array. There are many built-in functions that work with arrays in
PHP, because arrays are very common and useful. For example, if
you want to send email to more than one email address, you'll
store the email addresses in an array and then loop through the
array, sending the message to the current email address. Also, if
you have a form that permits multiple selections, the items the
user selected are returned in an array.
There are two kinds of arrays in PHP: indexed and associative.
The keys of an indexed array are integers, beginning at 0.
Indexed arrays are used when you identify things by their
position.
Associative arrays have strings as keys and behave more like
two-column tables. The first column is the key, which is used to
access the value.

Simple Arrays
Simply arrays store values in a numerical index.

<?
$array=array("Monday","Tuesday","Wendsday","Thursday",
"Friday","Saturday","Sunday");
For ($a=0; $a < count($array); $a++) {
echo "$array[$a]";
}
?>

The array function inserts the values passed to it into $array. We'll
discuss the for loop later on but what happens is if $a is less than the
number of values in the array $array the value of $array with an index
of $a is displayed. Every time the loop is run the value of $a is
incremented.

15
Associative Arrays
Associative arrays store value data in keys

To create an associative array with array( ), use the => symbol


to separate indexes from values:
$price = array('Gasket' => 15.29,
'Wheel' => 75.25,
'Tire' => 50.00);

Notice the use of whitespace and alignment. We could have


bunched up the code, but it wouldn't have been as easy to read:
$price =
array('Gasket'=>15.29,'Wheel'=>75.25,'Tire'=>50.00);

To construct an empty array, pass no arguments to array( ):


$addresses = array( );

You can specify an initial key with => and then a list of values.
The values are inserted into the array starting with that key, with
subsequent values having sequential keys:
$days = array(1 => 'Monday', 'Tuesday', 'Wednesday',
'Thursday', 'Friday', 'Saturday', 'Sunday');
// 2 is Tuesday, 3 is Wednesday, etc.

<?
$assoc=array("name" => "Jon Smith",
"phone" => "555-555-1234",
"address" => "1010 Home Cir",
"city" => "Atlanta",
"state" => "GA",
"zipcode" => "30060");
$assoc["email"]="jon@smith.com";
foreach ($assoc as $key => $value) {
echo "$key : $value - ";
}
?>

Outputs name : Jon Smith - phone : 555-555-1234 - address : 1010


Home Cir - city : Atlanta - state : GA - zipcode : 30060 - email :
jon@smith.com

We'll get into the foreach loop a little later but for every value of
$assoc it set the key equal to $key and the value to $value and then
used the echo statement to display the values

16
Multidimensional arrays
<?
$info = array("Jon" => array("name" => "Jon Smith","address" => "2 Little
St","city" => "Atlanta","state" => "GA",
"zipcode" => "30060"),
"Bob" => array("name" => "Bob Jones","address" => "725 Big Cir","city" =>
"Miami","state" => "FL",
"zipcode" => "33027"),
"Mark" => array("name" => "Mark Klien","address" => "1315 Riverland
Trace","city" => "Boston","state" => "MA",
"zipcode" => "11083");
?>

This stores an array inside an array. To retrieve a value use echo


$info["Jon"]["city"] will display Atlanta.

The values in an array can themselves be arrays. This lets you


easily create multidimensional arrays:
$row_0 = array(1, 2, 3);
$row_1 = array(4, 5, 6);
$row_2 = array(7, 8, 9);
$multi = array($row_0, $row_1, $row_2);

You can refer to elements of multidimensional arrays by


appending more []s:
$value = $multi[2][0]; // row 2, column 0.
$value = 7

To interpolate a lookup of a multidimensional array, you must


enclose the entire array lookup in curly braces:
echo("The value at row 2, column 0 is {$multi[2][0]}\n");

Failing to use the curly braces results in output like this:


The value at row 2, column 0 is Array[0]

PHP Array Functions

Function Description
array() Creates an array
array_change_key_cas Returns an array with all keys in lowercase or
e() uppercase
array_chunk() Splits an array into chunks of arrays
array_combine() Creates an array by using one array for keys and
another for its values

17
array_count_values() Returns an array with the number of occurrences for
each value
array_diff() Compares array values, and returns the differences

array_diff_assoc() Compares array keys and values, and returns the


differences
array_diff_key() Compares array keys, and returns the differences

array_diff_uassoc() Compares array keys and values, with an additional


user-made function check, and returns the
differences
array_diff_ukey() Compares array keys, with an additional user-made
function check, and returns the differences

array_fill() Fills an array with values


array_filter() Filters elements of an array using a user-made
function
array_flip() Exchanges all keys with their associated values in an
array
array_intersect() Compares array values, and returns the matches

array_intersect_assoc( Compares array keys and values, and returns the


) matches
array_intersect_key() Compares array keys, and returns the matches

array_intersect_uassoc Compares array keys and values, with an additional


() user-made function check, and returns the matches

array_intersect_ukey() Compares array keys, with an additional user-made


function check, and returns the matches

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

array_keys() Returns all the keys of an array


array_map() Sends each value of an array to a user-made
function, which returns new values
array_merge() Merges one or more arrays into one array

array_merge_recursive Merges one or more arrays into one array


()
array_multisort() Sorts multiple or multi-dimensional arrays

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


array_udiff() Compares array values in a user-made function and
returns an array
array_udiff_assoc() Compares array keys, and compares array values in a
user-made function, and returns an array

array_udiff_uassoc() Compares array keys and array values in user-made


functions, and returns an array

array_uintersect() Compares array values in a user-made function and


returns an array
array_uintersect_assoc Compares array keys, and compares array values in a
() user-made function, and returns an array

array_uintersect_uasso Compares array keys and array values in user-made


c() functions, and returns an array

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

19
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 array in reverse order and maintain index
association
asort() Sorts an array and maintain index association

compact() Create array containing variables and their values

count() Counts elements in an array, or properties in an


object
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 array by key in reverse order
ksort() Sorts an array by 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 array in reverse order
shuffle() Shuffles an array

20
sizeof() Alias of count()
sort() Sorts an array
uasort() Sorts an array with a user-defined function and
maintain index association
uksort() Sorts an array by keys using a user-defined function

usort() Sorts an array by values using a user-defined


function

PHP Array Constants


PHP: indicates the earliest version of PHP that supports the constant.

Constant Description
CASE_LOWER Used with array_change_key_case() to convert array
keys to lower case
CASE_UPPER Used with array_change_key_case() to convert array
keys to upper case
SORT_ASC Used with array_multisort() to sort in ascending
order
SORT_DESC Used with array_multisort() to sort in descending
order
SORT_REGULAR Used to compare items normally
SORT_NUMERIC Used to compare items numerically
SORT_STRING Used to compare items as strings
SORT_LOCALE_STRING Used to compare items as strings, based on the
current locale
COUNT_NORMAL
COUNT_RECURSIVE
EXTR_OVERWRITE
EXTR_SKIP
EXTR_PREFIX_SAME
EXTR_PREFIX_ALL
EXTR_PREFIX_INVALID
EXTR_PREFIX_IF_EXIS
TS
EXTR_IF_EXISTS
EXTR_REFS

21
MODULE 8

(Operators)
Operators are used to operate on values.

PHP Operators

This section lists the different operators used in PHP.

Arithmetic Operators

22
Operator Description Example Result
+ Addition x=2 4
x+2
- Subtraction x=2 3
5-x
* Multiplication x=4 20
x*5
/ Division 15/5 3
5/2 2.5
% Modulus (division remainder) 5%2 1
10%8 2
10%2 0
++ Increment x=5 x=6
x++
-- Decrement x=5 x=4
x--

Assignment Operators

Operator Example Is The Same As


= x=y x=y
+= x+=y x=x+y
-= x-=y x=x-y
*= x*=y x=x*y
/= x/=y x=x/y
%= x%=y x=x%y

Comparison Operators

Operator Description Example


== is equal to 5==8 returns false
!= is not equal 5!=8 returns true
> is greater than 5>8 returns false
< is less than 5<8 returns true
>= is greater than or equal to 5>=8 returns false

23
<= is less than or equal to 5<=8 returns true

Logical Operators

Operator Description Example


&& And x=6
y=3

(x < 10 && y > 1) returns true


|| Or x=6
y=3

(x==5 || y==5) returns false


! Not x=6
y=3

!(x==y) returns true

MODULE 9

(Server Includes)

Server Side Includes


You can insert the content of a file into a PHP file before the server
executes it, with the include() or require() function. The two functions

24
are identical in every way, except how they handle errors. The
include() function generates a warning (but the script will continue
execution) while the require() function generates a fatal error (and the
script execution will stop after the error).

These two functions are used to create functions, headers, footers, or


elements that can be reused on multiple pages.

This can save the developer a considerable amount of time. This


means that you can create a standard header or menu file that you
want all your web pages to include. When the header needs to be
updated, you can only update this one include file, or when you add a
new page to your site, you can simply change the menu file (instead of
updating the links on all web pages).

The include() Function


The include() function takes all the text in a specified file and copies it
into the file that uses the include function.

Example 1

Assume that you have a standard header file, called "header.php". To


include the header file in a page, use the include() function, like this:

<html>
<body>

<?php include("header.php"); ?>

<h1>Welcome to my home page</h1>

<p>Some text</p>

</body>
</html>

Example 2

Now, let's assume we have a standard menu file that should be used
on all pages (include files usually have a ".php" extension). Look at the
"menu.php" file below:

<html>

25
<body>

<a href="http://www.w3schools.com/default.php">Home</a> |
<a href="http://www.w3schools.com/about.php">About Us</a> |
<a href="http://www.w3schools.com/contact.php">Contact Us</a>

The three files, "default.php", "about.php", and "contact.php" should


all include the "menu.php" file. Here is the code in "default.php":

<?php include("menu.php"); ?>

<h1>Welcome to my home page</h1>

<p>Some text</p>

</body>
</html>

If you look at the source code of the "default.php" in a browser, it will


look something like this:

<html>
<body>
<a href="default.php">Home</a> |
<a href="about.php">About Us</a> |
<a href="contact.php">Contact Us</a>
<h1>Welcome to my home page</h1>
<p>Some text</p>
</body>
</html>

And, of course, we would have to do the same thing for "about.php"


and "contact.php". By using include files, you simply have to update
the text in the "menu.php" file if you decide to rename or change the
order of the links or add another web page to the site.

The require() Function


The require() function is identical to include(), they only handle errors
differently.

The include() function generates a warning (but the script will continue
execution) while the require() function generates a fatal error (and the
script execution will stop after the error).

If you include a file with the include() function and an error occurs,
you might get an error message like the following.

26
<html>
<body>

<?php
include("wrongFile.php");
echo "Hello World!";
?>

</body>
</html>

Error message:

Warning: include(wrongFile.php) [function.include]:


failed to open stream:
No such file or directory in C:\home\website\test.php on line 5

Warning: include() [function.include]:


Failed opening 'wrongFile.php' for inclusion
(include_path='.;C:\php5\pear')
in C:\home\website\test.php on line 5

Hello World!

Notice that the echo statement is still executed! This is because a


Warning does not stop the script execution.

Now, let's run the same example with the require() function.

<html>
<body>

<?php
require("wrongFile.php");
echo "Hello World!";
?>

</body>
</html>

Error message:

Warning: require(wrongFile.php) [function.require]:


failed to open stream:
No such file or directory in C:\home\website\test.php on line 5

Fatal error: require() [function.require]:

27
Failed opening required 'wrongFile.php'
(include_path='.;C:\php5\pear')
in C:\home\website\test.php on line 5

The echo statement was not executed because the script execution
stopped after the fatal error.

It is recommended to use the require() function instead of include(),


because scripts should not continue executing if files are missing or
misnamed.

MODULE 10

(PHP Functions)

What are PHP Functions

A function is a block of code that can be executed whenever we need

28
it.

Creating PHP functions:

• All functions start with the word "function()"


• Name the function - It should be possible to understand what
the function does by its name. The name can start with a letter
or underscore (not a number)
• Add a "{" - The function code starts after the opening curly
brace
• Insert the function code
• Add a "}" - The function is finished by a closing curly brace

Example
A simple function that writes my name when it is called:

<html>
<body>

<?php
function writeMyName()
{
echo "Kai Jim Refsnes";
}

writeMyName();
?>

</body>
</html>

Use a PHP Function


Now we will use the function in a PHP script:

<html>
<body>

<?php
function writeMyName()
{
echo "Kai Jim Refsnes";
}

echo "Hello world!<br />";


echo "My name is ";
writeMyName();
echo ".<br />That's right, ";
writeMyName();
echo " is my name.";

29
?>

</body>
</html>

The output of the code above will be:

Hello world!
My name is Kai Jim Refsnes.
That's right, Kai Jim Refsnes is my name.

PHP Functions - Adding parameters to Functions


Our first function (writeMyName()) is a very simple function. It only
writes a static string.

To add more functionality to a function, we can add parameters. A


parameter is just like a variable.

You may have noticed the parentheses after the function name, like:
writeMyName(). The parameters are specified inside the parentheses.

Example 1

The following example will write different first names, but the same
last name:

<html>
<body>

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

echo "My name is ";


writeMyName("Kai Jim");

echo "My name is ";


writeMyName("Hege");

echo "My name is ";


writeMyName("Stale");
?>

</body>
</html>
The output of the code above will be:

My name is Kai Jim Refsnes.

30
My name is Hege Refsnes.
My name is Stale Refsnes.

Example 2

The following function has two parameters:

<html>
<body>

<?php
function writeMyName($fname,$punctuation)
{
echo $fname . " Refsnes" . $punctuation . "<br />";
}

echo "My name is ";


writeMyName("Kai Jim",".");

echo "My name is ";


writeMyName("Hege","!");

echo "My name is ";


writeMyName("Ståle","...");
?>

</body>
</html>

The output of the code above will be:

My name is Kai Jim Refsnes.


My name is Hege Refsnes!
My name is Ståle Refsnes...

PHP Functions - Return values


Functions can also be used to return values.

Example:

<html>

31
<body>

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

echo "1 + 16 = " . add(1,16)


?>

</body>
</html>

The output of the code above will be:

1 + 16 = 17

PHP Date / Time Functions

Function Description
checkdate() Validates a Gregorian date
date_default_timezone_ Returns the default time zone
get()
date_default_timezone_s Sets the default time zone
et()
date_sunrise() Returns the time of sunrise for a given day /
location
date_sunset() Returns the time of sunset for a given day /
location
date() Formats a local time/date
getdate() Returns an array that contains date and time
information for a Unix timestamp
gettimeofday() Returns an array that contains current time
information
gmdate() Formats a GMT/UTC date/time
gmmktime() Returns the Unix timestamp for a GMT date

gmstrftime() Formats a GMT/UTC time/date according to


locale settings
idate() Formats a local time/date as integer
localtime() Returns an array that contains the time
components of a Unix timestamp

32
microtime() Returns the microseconds for the current time

mktime() Returns the Unix timestamp for a date


strftime() Formats a local time/date according to locale
settings
strptime() Parses a time/date generated with strftime()

strtotime() Parses an English textual date or time into a


Unix timestamp
time() Returns the current time as a Unix timestamp

PHP HTTP Functions

Function Description
header() Sends a raw HTTP header to a client
headers_list() Returns a list of response headers sent (or
ready to send)
headers_sent() Checks if / where the HTTP headers have been
sent
setcookie() Sends an HTTP cookie to a client
setrawcookie() Sends an HTTP cookie without URL encoding
the cookie value

PHP Mail Functions

Function Description
ezmlm_hash() Calculates the hash value needed by the
EZMLM mailing list system
mail() Allows you to send emails directly from a
script
PHP Math Functions

Function Description
abs() Returns the absolute value of a number
acos() Returns the arccosine of a number
acosh() Returns the inverse hyperbolic cosine of a
number
asin() Returns the arcsine of a number

33
asinh() Returns the inverse hyperbolic sine of a
number
atan() Returns the arctangent of a number as a
numeric value between -PI/2 and PI/2
radians
atan2() Returns the angle theta of an (x,y) point as
a numeric value between -PI and PI
atanh() radians
Returns the inverse hyperbolic tangent of a
number
base_convert() Converts a number from one base to
another
bindec() Converts a binary number to a decimal
number
ceil() Returns the value of a number rounded
upwards to the nearest integer
cos() Returns the cosine of a number
cosh() Returns the hyperbolic cosine of a number
decbin() Converts a decimal number to a binary
number
dechex() Converts a decimal number to a
hexadecimal number
decoct() Converts a decimal number to an octal
number
deg2rad() Converts a degree to a radian number
exp() Returns the value of Ex
expm1() Returns the value of Ex - 1
floor() Returns the value of a number rounded
downwards to the nearest integer
fmod() Returns the remainder (modulo) of the
division of the arguments
getrandmax() Returns the maximum random number that
can be returned by a call to the rand()
function
hexdec() Converts a hexadecimal number to a
decimal number
hypot() Returns the length of the hypotenuse of a
right-angle triangle
is_finite() Returns true if a value is a finite number
is_infinite() Returns true if a value is an infinite number
is_nan() Returns true if a value is not a number

34
lcg_value() Returns a pseudo random number in the
range of (0,1)
log() Returns the natural logarithm (base E) of a
number
log10() Returns the base-10 logarithm of a number
log1p() Returns log(1+number)
max() Returns the number with the highest value
of two specified numbers
min() Returns the number with the lowest value
of two specified numbers
mt_getrandmax() Returns the largest possible value that can
be returned by mt_rand()
mt_rand() Returns a random integer using Mersenne
Twister algorithm
mt_srand() Seeds the Mersenne Twister random
number generator
octdec() Converts an octal number to a decimal
number
pi() Returns the value of PI
pow() Returns the value of x to the power of y
rad2deg() Converts a radian number to a degree
rand() Returns a random integer
round() Rounds a number to the nearest integer
sin() Returns the sine of a number
sinh() Returns the hyperbolic sine of a number
sqrt() Returns the square root of a number
srand() Seeds the random number generator
tan() Returns the tangent of an angle
tanh() Returns the hyperbolic tangent of an angle

PHP String Functions

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
chop() Alias of rtrim()

35
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 how many times an ASCII
character occurs within a string and returns
the information
crc32() Calculates a 32-bit CRC for a string
crypt() One-way string encryption (hashing)
echo() Outputs strings
explode() Breaks a string into an array
fprintf() Writes a formatted string to a specified
output stream
get_html_translation_table() Returns the translation table used by
htmlspecialchars() and htmlentities()
hebrev() Converts Hebrew text to visual text
hebrevc() Converts Hebrew text to visual text and
new lines (\n) into <br />
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()
levenshtein() Returns the Levenshtein distance between
two strings
localeconv() Returns locale numeric and monetary
formatting information
ltrim() Strips whitespace from the left side of a
string
md5() Calculates the MD5 hash of a string
md5_file() Calculates the MD5 hash of a file

36
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 a string
printf() Outputs a formatted string
quoted_printable_decode() Decodes a quoted-printable string
quotemeta() Quotes meta characters
rtrim() Strips whitespace from the right side of a
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_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

37
MODULE 11
(PHP Classes)

Introduction

Continuing our PHP functions article, we move on to creating classes.


Let me say right at the start that you can write perfectly effective and
useful PHP code without creating classes or going into object oriented
programming. Another thing is that PHP, at its core, is not an object
oriented language. This is because PHP was built from the C language,
which is at its core a procedural language, rather than a methodical
one. However, object oriented programming can be very powerful and
PHP programmers are increasingly taking advantage of these
capabilities, which have been greatly expanded since PHP4.

What is a class?

A class is a collection of variables and functions that serves a common


purpose. It gives you the ability to think about real world objects and
translate them into code. For example, let's try to describe a car.
The class "car" might have variables: $name_of_car, $wheels,

38
$steeringwheel, $windscreen, $lights, $pedals and $brakes. The
functions of a car might include Turnleft(),Turnright() and
Accelerate(). The function "Accelerate()" might take arguments such
as $increase_speed. Now, all of the above describes a car and what a
car does in both real terms and in code.

Now you might ask, couldn't this be done with regular functions and
variables? Yes, it could, especially if you were talking about one car.
But if you are talking about more than one car, then it would be
impossible to keep up with all the various variables and functions
associated with multiple cars. This is where classes become very
useful, because classes bring all those variables and functions under
one name. In this case, it's an object named "car." Now if you have
more than one car, all you have to do is instantiate that object. The
term instantiate basically means making a copy of the object. The new
copy will have all the variables and functions of the original object
available to it. You can include the class in any script that you create;
the class will work the same

A class has the following members:

• Attributes

• Methods

A good example of a class is Human. A human class would have


characteristics (attributes) of gender, hands, legs, age, and so forth. It
would also have actions (methods) such as walking, eating, running,
talking, and so on.

The syntax of a class is as follows:

class class_name{
var $variable_name;
functionfunction_name(){
statements;
}
}

Notice that within the class you use the var keyword to identify your
variables. At this point you can also assign a value to your variables.
Try to use the same naming conventions as you would for functions. It
is easier to recognize what a class is if it reflects its purpose(e.g. class
Human_class{). Another keyword, $this, is used to refer to the

39
instances of an object and its attributes e.g. $this->$variable_name.
To instantiate a class means to create a new version of it. Say we
have a class called dog, to instantiate it, we do this:

$rex = new dog();

Now, rex will have all the attributes of the class dog.

Creating a Class

Let's create a simple class to demonstrate the concepts


discussed above. Create a new PHP document called
sample_class.php. Our class is going to be called human.
We know that a human has legs and arms, which in our class are
going to represent the attributes. And we also know that humans
walk, eat and sleep. These will act as the methods.

Script: sample_class.php:

<?
class human{
var $legs=2;
var $arms=2;
}
//instantiate the class
$jude = new human();
echo "Jude has " .$jude->legs." legs";
?>

Here we have a new object created from our human class, called jude.
We also have a simple result saying how many legs Jude has. Note
how the variable "legs"(declared in the class) is used without the dollar
sign in the echo statement.

As well as calling attributes, we can also modify the attributes in the


same way. For example if we want the leg attribute to be increased by
say, one, so that legs now equals three, then this is what we do:

<?
class human{
var $legs=2;
var $arms=2;
}
//instantiate the class
$jude = new human();
< style="color: red;" lang="EN-GB">$jude-
>legs++; //increase legs by one
echo "Jude has " .$jude->legs." legs";
?>

40
OUTPUT:

Jude has 3 legs

As you can see, we can use attributes in a way that is similar to


how we use variables.

Adding an Attribute to the Objects

Let' create another instance to see what happens:

<?
class human{
var $legs=2;
var $arms=2;
}
//instantiate the class
< style="color: navy;" lang="EN-GB">$jude = new human();
< style="color: navy;" lang="EN-GB">$jane = new human();
< style="color: red;" lang="EN-GB">$jude-
>legs++; //increase legs by one
echo "Jude has " .$jude->legs." Legs<br>";
echo "Jane has " .$jane->legs." legs";
?>

Output:

Jude has 3 Legs

Jane has 2 Legs

As you can see from the result, we can modify the instance of a class
without touching the class definition itself. This re-usability is what
makes classes so useful.
Now we can also add a new attribute to any of the objects (jane or
jude). For example, let's add a new attribute to jane. The attribute is
hair color:

<?
class human{
var $legs=2;
var $arms=2;
}
//instantiate the class
$jude = new human();

41
$jane = new human();
< style="color: red;" lang="EN-GB">$jane->haircolor="brown";
$jude->legs++; //increase legs by one
echo "Jude has " .$jude->legs." Legs<br>";
echo "Jane has ".$jane->haircolor." Hair and was created from the
class <b>".get_class($jane)."</b> She also has <b>".$jane->legs."
</b>legs";
?>

So if we wanted to do the same thing for jude, we have to type all that
out again, which is time consuming. Instead, we are going to
automate this process by creating a function that will report on both
jane and jude. So let's change the class to include this function:

<?
class human{
var $legs=2;
< style="color: red;" lang="EN-GB">function report(){
< style="color: red;" lang="EN-GB">return "This <b>".get_class
($this)."</b> has <b>" .$this->haircolor. "</b> hair,and
<b>" .$this->legs. "</b> legs<br>" ;
}
}
//instantiate the class
$jude = new human();
$jane = new human();
$jane->haircolor="brown";
$jude->haircolor="black";
$jude->legs++; //increase legs by one
echo $jane->report();
echo $jude->report();
?>

Constructor Functions

This "problem" requires us to write special function called a


"constructor function." A constructor function is a function that is
written in a way that is very similar to a method of a class. The
difference is that a constructor function will be called every time a new
instance is made.

The syntax of a constructor function is:

function class_name(){
statements
}

Yes, the constructor function name must be the same as the class
name. And within the function you can include all the attributes that
are going to be included when an instance of the class is made. So,
let's add a constructor function that will sort out our problem:

42
<?
class human{
function human($hcolor){
$this->hcolor=$hcolor;
}
var $legs=2;
function report(){
return "This <b>".get_class($this)."</b> has <b>" .$this-
>haircolor. "</b> hair,and <b>" .$this->legs. "</b> legs<br>" ;
}
}
//instantiate the class
$jude = new human();
$jane = new human();
$jane->haircolor="brown";
$jude->haircolor="black";
$jude->legs++; //increase legs by one
echo $jane->report();
echo $jude->report();
?>

The " $this->hcolor=$hcolor;" line will install the hcolor variable as an


attribute when a new object is instantiated. So, instead of creating the
hair color attribute every time we instantiate a new object, it is
automatically called. The new class will look like this:

<?
class human{
function human($hcolor){
$this->hcolor=$hcolor;
}
var $legs=2;
function report(){
return "This <b>".get_class($this)."</b> has <b>" .$this-
>hcolor. "</b> hair,and <b>" .$this->legs. "</b> legs<br>" ;}
}
//instantiate the class
$jude = new human("black");
$jane = new human("brown");
$jude->legs++; //increase legs by one
echo $jane->report();
echo $jude->report();
?>

43
MODULE 12
(Cookies)

What is a Cookie?
A cookie is often used to identify a user. A cookie is a small file that
the server embeds on the user's computer. Each time the same
computer requests a page with a browser, it will send the cookie too.
With PHP, you can both create and retrieve cookie values.

Syntax:

PHP cookies can be set using the setcookie() function. The syntax is as
follows:

setcookie(name[, value[, expire[, path[, domain[, security]]]]])

• [name] The cookie name. The name of each cookie sent is


stored in the superglobal array $_COOKIE.

44
• [value] The cookie value. It is associated with the cookie
name.
• [expire] The time after which the cookie should expire in
seconds
• [path] Specifies the exact path on the domain that can use the
cookies.
• [domain] The domain that the cookie is available. If not
domain is specified, the default value is the value of the domain
in which cookie was created.
• [security] Specifies whether the cookie will be sent via HTTPS.
A value of 1 specifies that the cookie is sent over a secure
connection but it doesn't mean that the cookie is secure. It's
just a text file like every other cookie. A value of 0 denotes a
standard HTTP transmission.

Example:

<?PHP setcookie(“user”,”Alex Porter”, time()+3600); ?>

Note: The value of the cookie is automatically URLencoded when


sending the cookie, and automatically decoded when received (to
prevent URLencoding, use setrawcookie() instead).

How to Retrieve a Cookie Value?


The PHP $_COOKIE variable is used to retrieve a cookie value.

In the example below, we retrieve the value of the cookie named


"user" and display it on a page:

<?
//print a cookie
echo $_COOKIE[‘user’];

//prints all cookie

print_r($_COOKIE);

?>

In the following example we use the isset() function to find out if a


cookie has been set:

<html>
<body>

<?php

45
if (isset($_COOKIE["user"]))
echo "Welcome " . $_COOKIE["user"] . "!<br />";
else
echo "Welcome guest!<br />";
?></html></body>

How to Delete a Cookie?


When deleting a cookie you should assure that the expiration date is in
the past.

Delete example:

<?php
// set the expiration date to one hour ago
setcookie("user", "", time()-3600);
?>

MODULE 13

(Session)

What is PHP Session Variable

A PHP session variable is used to store information about, or change


settings for a user session. Session variables hold information about
one single user, and are available to all pages in one application.

When you are working with an application, you open it, do some
changes and then you close it. This is much like a Session. The
computer knows who you are. It knows when you start the application
and when you end. But on the internet there is one problem: the web
server does not know who you are and what you do because the HTTP
address doesn't maintain state.

A PHP session solves this problem by allowing you to store user

46
information on the server for later use (i.e. username, shopping items,
etc). However, session information is temporary and will be deleted
after the user has left the website. If you need a permanent storage
you may want to store the data in a database.

Sessions work by creating a unique id (UID) for each visitor and store
variables based on this UID. The UID is either stored in a cookie or is
propagated in the URL.

Starting a PHP Session


Before you can store user information in your PHP session, you must
first start up the session.

Note: The session_start() function must appear BEFORE the <html>


tag:

<?php session_start(); ?>

<html>
<body>

</body>
</html>

The code above will register the user's session with the server, allow
you to start saving user information, and assign a UID for that user's
session.

Storing a Session Variable


The correct way to store and retrieve session variables is to use the
PHP $_SESSION variable:

<?php
session_start();
// store session data
$_SESSION['views']=1;
?>

<html>
<body>

<?php
//retrieve session data
echo "Pageviews=". $_SESSION['views'];
?>

</body>

47
</html>

Output:

Pageviews=1

In the example below, we create a simple page-views counter. The


isset() function checks if the "views" variable has already been set. If
"views" has been set, we can increment our counter. If "views" doesn't
exist, we create a "views" variable, and set it to 1:

<?php

session_start();

if(isset($_SESSION['views']))
$_SESSION['views']=$_SESSION['views']+1;

else
$_SESSION['views']=1;
echo "Views=". $_SESSION['views'];
?>

Destroying a Session
If you wish to delete some session data, you can use the unset() or
the session_destroy() function.

The unset() function is used to free the specified session variable:

<?php
unset($_SESSION['views']);
?>

You can also completely destroy the session by calling the


session_destroy() function:

<?php
session_destroy();
?>

Note: session_destroy() will reset your session and you will lose all
your stored session data.

48
MODULE 14

(File Handling)

This module describes file handling in PHP.

How to Create a File


The fopen function needs two important pieces of information to
operate correctly. First, we must supply it with the name of the file
that we want it to open. Secondly, we must tell the function what we
plan on doing with that file (i.e. read from the file, write information,
etc).

Since we want to create a file, we must supply a file name and tell PHP
that we want to write to the file. Note: We have to tell PHP we are
writing to the file, otherwise it will not create a new file.

49
PHP Code:
$ourFileName = "testFile.txt";
$ourFileHandle = fopen($ourFileName, 'w') or die("can't open file");
fclose($ourFileHandle);

The file "testFile.txt" should be created in the same directory where


this PHP code resides. PHP will see that "testFile.txt" does not exist
and will create it after running this code. There's a lot of information in
those three lines of code, let's make sure you understand it.

• $ourFileName = "testFile.txt";

Here we create the name of our file, "testFile.txt" and store it


into a PHP String variable $ourFileName.

• $ourFileHandle = fopen($ourFileName, 'w') or die("can't


open file");

This bit of code actually has two parts. First we use the function
fopen and give it two arguments: our file name and we inform
PHP that we want to write by passing the character "w".

Second, the fopen function returns what is called a file handle,


which will allow us to manipulate the file. We save the file
handle into the $ourFileHandle variable. We will talk more about
file handles later on.

• fclose($ourFileHandle);

We close the file that was opened. fclose takes the file handle
that is to be closed. We will talk more about this more in the file
closing lesson.

PHP - Permissions

If you are trying to get this program to run and you are having errors,
you might want to check that you have granted your PHP file
access to write information to the hard drive. Setting permissions
is most often done with the use of an FTP program to execute a
command called CHMOD. Use CHMOD to allow the PHP file to
write to disk, thus allowing it to create a file.

Opening a File

The fopen() function is used to open files in PHP.

50
The first parameter of this function contains the name of the file to be
opened and the second parameter specifies in which mode the file
should be opened in:

<html>
<body>
<?php
$f=fopen("welcome.txt","r");
?>
</body>
</html>

The file may be opened in one of the following modes:

File Modes Description

r Read only. File pointer at the start of the file

r+ Read/Write. File pointer at the start of the file

w Write only. Truncates the file (overwriting it). If the file doesn't exist,
fopen() will try to create the file

w+ Read/Write. Truncates the file (overwriting it). If the file doesn't exist,
fopen() will try to create the file

a Append. File pointer at the end of the file. If the file doesn't exist, fopen()
will try to create the file

Read/Append. File pointer at the end of the file. If the file doesn't exist,
a+
fopen() will try to create the file

x Create and open for write only. File pointer at the beginning of the file. If
the file already exists, the fopen() call will fail and generate an error. If
the file does not exist, try to create it

x+ Create and open for read/write. File pointer at the beginning of the file. If
the file already exists, the fopen() call will fail and generate an error. If
the file does not exist, try to create it

Note: If the fopen() function is unable to open the specified file, it


returns 0 (false).

Example

The following example generates a message if the fopen() function is


unable to open the specified file:

<html>
<body>
<?php
if (!($f=fopen("welcome.txt","r")))
exit("Unable to open file!");
?>
</body>
</html>

51
Closing a File

The fclose() function is used to close a file.

In PHP it is not system critical to close all your files after using them
because the server will close all files after the PHP code finishes
execution. However the programmer is still free to make mistakes
(i.e. editing a file that you accidentally forgot to close). You should
close all files after you have finished with them because it's a good
programming practice and because we told you to!

fclose($f);

EXAMPLE:

$ourFileName = "testFile.txt";
$ourFileHandle = fopen($ourFileName, 'w') or die("can't open
file");
fclose($ourFileHandle);

The function fclose requires the file handle that we want to close down.
In our example we set our variable "$fileHandle" equal to the file
handle returned by the fopen function.

After a file has been closed down with fclose it is impossible to read,
write or append to that file unless it is once more opened up with the
fopen function.

Writing to a file

Now that you know how to open and close a file, lets get on to the
most useful part of file manipulation, writing! There is really only one
main function that is used to write and it's logically called fwrite.
Before we can write information to our test file we have to use the
function fopen to open the file for writing.

$myFile = "testFile.txt";
$fh = fopen($myFile, 'w');

We can use php to write to a text file. The fwrite function allows data
to be written to any type of file. Fwrite's first parameter is the file
handle and its second parameter is the string of data that is to be
written. Just give the function those two bits of information and you're

52
good to go! Below we are writing a couple of names into our test file
testFile.txt and separating them with a carriage return.

$myFile = "testFile.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
$stringData = "Bobby Bopper\n";
fwrite($fh, $stringData);
$stringData = "Tracy Tanner\n";
fwrite($fh, $stringData);
fclose($fh);

The $fh variable contains the file handle for testFile.txt. The file handle
knows the current file pointer, which for writing, starts out at the
beginning of the file.

We wrote to the file testFile.txt twice. Each time we wrote to the file
we sent the string $stringData that first contained Bobby Bopper and
second contained Tracy Tanner. After we finished writing we closed the
file using the fclose function.

If you were to open the testFile.txt file in NOTEPAD it would contain


this:

Bobby Bopper
Tracy Tanner

Reading from a File

The fread function is the staple for getting data out of a file. The
function requires a file handle, which we have, and an integer to tell
the function how much data, in bytes, it is supposed to read.

EXAMPLE:

$myFile = "testFile.txt";
$fh = fopen($myFile, 'r');
$theData = fread($fh, 5);
fclose($fh);
echo $theData;

Display:
Flopp

The first five characters from the testFile.txt file are now stored inside

53
$theData. You could echo this string, $theData, or write it to another
file.

If you wanted to read all the data from the file, then you need to get
the size of the file. The filesize function returns the length of a file, in
bytes, which is just what we need! The filesize function requires the
name of the file that is to be sized up.

$myFile = "testFile.txt";
$fh = fopen($myFile, 'r');
$theData = fread($fh, filesize($myFile));
fclose($fh);
echo $theData;

The feof() function is used to determine if the end of file is true.

Note: You cannot read from files opened in w, a, and x mode!

if (feof($f))
echo "End of file";

Reading a Character

The fgetc() function is used to read a single character from a file.

Note: After a call to this function the file pointer has moved to the
next character.

Example

The example below reads a file character by character, until the end of
file is true:

<?php
if (!($f=fopen("welcome.txt","r")))
exit("Unable to open file.");
while (!feof($f))
{
$x=fgetc($f);
echo $x;
}
fclose($f);
?>

Deleting a File

54
You know how to create a file. You know how to open a file in an
assortment of different ways. You even know how to read and write
data from a file! Now it's time to learn how to destroy (delete) files.
In PHP you delete files by calling the unlink function.

File Unlink
When you view the contents of a directory you can see all the files that
exist in that directory because the operating system or application that
you are using displays a list of filenames. You can think of these
filenames as links that join the files to the directory you are currently
viewing. If you unlink a file, you are effectively causing the system to
forget about it or delete it!

Before you can delete (unlink) a file, you must first be sure that it is
not open in your program. Use the fclose function to close down an
open file.

$myFile = "testFile.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
fclose($fh);

Now to delete testFile.txt we simply run a PHP script that is located in


the same directory. Unlink just needs to know the name of the file to
start working its destructive magic.

$myFile = "testFile.txt";
unlink($myFile);

Unlink: Safety First!


With great power comes a slough of potential things you can mess up!
When you are performing the unlink function be sure that you are
deleting the right file!

File Upload: HTML Form


Before you can use PHP to manage your uploads, you must first build
an HTML form that lets users select a file to upload. See our HTML
Form lesson for a more in-depth look at forms.

HTML Code:
<form enctype="multipart/form-data" action="uploader.php"
method="POST">
<input type="hidden" name="MAX_FILE_SIZE" value="100000" />
Choose a file to upload: <input name="uploadedfile" type="file" /><br
/>
<input type="submit" value="Upload File" />

55
</form>

Here is a brief description of the important parts of the above code:

• enctype="multipart/form-data" - Necessary for our to-be-


created PHP file to function properly.
• action="uploader.php" - The name of our PHP page that will
be created, shortly.
• method="POST" - Informs the browser that we want to send
information to the server using POST.
• input type="hidden" name="MA... - Sets the maximum
allowable file size, in bytes, that can be uploaded. This safety
mechanism is easily bypassed and we will show a solid backup
solution in PHP. We have set the max file size to 100KB in this
example.
• input name="uploadedfile" - uploadedfile is how we will
access the file in our PHP script.

Save that form code into a file and call it upload.html. If you view it in
a browser it should look like this:

File Upload: What's the PHP Going to Do?


Now that we have the right HTML form we can begin to code the PHP
script that is going to handle our uploads. Typically, the PHP file should
make a key decision with all uploads: keep the file or throw it away. A
file might be thrown away from many reasons, including:

• The file is too large and you do not want to have it on your
server.
• You wanted the person to upload a picture and they uploaded
something else, like an executable file (.exe).
• There were problems uploading the file and so you can't keep it.

This example is very simple and omits the code that would add such
functionality.

File Upload: uploader.php


When the uploader.php file is executed, the uploaded file exists in a
temporary storage area on the server. If the file is not moved to a
different location it will be destroyed! To save our precious file we are
going to need to make use of the $_FILES associative array.

The $_FILES array is where PHP stores all the information about files.
There are two elements of this array that we will need to understand
for this example.

56
• uploadedfile - uploadedfile is the reference we assigned in our
HTML form. We will need this to tell the $_FILES array which file
we want to play around with.
• $_FILES['uploadedfile']['name'] - name contains the original
path of the user uploaded file.
• $_FILES['uploadedfile']['tmp_name'] - tmp_name contains
the path to the temporary file that resides on the server. The file
should exist on the server in a temporary directory with a
temporary name.

Now we can finally start to write a basic PHP upload manager script!
Here is how we would get the temporary file name, choose a
permanent name, and choose a place to store the file.

// Where the file is going to be placed


$target_path = "uploads/";

/* Add the original filename to our target path.


Result is "uploads/filename.extension" */
$target_path = $target_path . basename( $_FILES['uploadedfile']
['name']);
$_FILES['uploadedfile']['tmp_name'];

NOTE: You will need to create a new directory in the directory where
uploader.php resides, called "uploads", as we are going to be saving
files there.

We now have all we need to successfully save our file to the server.
$target_path contains the path where we want to save our file to.

File Upload: move_uploaded_file Function


Now all we have to do is call the move_uploaded_file function and let
PHP do its magic. The move_uploaded_file function needs to know 1)
The path of the temporary file (check!) 2) The path where it is to be
moved to (check!).

$target_path = "uploads/";

$target_path = $target_path . basename( $_FILES['uploadedfile']


['name']);

if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'],
$target_path)) {
echo "The file ". basename( $_FILES['uploadedfile']['name']).
" has been uploaded";
} else{
echo "There was an error uploading the file, please try
again!";
}

57
If the upload is successful, then you will see the text "The file filename
has been uploaded". This is because $move_uploaded_file returns true
if the file was moved, and false if it had a problem.

If there was a problem then the error message "There was an error
uploading the file, please try again!" would be displayed.

MODULE 15
(Introduction to MySQL)

What is MySQL?
MySQL is a database. A database defines a structure for storing
information.

In a database, there are tables. Just like HTML tables, database tables
contain rows, columns, and cells.

Databases are useful when storing information categorically. A


company may have a database with the following tables: "Employees",
"Products", "Customers" and "Orders".

Database Tables
A database most often contains one or more tables. Each table has a

58
name (e.g. "Customers" or "Orders"). Each table contains records
(rows) with data.

Below is an example of a table called "Persons":

LastName FirstName Address City


Hansen Ola Timoteivn 10 Sandnes
Svendson Tove Borgvn 23 Sandnes
Pettersen Kari Storgt 20 Stavanger
The table above contains three records (one for each person) and four
columns (LastName, FirstName, Address, and City).

Queries
A query is a question or a request.

With MySQL, we can query a database for specific information and have a
recordset returned.

Look at the following query:

SELECT LastName FROM


Persons

The query above selects all the data in the LastName column in the Persons
table, and will return a recordset like this:

LastName
Hansen
Svendson
Pettersen

59
Connecting to a MySQL Database
Before you can access and work with data in a database, you must create a
connection to the database.

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

Syntax

mysql_connect(servername,username,password);

Parameter Description
servername Optional. Specifies the server to connect to.
Default value is "localhost:3306"
username Optional. Specifies the username to log in with.
Default value is the name of the user that owns
password the serverSpecifies
Optional. process the password to log in with.
Default is ""

Note: There are more available parameters, but the ones listed above are
the most important. Visit our full PHP MySQL Reference for more details.

Example

In the following example we store the connection in a variable ($con) for


later use in the script. The "die" part will be executed if the connection fails:

<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}

// some code

?>

60
Closing a Connection
The connection will be closed as soon as the script ends. To close the
connection before, use the mysql_close() function.

<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}

// some code

mysql_close($con);
?>

A database holds one or multiple tables.

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

Syntax
CREATE DATABASE database_name

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

Example

In the following example we create a database called "my_db":

61
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}

if (mysql_query("CREATE DATABASE my_db",$con))


{
echo "Database created";
}
else
{
echo "Error creating database: " . mysql_error();
}

mysql_close($con);
?>

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

Syntax
CREATE TABLE table_name
(
column_name1 data_type,
column_name2 data_type,
column_name3 data_type,
.......
)

We must add the CREATE TABLE statement to the mysql_query() function


to execute the command.

Example

The following example shows how you can create a table named "person",
with three columns. The column names will be "FirstName", "LastName" and
"Age":

62
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}

// Create database
if (mysql_query("CREATE DATABASE my_db",$con))
{
echo "Database created";
}
else
{
echo "Error creating database: " . mysql_error();
}

// Create table in my_db database


mysql_select_db("my_db", $con);
$sql = "CREATE TABLE person
(
FirstName varchar(15),
LastName varchar(15),
Age int
)";
mysql_query($sql,$con);

mysql_close($con);
?>

Important: A database must be selected before a table can be created.


The database is selected with the mysql_select_db() function.

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

MySQL Data Types


Below is the different MySQL data types that can be used:

Numeric Data Description


Types
int(size) Hold integers only. The maximum number of digits can be
smallint(size) specified in the size parameter
tinyint(size)
mediumint(size)
bigint(size)

63
decimal(size,d) Hold numbers with fractions. The maximum number of
double(size,d) digits can be specified in the size parameter. The
float(size,d) maximum number of digits to the right of the decimal is
specified in the d parameter

Textual Data Description


Types
char(size) Holds a fixed length string (can contain letters, numbers,
and special characters). The fixed size is specified in
parenthesis

varchar(size) Holds a variable length string (can contain letters,


numbers, and special characters). The maximum size is
specified in parenthesis
tinytext Holds a variable string with a maximum length of 255
characters
text Holds a variable string with a maximum length of 65535
blob characters
mediumtext Holds a variable string with a maximum length of
mediumblob 16777215 characters
longtext Holds a variable string with a maximum length of
longblob 4294967295 characters

Date Data Types Description


date(yyyy-mm- Holds date and/or time
dd)
datetime(yyyy-
mm-dd
hh:mm:ss)
timestamp(yyyym
mddhhmmss)
time(hh:mm:ss)

Misc. Data Types Description


enum(value1,valu ENUM is short for ENUMERATED list. Can store one of up
e2,ect) to 65535 values listed within the ( ) brackets. If a value is
inserted that is not in the list, a blank value will be
inserted

set SET is similar to ENUM. However, SET can have up to 64


list items and can store more than one choice

64
Primary Keys and Auto Increment Fields
Each table 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 primary key field is always indexed. There is no exception to this rule!
You must index the primary key field so the database engine can quickly
locate rows based on the key's value.

The following example sets the personID 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.

Example

$sql = "CREATE TABLE person


(
personID int NOT NULL AUTO_INCREMENT,
PRIMARY KEY(personID),
FirstName varchar(15),
LastName varchar(15),
Age int
)";

mysql_query($sql,$con);

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

Insert Data Into a Database Table


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

Syntax

INSERT INTO table_name


VALUES (value1, value2,....)

65
You can also specify the columns where you want to insert the data:

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


VALUES (value1, value2,....)

Note: SQL statements are not case sensitive. INSERT INTO is the same as
insert into.

To get PHP to execute the statements above we must use the


mysql_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 "Person", 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 "Person"
table:
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}

mysql_select_db("my_db", $con);

mysql_query("INSERT INTO person (FirstName, LastName, Age)


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

mysql_query("INSERT INTO person (FirstName, LastName, Age)


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

mysql_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 "Person" table.

Here is the HTML form:

66
<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 mysql_query() function executes the INSERT INTO
statement, and a new record will be added to the database table.

Below is the code in the "insert.php" page:

<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}

mysql_select_db("my_db", $con);

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


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

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

mysql_close($con)
?>

67
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

Note: SQL statements are not case sensitive. SELECT is the same as select.

To get PHP to execute the statement above we must use the mysql_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 "Person" table (The
* character selects all of the data in the table):

<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}

mysql_select_db("my_db", $con);

$result = mysql_query("SELECT * FROM person");

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

mysql_close($con);
?>

68
The example above stores the data returned by the mysql_query() function
in the $result variable. Next, we use the mysql_fetch_array() function to
return the first row from the recordset as an array. Each subsequent call to
mysql_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 = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}

mysql_select_db("my_db", $con);

$result = mysql_query("SELECT * FROM person");

echo "<table border='1'>


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

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

mysql_close($con);
?>

The output of the code will be:

Firstname Lastname

69
Glenn Quagmire
Peter Griffin

To select only data that matches a specified criteria, add a WHERE clause to
the SELECT statement.

The WHERE clause


To select only data that matches a specific criteria, add a WHERE clause to
the SELECT statement.

Syntax
SELECT column FROM table
WHERE column operator value

The following operators can be used with the WHERE clause:

Operator Description
= Equal
!= Not equal
> Greater than
< Less than
>= Greater than or equal
<= Less than or equal
BETWEEN Between an inclusive range
LIKE Search for a pattern

Note: SQL statements are not case sensitive. WHERE is the same as where.

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

Example

The following example will select all rows from the "Person" table, where
FirstName='Peter':

70
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}

mysql_select_db("my_db", $con);

$result = mysql_query("SELECT * FROM person


WHERE FirstName='Peter'");

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

?>

The output of the code above will be:

Peter Griffin

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.

Syntax

SELECT column_name(s)
FROM table_name
ORDER BY column_name

Note: SQL statements are not case sensitive. ORDER BY is the same as
order by.

Example

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

71
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}

mysql_select_db("my_db", $con);

$result = mysql_query("SELECT * FROM person ORDER BY age");

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

mysql_close($con);
?>

The output of the code above will be:

Glenn Quagmire 33
Peter Griffin 35

Sort Ascending or Descending


If you use the ORDER BY keyword, the sort-order of the recordset is
ascending by default (1 before 9 and "a" before "p").

Use the DESC keyword to specify a descending sort-order (9 before 1 and


"p" before "a"):
SELECT column_name(s)
FROM table_name
ORDER BY column_name DESC

Order by Two Columns


It is 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 identical:

SELECT column_name(s)
FROM table_name
ORDER BY column_name1, column_name2

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

Update Data In a Database


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

Syntax
UPDATE table_name
SET column_name = new_value
WHERE column_name = some_value

Note: SQL statements are not case sensitive. UPDATE is the same as
update.

To get PHP to execute the statement above we must use the mysql_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 "Person". Here is how it


looks:
FirstName LastName Age
Peter Griffin 35
Glenn Quagmire 33
The following example updates some data in the "Person" table:

<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}

mysql_select_db("my_db", $con);

mysql_query("UPDATE Person SET Age = '36'


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

mysql_close($con);
?>

After the update, the "Person" table will look like this:

73
FirstName LastName Age
Peter Griffin 36
Glenn Quagmire 33

The DELETE FROM statement is used to delete rows from a database 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 column_name = some_value

Note: SQL statements are not case sensitive. DELETE FROM is the same as
delete from.

To get PHP to execute the statement above we must use the mysql_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 "Person". Here is how it


looks:

FirstName LastName Age


Peter Griffin 35
Glenn Quagmire 33
The following example deletes all the records in the "Person" table where
LastName='Griffin':

74
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}

mysql_select_db("my_db", $con);

mysql_query("DELETE FROM Person WHERE LastName='Griffin'");

mysql_close($con);
?>

After the deletion, the table will look like this:

FirstName LastName Age


Glenn Quagmire 33

MODULE 16

(MySQL Functions)

75
Function Description
mysql_affected_rows() Returns the number of affected rows in the previous
MySQL operation
mysql_change_user() Deprecated. Changes the user of the current MySQL
connection
mysql_client_encoding() Returns the name of the character set for the current
connection
mysql_close() Closes a non-persistent MySQL connection

mysql_connect() Opens a non-persistent MySQL connection

mysql_create_db() Deprecated. Creates a new MySQL database. Use


mysql_query() instead
mysql_data_seek() Moves the record pointer
mysql_db_name() Returns a database name from a call to
mysql_list_dbs()
mysql_db_query() Deprecated. Sends a MySQL query. Use
mysql_select_db() and mysql_query() instead

mysql_drop_db() Deprecated. Deletes a MySQL database. Use


mysql_query() instead
mysql_errno() Returns the error number of the last MySQL
operation
mysql_error() Returns the error description of the last MySQL
operation
mysql_escape_string() Deprecated. Escapes a string for use in a
mysql_query. Use mysql_real_escape_string()
instead
mysql_fetch_array() Returns a row from a recordset as an associative
array and/or a numeric array
mysql_fetch_assoc() Returns a row from a recordset as an associative
array
mysql_fetch_field() Returns column info from a recordset as an object

mysql_fetch_lengths() Returns the length of the contents of each field in a


result row
mysql_fetch_object() Returns a row from a recordset as an object

mysql_fetch_row() Returns a row from a recordset as a numeric array

76
mysql_field_flags() Returns the flags associated with a field in a
recordset
mysql_field_len() Returns the maximum length of a field in a recordset

mysql_field_name() Returns the name of a field in a recordset


mysql_field_seek() Moves the result pointer to a specified field

mysql_field_table() Returns the name of the table the specified field is in

mysql_field_type() Returns the type of a field in a recordset


mysql_free_result() Free result memory
mysql_get_client_info() Returns MySQL client info
mysql_get_host_info() Returns MySQL host info
mysql_get_proto_info() Returns MySQL protocol info
mysql_get_server_info() Returns MySQL server info
mysql_info() Returns information about the last query
mysql_insert_id() Returns the AUTO_INCREMENT ID generated from
the previous INSERT operation

mysql_list_dbs() Lists available databases on a MySQL server

mysql_list_fields() Deprecated. Lists MySQL table fields. Use


mysql_query() instead
mysql_list_processes() Lists MySQL processes
mysql_list_tables() Deprecated. Lists tables in a MySQL database. Use
mysql_query() instead
mysql_num_fields() Returns the number of fields in a recordset

mysql_num_rows() Returns the number of rows in a recordset

mysql_pconnect() Opens a persistent MySQL connection


mysql_ping() Pings a server connection or reconnects if there is no
connection
mysql_query() Executes a query on a MySQL database
mysql_real_escape_strin Escapes a string for use in SQL statements
g()
mysql_result() Returns the value of a field in a recordset
mysql_select_db() Sets the active MySQL database
mysql_stat() Returns the current system status of the MySQL
server

77
mysql_tablename() Deprecated. Returns the table name of field. Use
mysql_query() instead
mysql_thread_id() Returns the current thread ID
mysql_unbuffered_query Executes a query on a MySQL database (without
() fetching / buffering the result)

78

You might also like