Cover  Copyright  Contents  Reference  Index  previous  next
Chapter 1. AN INTRODUCTION TO PHP
Contents:
1. SAMPLES
1.1 A simple PHP page
1.2 Client/server communication
1.3 Database access
1.3.1 Database creation
1.3.2 Table creation
1.3.3 Data insertion
1.3.4 Data query
1.3.5 Client side query
1.3.6 Table updating
1.4 Generating an XML page

2. CONCEPTS
2.1 How an HTML page is processed
2.1.1 PHP sequences within an HTML page
2.1.2 Generating the result page
2.1.3 Generating an HTML page with Javascript
2.1.4 Generating an XML page
2.1.5 Submitting a request
2.2 Data and variables
2.2.1 Data types
2.2.2 Variable names and types
Variable names
Variable types
Array Variables
2.2.3 Superglobal variables
2.3 Conditions
2.4 Operations
2.5 Expressions
2.2.1 Expressions explained
2.2.2 Precedence
2.6 Functions
2.6.1 Core functions
2.6.2 The MySQL extended functions
2.7 Control statements
2.7.1 The if ... else statement
2.7.2 The while statement
2.7.3 The for statement
2.8 Illustration

3. SYNTAX SUMMARY
3.1 PHP tags
3.2 Data types
3.3 Variable name
3.4 Variable types
3.5 Operations
3.6 Functions
3.7 Control statements

 

A PHP application basically involves PHP scripts which handle data exchanged between clients at remote terminals and a server site which processes and registers the data on some storage facility, usually one or more databases, and serves them to the clients on their requests.

Client/Server

The present chapter shows sample scripts to handle the basic operations involved in these proceedings:

-presenting a data entry form to the client
-retrieving the data entered by the client
-handling the basic database operations: creating databases and tables, inserting and retrieving data from the databases

and explains the concepts involved therein.

1. SAMPLES

In the following are a number of scripts intended to be run by a Web server upon request from users. All the scripts shown are available in the 'samples' directory accompanying this document. You can request them and have their response displayed on your screen, by installing a Web server and a PHP processor in your computer.

Appendix 1. Installing the supporting software shows how simply to install an Apache Web server, and a PHP processor, and to set the system to work.

To call the sample scripts directly from the samples directory, you can create an alias for this directory, and call the scripts under this alias.

In a Windows system, suppose you installed the present document package in the directory 'C:\books\PHP\', then the samples directory has the path name 'C:\books\PHP\samples\' (please, check). You define an alias, say hpp, for this directory by adding the following line to the Apache configuration file (%ApacheHome%/conf/httpd.conf -- where %ApacheHome% represents the directory where you installed the Apache system):

Alias /hpp "C:/books/PHP/samples"
(you can put the line anywhere in the file, but it is advisable to group it with the other 'alias' directives).

Then you would be able to request a script called somescript.php from the samples directory, by entering the following line from an Internet Explorer or a Netscape navigator or any other browser, window:

http://localhost/hpp/somescript.php
where the hpp within the slashes is the alias you chose for the samples directory, in the above Alias directive (if you chose another name, put this other name here).

1.1 A simple PHP page

<!-- MyFirst.php -->
<HTML><HEAD>
<TITLE>MY FIRST PHP PAGE</TITLE>
</HEAD>
<BODY style="background-color:#99EEBB;">
<IMG src="images/Snowdrop.png">
<b style="color:red; padding:5em;">
<?PHP
  echo "Hello, world!";
?>
</b>
</BODY>
</HTML>
Shown on the left is a sample PHP page made of PHP code embedded in a HTML page.

The PHP code is the text sequence in blue characters, enclosed within a starting and an ending mark:

<?PHPis the starting mark,
?>is the ending mark.
In between is the code to be processed by PHP. Here, it includes just one line, which is the echo statement that writes out the sequence "Hello, world!". The HTML code is anything an ordinary HTML page can contain. Here the HTML code defines a light green background for the page, and includes an image.
You can schedule this page from our site, by entering its address to your browser:
http://www.hatayservices.com/PHP/MyFirst.php

Depending on your Internet provider, you may have to manually establish a connection before being able to call any page from the Internet.

The result will look like this:

Hello, world!

You can display the page source which shows as:

<HTML><HEAD><TITLE>MY FIRST PHP PAGE</TITLE></HEAD>
<BODY style="background-color:#99EEBB;">
<IMG src="Images/Snowdrop.png">
<b style="color:red; padding:5em;">
Hello, world!</b>
</BODY>
</HTML>
This comes from the original PHP page where the HTML code has been preserved, and the PHP code replaced by its result: the PHP marks were deleted, and the echo statement replaced by the character string it was to write out.

This page was processed by your browser to display what you see, then saved among the Internet Temporary files.

If you installed Apache and the PHP system as suggested above, you can run the script which is also contained in the samples directory, by submitting the following request:

http://localhost/hpp/MyFirst.php

Normally, you can submit it from this page.

1.2 Client/Server communication

PHP is all about complementing an HTML page (or XML in the future, perhaps) with information coming from the client and/or the server, before sending the page to the client.

In this example, an HTML page is first used for the client to fill in specific information which is sent to the server along with a request for a PHP page. The latter is an HTML page to be complemented by the information sent in by the client. Client information is merely sent back. This is just an example to show how things work. The next paragraph will show how information can be retrieved from a database.

The first code shown below is a regular HTML page that contains a FORM element (a working knowledge of HTML helps.)

HTML data entry form
DataEntry.html (may not work -- explanation follows ...)

<!-- DataEntry.html -->
<HTML><HEAD><TITLE>DATA ENTRY</TITLE></HEAD>
<BODY>
<FORM ACTION="DataRetrieve.php" METHOD="POST">
<TABLE>
 <TR><TD style="color:blue;"><b>First Name</b>
     <TD><INPUT TYPE="text" NAME="firstName" 
          STYLE="background:lime">
 <TR><TD style="color:blue;"><b>Last Name</b>
     <TD><INPUT TYPE="text" NAME="lastName" 
          STYLE="background:lime">
 <TR><TD style="color:blue;"><b>e-mail</b>
     <TD><INPUT TYPE="text" NAME="eMail" 
          STYLE="background:lime">
 <TR><TD style="vertical-align:top; 
                color:blue;font-weight:bold;">Sex: 
     <TD><INPUT TYPE="radio" NAME="sex"
                VALUE="M">Male<BR>
         <INPUT TYPE="radio" NAME="sex" 
                VALUE="F">Female
 <TR><TD colspan="2">
     <SPAN STYLE="color:blue;font-weight:bold;">
     Favourite occupations</SPAN>
     <br>- please click one or more
 <TR><TD><TD><INPUT TYPE="checkbox" 
              NAME="riding">Horseback riding
 <TR><TD><TD><INPUT TYPE="checkbox" 
              NAME="hunting">Fox hunting
 <TR><TD><TD><INPUT TYPE="checkbox" 
              NAME="bird">Bird watching
 <TR><TD><TD><INPUT TYPE="checkboxx" 
              NAME="travels">Travels
 <TR><TD><BUTTON TYPE="submit" 
                 NAME="sub"><b STYLE="color:red">
                 SUBMIT</BUTTON>
</TABLE></FORM></BODY></HTML>
This element contains a number of fields to be filled in by the user. These are:
- 3 INPUT text type fields
- 2 INPUT radio type fields
- 4 INPUT checkbox type fields
In the HTML source page, these fields are identified by the value of their NAME attribute. They are made to stand out in blue characters.

PHP comes in through the ACTION attribute value 'DataRetrieves.php' which references the PHP page to be scheduled when the user clicks on the 'SUBMIT' button. The attribute METHOD=POST specifies that the data from this page are to be retrieved by PHP using the POST method (the consequence of which will be seen in the next script below).

The HTML data entry page as displayed to the user looks like this:

First Name
Last Name
e-mail
Sex: Male
Female
Favourite occupations
- please click one or more
Horseback riding
Fox hunting
Bird watching
Travels
PHP data retrieving page
<!-- DataRetrieve.php -->
<HTML><HEAD>
<TITLE>DATA DISPLAY</TITLE>
</HEAD>
<BODY>
<DIV style="font-size:120%; 
     font-weight:bold; color:red; 
     text-align:center;
     margin-bottom:2em; ">
DATA RECEIVED
</DIV>

<TABLE>
<TR><TD>First name
    <TD><?php print ($firstName) ?>
<TR><TD>Last name
<?php print ("<TD>$lastName"); 
      print ("<TR><TD>e-mail");
      print ("<TD>$eMail") ?>
<TR><TD>Sex
    <TD><?php print ($sex) ?>
<TR><TD>Favourites
<TR><TD>Horseback riding
    <TD><?php print($riding) ?>
<TR><TD>Fox hunting
    <TD><?php print($hunting) ?>
<TR><TD>Bird watching
    <TD><?php print($bird) ?>
<TR><TD>Travels
    <TD><?php print($travels) ?>
<TR><TD>
<FORM ACTION="DataEntry.html">
  <BUTTON TYPE="submit" NAME="html">
  NEXT</BUTTON>
</FORM>
<FORM ACTION="TheEnd.html">
 <BUTTON TYPE="submit" NAME="end">
 END</BUTTON>
</FORM>
</TABLE>
</BODY>
</HTML>
Shown on the left is the source code of the PHP page to be scheduled when the SUBMIT button of the above Data Entry HTML page is clicked. This page in an HTML page interspersed with PHP code. The scheduling is done by the PHP processor which has to be installed as part of the Web Server, also to be installed before any PHP processing can be considered.

The PHP processor executes the PHP code present in the page. This code is made up of the text portions enclosed within the <?php ... ?> tags. These are all of the text sequences set in blue characters.

INPUT value

The first sequence is print($firstName). It involves a print function and a $firstName variable. A PHP variable always starts with the $ sign. This variable here has the same name as an INPUT field from the calling HTML page. It is set to the value of this field when the PHP page is scheduled.

The print function has an argument enclosed within parentheses. It writes this argument out onto the PHP page, at the position where it is located.

Everything that a print function writes out goes to the PHP page. Instead of merely printing out the PHP variables, the function can write out HTML elements. In print("<TD>$lastName"), the element <TD> is written out, followed by the value of the variable $lastName. The latter is said to be expanded, i.e. it is replaced by its value before printing occurs. The next print writes out pure HTML code: <TR><TD>e-mail.

After all of the PHP statements are excuted, the HTML page as resulted from the unchanged original HTML code (in black), and the results of the print functions, is sent to the client side, i.e. to the browser from which the DataRetrieve.php page was called.

The $sex variable is associated with a set of radio type fields, with the same name, but different values, as specified by the 'value' attribute. The value it receives is that of the selected field.

The INPUT fields of the checkbox type have each its own name. Such a field has a value of "ON" when selected; when not selected, it is not present in the data flow emitted by the HTML page, and the corresponding variable in the PHP page is not defined (which is different from being an empty string, or having a null value.)

The HTML page as generated by the PHP processing, and sent to the client's browser, looks as shown below on the left:
<HTML><HEAD><TITLE>DATA DISPLAY</TITLE></HEAD>
<BODY><DIV style="font-size:120%; font-weight:bold; 
     margin-bottom:2em; text-align:center; 
     color:red">DATA RECEIVED</DIV>
<TABLE>
<TR><TD>First name<TD>Jack
<TR><TD>Last name<TD>Russell
<TR><TD>e-mail<TD>jrussell@terrier.ca
<TR><TD>Sex<TD>M
<TR><TD>Favourites
<TR><TD>Horseback riding<TD>on
<TR><TD>Fox hunting<TD>on
<TR><TD>Bird watching<TD>on
<TR><TD>Travels<TD>
<TR><TD><FORM ACTION="DataEntry.html">
<BUTTON TYPE="submit" NAME="html">NEXT</BUTTON>
</FORM>
<FORM ACTION="TheEnd.html">
<BUTTON TYPE="submit" NAME="end">END</BUTTON>
</FORM></TABLE>
</BODY></HTML>
The PHP page has 2 buttons of the submit type:
- the one labelled "NEXT" causes the DataEntry.html page to be called again
- the other labelled "END" causes the TheEnd.html page to be called, which ends the session.
The client's browser displays the page as:
DATA RECEIVED
First nameJack
Last nameRussell
e-mailjrussell@terrier.ca
SexM
Favourites
Horseback ridingon
Fox huntingon
Bird watchingon
Travels

All that was explained above might not work, i.e. the data fields in the result might be undefined. This would be because your PHP processor has a protection set on, which prevents the received data from being directly set into the intended variable ("Jack" would not go to $firstName).

Data received from the client are to be found in the so-called superglobal array $_POST.
An array is a data structure composed of a number of items. Each item has a value, and is identified by a key set within square brackets, like this: $_POST['firstName'].

The $_POST array is created by the PHP processor, when data are received through the POST method. In this array, the keys are the names of the INPUT elements from the user's FORM, and the values are the values of these elements.

DataEntryBis.html
<?php
if (isset($_POST['firstName']))
   $firstName = $_POST['firstName'];
   else $firstName = "";
if (isset($_POST['lastName']))
   $lastName  = $_POST['lastName'];
   else $lastName = "";
if (isset($_POST['eMail']))
   $eMail     = $_POST['eMail'];
   else $eMail = "";
if (isset($_POST['sex']))
   $sex       = $_POST['sex'];
   else $sex = "";
if (isset($_POST['riding']))
   $riding    = $_POST['riding'];
   else $riding = "off";
if (isset($_POST['hunting']))
   $hunting   = $_POST['hunting'];
   else $hunting = "off";
if (isset($_POST['bird']))
   $bird      = $_POST['bird'];
   else $bird = "off";
if (isset($_POST['travels']))
   $travels   = $_POST['travels'];
   else $travels = "off";
?>
You would have to retrieve the data explicitly, using a script like the one shown on the left, to be placed somewhere before the result table definition (to see the whole page, please click here): The statement
$firstName = $_POST['firstName'] creates the $firstName variable, and assigns it the value of the 'firstName' INPUT field of the data entry form.

A problem arises when such a field is empty, or a checkbox is not checked. In this case, the related data is not transmitted to the server, and the corresponding key and value are not set in the $_POST array. For instance, if the checkbox 'riding' is not checked, the item $_POST['riding'] is not defined; then the statement $riding=$_POST['riding'] causes an error.
A test has to be carried out before assigning an item to the corresponding variable. This is done through the isset function. The isset function returns true if its argument is set, i.e. is defined and has been assigned a value. Here, when the item $_POST[...] is not set, the script creates the corresponding variable, and assigns it the appropriate value; this is necessary as the variable is subsequently to be displayed by the script, and if not defined, will cause an error.

A number of superglobal arrays are available to a PHP script; they are so called because they are accessible from everywhere. The $_POST superglobal array contains the data from a FORM using the POST method.

The TheEnd.html source page is shown below. Its display looks is as shown on the right:

<HTML><HEAD>
<TITLE>THAT'S ALL FOLKS</TITLE>
</HEAD>
<BODY>
<DIV style="font-size:150%;font-weight:bold;
color:red;text-align:center;background:yellow;
padding:5em">
THE END</DIV>
</BODY>
</HTML>
THE END

This example was intended to show how data from a client data entry form can be retrieved into a PHP script, on the server side.

1.3 Database access

The following samples show how to access a database and perform the basic functions in this connection:
- creating a database
- creating a table
- inserting data into a table
- querying a table
- sending a table object to the client
- updating a table

These samples are scripts installed in the 'samples'directory. They can be called from this page by a click on their name, if you installed the Web server and PHP as suggested above. They attempt to connect to a MySQL database server installed in the localhost, using an account named "myuser", with the password "mypass". For the examples to thoroughly work, you have to install MySQL, and create an account with the mentionned account name and password.

1.3.1 Database creation

CreateMyDbase.php (database access information to be defined)
<!-- CreateMyDbase.php" -->
<HTML><HEAD><TITLE>Create mydatabase
</TITLE></HEAD><BODY>
DATABASE CREATE<br>
<b style="color:red">
<?php $ok = false; $host = "localhost:3306"; $user = "myuser"; $pass = "mypass"; $dbase= "mydatabase"; $link = mysql_connect($host, $user, $pass); if ($link) { $query = "CREATE DATABASE $dbase"; $ok = mysql_query($query); if ($ok){ print "$dbase Database created"; } else {die (mysql_error());} }//end if else { die (mysql_error()); } mysql_close($link); ?>
</b> </BODY></HTML>
The PHP page shown on the left (CreateMyDbase.php) is to be called directly. It creates a database called mydatabase. The PHP script is enclosed between the <?php and ?> marks; it is made to stand out in blue.

A number of variables containing database access information are defined first:

$hostdefines the computer that hosts the database: here, it is the local host, port 3306 -- the port used by MySQL is shown on the MySQL start up message.
$user defines the user account
$pass defines the password associated with the user
$dbase defines the database to create
mysql_connect is a so-called extension function. In this instance, it pertains to the MySQL module. This function returns a connection to the server as installed in the designated host, listening at the designated port. In the present case, the connection is returned in the $link variable. If the connection fails, the returned value is the boolean false. When successful, the connection has a non-null value, and is interpreted as true.

The mysql_query function submits the SQL statement defined by its argument. CREATE DATABASE is the SQL statement which creates a database. It returns the boolean value of true if successful, false otherwise.

The mysql_close function frees the resources held by the connection.

A function which is often used to terminate a script when something goes wrong, is die. This function prints the message defined by its argument, and terminates the execution of the script. The message here is the value of the mysql_error function, which returns the latest message error of the MySQL server.

The characters in black are HTML code which is sent to the client, unchanged.

1.3.2 Table creation

CreatePeople.php
<!-- CreatePeople.html -->
<HTML><HEAD><TITLE>Create People Table</TITLE>
</HEAD><BODY>
CREATE PEOPLE TABLE<br>
<b style="color:red">
<?php $host = "localhost:3306"; $user = "myuser"; $pass = "mypass"; $link = mysql_connect($host, $user, $pass) or die ("Unable to connect to DB server"); $dbase = "mydatabase"; mysql_select_db ($dbase) or die ("Unable to open$dbase"); print "Database opened!<br>"; $query = "CREATE TABLE people (firstName VARCHAR(24), lastName VARCHAR(24), email VARCHAR(32), sex CHAR(8), riding VARCHAR(8), hunting VARCHAR(8), bird VARCHAR(8), travel VARCHAR(8))"; mysql_query($query) or die ("Table NOT created<br>".mysql_error()); print "Table created"; mysql_close($link); ?>
</b> </BODY></HTML>
The PHP page shown on the left (CreatePeople.php) creates a table named people, in the database to which the script is currently connected.

The mysql_connect requests connection to the local host. The function invocation is followed by the statement 'or die (...)'. This syntax is of common occurrence. Let's see how it works.
The whole expression including the = operator has a value, and is to be evaluated. Due to operation precedence, the assignment is carried out first, i.e. the result of the mysql_connect function is assigned to the $link variable. Then the expression $link or die(...) is evaluated. If mysql_connect is successful, $link receives a value which is not null and is interpreted as true. The expression is then true and there is no need to proceed on further. If the function fails, the result is false; then the second term, die (...) has to be evaluate, i.e the function is called, and terminates the script. The function or die syntax is often used to terminate a script with a message, on abnormal end of a function.

The argument of the die function, under mysql_select_db is:
"Unable to open $dbase"
This is a string composed of the constant "Unable to open " followed by the value of the $dbase variable (variables within double-quotes are expanded.)

The mysql_select_db connects to the database identified by its argument, namely 'mydatabase'.

The mysql_query function submits the SQL statement defined by its argument. CREATE TABLE is an SQL statement. Here it creates a table named 'people' into the database to which the script is currently connected. The columns of the table are defined within the parentheses: firsName, lastName, email, sex, etc.
The argument of the die function is composed of 2 parts, the constant string "Table NOT created<br>" and the function mysql_error. The "." (dot) sign is the concatenation operator in PHP.

1.3.3 Data insertion

This example uses two pages. The first is a pure HTML page from which the client enters the data. The other is a PHP page which is called to retrieve the data entered through the HTML page and insert them into a MySQL table.
DataInsert.html
<!-- DataInsert.html -->
<HTML><HEAD><TITLE>DATA ENTRY</TITLE></HEAD>
<BODY>
Use this form to enter a name and e-mail address
<FORM ACTION="DataInsert.php" METHOD="POST">
<TABLE>
   <TR><TD style="color:blue;font-weight:bold;">First Name
       <TD><INPUT TYPE="text" NAME="firstName" 
                  STYLE="background:lime">
   <TR><TD style="color:blue;font-weight:bold;">Last Name
       <TD><INPUT TYPE="text" NAME="lastName" 
                  STYLE="background:lime">
   <TR><TD style="color:blue;font-weight:bold;">e-mail
       <TD><INPUT TYPE="text" NAME="eMail" 
                  STYLE="background:lime">
   <TR><TD style="vertical-align:top; 
                  color:blue;font-weight:bold;">Sex: 
       <TD><INPUT TYPE="radio" NAME="sex" VALUE="M">Male<BR>
           <INPUT TYPE="radio" NAME="sex" VALUE="F">Female
   <TR><TD colspan="2"><SPAN STYLE="color:blue;font-weight:bold;">
           Favourite occupations</SPAN> - please click one or more
   <TR><TD><TD><INPUT TYPE="checkbox" NAME="riding">Horseback riding
   <TR><TD><TD><INPUT TYPE="checkbox" NAME="hunting">Fox Hunting
   <TR><TD><TD><INPUT TYPE="checkbox" NAME="bird">Bird watching
   <TR><TD><TD><INPUT TYPE="checkbox" NAME="travels">Travels
   <TR><TD><BUTTON TYPE="submit" NAME="sub"><b STYLE="color:red">
           SUBMIT</BUTTON>
</TABLE>
</FORM></BODY></HTML>

On the left is the HTML code. The names of the INPUT elements stand out in blue. These names along with their values as entered by the user are sent to the server, when the user clicks on the SUBMIT button.

To see how the page is presented to the user, please click here.

If you installed the Apache Web server and the PHP processor as suggested in the introductory remarks to this section, clicking on the script name (on the left, above the script display) will request it. You have to install MySQL as described in Appendix 1, and run the two previous sample scripts. This supposes that you also created the user account and password to suit the values hard coded into the script that will be called next.

Below is the PHP to be called when data are submitted from the client side.

<!-- DataInsert.php -->
<HTML><HEAD><TITLE>DATA RECORDING</TITLE></HEAD>
<BODY>
<?php extract ($_POST); if (!isset($firstName))$firstName=""; if (!isset($lastName))$lastName=""; if (!isset($eMail))$eMail=""; if (!isset($sex))$sex=""; if (!isset($riding))$riding="off"; if (!isset($hunting))$hunting="off"; if (!isset($bird))$bird="off"; if (!isset($travels))$travels="off"; $host = "localhost:3306"; $user = "myuser"; $pass = "mypass"; $link = mysql_connect($host, $user, $pass) or die (mysql_error()); $dbase = "mydatabase"; mysql_select_db ($dbase) or die ("Unable to open $dbase ".mysql_error()); $query = "INSERT INTO people (firstName,lastName,email,sex, riding,hunting,bird,travel) VALUES('$firstName','$lastName','$eMail','$sex', '$riding','$hunting','$bird','$travels')"; print "<b style='color:red'>QUERY:</b> $query<br>"; mysql_query($query) or die (mysql_error()); print "<span style='color:blue'>Data recorded</span>"; mysql_close($link) or die (mysql_error()); ?>
<FORM ACTION="DataInsert.html"> <BUTTON TYPE="submit" NAME="html">NEXT</BUTTON> </FORM> <FORM ACTION="TheEnd.html"> <BUTTON TYPE="submit" NAME="end">END</BUTTON> </FORM> </BODY></HTML>
"extract" is a function from the PHP core. From the array passed as argument, it creates the variables which have as names the keys in the array, and as values the values associated with the keys. Here, the extract($_POST) function is expected to create the variables $firstName, $lastName, $eMail, ... from the keys 'firstName', 'lastName', 'eMail', ... set in the $_POST array. But as was seen above, some of the keys may not be set, then the corresponding variables are not created. The isset function is used to test if a function has been created by the extract function. If not, it is created with the appropriate value.

The informations needed to access the table are hard coded into the script: host name ($host), user name ($user), pass word ($pass), database name ($dbase). They are the same as used in the previous scripts to create the database and the table. The table name also is hard coded into the SQL statement, this is the table you created

In the above, we have seen all of the MySQL functions used here:
- mysql_connect connects to the server
- mysql_select_db connects to a database
- mysql_query submits an SQL statement
- mysql_error returns the latest MySQL error message
- mysql_close closes a connection to the server

If a function fails, it returns false and the die function is then called to write out the MySQL error message returned by mysql_error, and terminate the script. Else, the script proceeds on.

The INSERT statement of the SQL language inserts a row of data into a table. Here, it is the 'people' table, hard coded into the script. The first list within parentheses contains the names of the columns to receive data. The list following the word 'VALUE' contains the data to insert, each sent to the column named at the same rank in the first list.

A remark on the string that constitutes the INSERT statement. It is made of the multiple lines enclosed within double-quotes that is assigned to the $query variable. Within these double-quotes, the single-quotes that surround the variables such as $firstName are data characters. Therefore these variables are really within the double-quotes, and are expanded.

Two buttons are defined in two different FORM structures. The one with the label NEXT calls the DataInsert.html page again, for a new entry. The one with the END label calls the TheEnd.html page which goes nowhere further.

1.3.4 Data Query

This sample uses two pages, the first (PHPSelect.html) is a pure HTML page through which the user defines the database and the table to be queried. The other is the PHP page which receives the database and table identifications and sends back the informations on the table. PHPSelect.html
<!-- PHPSelect.html -->
<HTML><HEAD>
<TITLE>MySQL SELECT</TITLE></HEAD>
<BODY>
Enter the name of the database and table to be queried:
<FORM action="PHPSelect.php" method="GET">
  <TABLE>
    <TR><TD>Database name:
        <TD><INPUT type="text" name="dbName">
    <TR><TD>Table name:
        <TD><INPUT type="text" name="tableName">
    <TR><TD>
        <TD><INPUT type="submit" name="button" 
                                 value="SUBMIT">
  </TABLE>
</FORM>
</BODY></HTML>
Here is the HTML code.

The page has two data entry fields for the user to enter the names of the database and the table to query. These informations are sent to the server, to be processed by the PHPSelect.php script.

To merely see how the page is presented, please click here. If you have set up your Web server as suggested, clicking on the page name (on the left, above the page display) will request it under PHP.

The PHP page called to process the request is shown below.

PHPSelect.php -- not to be requested directly
<!-- PHPSelect.php -->
<HTML><HEAD><TITLE>MySQL SELECT</TITLE></HEAD>
<STYLE>
   TD {padding:0.25em;}
   TT {color:#0000AA;}
</STYLE>
<BODY>
<?php 
  $name  = $_GET['tableName'];
  $dbase = $_GET['dbName'];
?>
Table: 
<?php 
print ("<b style='color:red'>$dbase.$name</b><p>"); 
$ok   = false;
$host = "localhost:3306";
$user = "root";
$pass = "mypass";
$link = mysql_connect($host, $user, $pass)
or die (mysql_error());
  mysql_select_db ($dbase)
  or die ("Unable to open $dbase: ".mysql_error());
As method GET is used to handle the data, these are to be retrieved from the $_GET superglobal array variable.

The PHP script (in blue characters, enclosed within the <?php and ?> tags) are in multiple separate sequences. For execution, it is to be conceived of as a single block. Any 'print' and other function that writes out text, have their results put onto the result HTML page, at the locations where such functions are located in the page.

The data needed to access the table: host name ($host), user name ($user), password ($pass) are hard coded into the script.

In the argument of the print function, the dot (.) is a data character to be printed, not the concatenation operator, as it is within double-quotes.

The MySQL functions used in the script are:

mysql_connectconnects to the server
mysql_select_dbconnects to a database
mysql_querysubmits a SQL statement and returns the result.
mysql_num_fieldsreturns the number of columns contained in a query result
mysql_fetch_arrayreturns the next row from the result of a query
mysql_data_seeksets the next row to be returned by the mysql_fetch_array function
mysql_errorreturns the latest MySQL error message
mysql_closecloses the connection

Two SQL statements are used in this script:
- DESCRIBE (first query, result in $desc)
- SELECT (second query, result in $result)

  $query = "DESCRIBE $name";
  print ("QUERY: <tt>$query</tt><br>");
  $desc  = mysql_query($query);
  $col   = mysql_num_fields($desc);
?>
Table description<br>
<TABLE>
<THEAD style='color:red;background:black;'>
<TR><TD>Field<TD>Type<TD>Null
    <TD>Key<TD>Default<TD>Extra
</THEAD>
TBODY style='background:#000088;color:white;'>
<?php 
//write table description
while ($row=mysql_fetch_array($desc,MYSQL_NUM)){
    print ("<TR>");
    for ($i=0; $i < $col; $i++){
         print ("<TD>$row[$i] ");
    }//end for $col
    print ("\n");
}//end while $row
print ("</TBODY></TABLE><p>\n");

The DESCRIBE SQL statement returns a description table each row of which contains the description of a column of the queried table: the first item contains the column name, the second the column data type, the third indicates if the column can contain null values, etc. To see a sample of the result as displayed on the user's screen, please click here. The description table is in blue. To achieve this description:
-The header line (Field, Type, etc.) is hard coded in the HTML page (element THEAD in black)
-The contents of subsequent rows are printed in a while loop. The mysql_fetch_array function returns the next row from the $desc table resulting from the DESCRIBE statement, into the $row array. The MYSQL_NUM argument causes the returned row to be an array (variable $row) indexed by number. Each item in the array ($row[0], $row[1], ...) is set in a <TD> element of a <TR> row of an HTML table in the result page.
-The while loop ends when there is no more rows, as the mysql_fetch_array function then returns the false value.
$query  = "SELECT * FROM $name\n";
print ("QUERY: <tt>$query</tt>");
$result = mysql_query($query);
//write column headers in SELECT result table
print ("<TABLE style='background:black;'>\n");
print ("<THEAD style='background:#EEDD44;'>\n");
print ("<TR>");
mysql_data_seek($desc,0);
while ($row=mysql_fetch_array($desc,MYSQL_NUM)){
   print ("<TD>$row[0]</TD>");
}//end while $row
print ("\n</THEAD>\n");
mysql_free_result($desc);
  
print ("<TBODY style='background:#88FF88;'>\n");
$col    = mysql_num_fields($result);
while($row=mysql_fetch_array($result,MYSQL_NUM)){
  print ("<TR>");
  for ($i=0; $i < $col; $i++){
       print ("<TD>$row[$i] </TD>");
  }//end for $col
  print ("\n");
}//end while
print ("</TBODY></TABLE>");
mysql_free_result($result);
mysql_close($link);
?>
</BODY></HTML>
In the SQL statement SELECT * FROM $name:
- the asterisk (*) stands for 'all of the columns'
- the variable $name contains the table name entered by the user
So, it requests all of the informations from the table named by the user

The mysql_data_seek function here resets the $desc table, so that the next mysql_fetch_array will fetch its first row. The first value in each row resulting from the DESCRIBE query is the name of a column of the queried table. So, the while loop following the mysql_data_seek writes out the column names of the queried table as headers for the result table of the second query.

The second while loop writes out the contents of the queried table:

-the mysql_num_fields function returns the number of columns in the query result
-the mysql_fetch_array returns the next row from the query result, or false when no more rows are available

Expressions like $row=mysql_fetch_array($result,MYSQL_NUM) are use as a condition in the while loop. This means that it has a boolean value of true or false. How can this be explained?

An expression containing the assignment operator, has a type and a value. These are the type and value assigned to the variable on the left handside. The expression $row=mysql_fetch_array(...) is an array when the argument has still a row to return. It is the boolean false when no more row exists. Now, an array which is not null has the boolean value of true. Therefore $row=mysql_fetch_array(...) is true when a row is returned, false when no more row is available. This is how this expression can be used to control the while loop.

1.3.5 Client side query

In this sample application, the whole queried table is sent to the client side. The rows of the table can then be displayed one at a time, using Javascript. The Javascript code is to be generated by PHP. To easily understand the PHP script to create, one must be aware of the result to be obtained. We are going to see the resulting Javavascript script to obtain before seeing how to generate it.

The HTML/Javascript generated page

Please click here to see a sample HTML page as can be generated. As this is a realistic example, the page has many lines. But these lines are repetitive. When you understand one in a group, you understand them all.

In the display, the lines in green characters make up the HTML code that presents the results for the user to see. This code represents a number of text type INPUT elements set in a TABLE for presentation clarity. These INPUT elements are to receive the data to display. Their names are made to stand out in red. Remember that the text that shows in the INPUT fields, on the user's screen, is the character string assigned to the value attribute of the INPUT elements (this is HTML).

Displaying data is achieved through the use of Javascript functions. In the HTML code, the lines pertaining to Javascript are in blue characters. The first block, repeated below, is the Javascript object which contains the whole table received from the server:

tableObject = {
 kk : 0,
 kx : 7,
 A0: {firstName:"Fanny",lastName:"Adams",email:"fanny@yahoo.com",sex:"F",riding:"on",hunting:"",bird:"on",travel:""}, 
 A1: {firstName:"Joe",  lastName:"Blow",email:"joe@compuserv.com",sex:"M",riding:"on",hunting:"",bird:"",travel:""}, 
 A2: {firstName:"Richard",lastName:"Miles",email:"dickm@free.us",sex:"M",riding:"",hunting:"on",bird:"on",travel:""}, 
 A3: {firstName:"Mary",lastName:"Jane",email:"maryj@aol.com",sex:"F",riding:"on",hunting:"",bird:"",travel:""}, 
 A4: {firstName:"Jack",lastName:"Russell",email:"jackr@yahoo.com",sex:"M",riding:"",hunting:"",bird:"on",travel:""}, 
 A5: {firstName:"John",lastName:"Doe",email:"jdoe@hata.com",sex:"M",riding:"on",hunting:"",bird:"on",travel:"on"}, 
 A6: {firstName:"Richard",lastName:"Roe",email:"rroe@aol.com",sex:"M",riding:"on",hunting:"",bird:"",travel:"on"}  
}//end table object 
The object is named tableObject. Its contents are enclosed within curly braces (as is the rule for Javascript objects). These contents are:
kkis an integer variable which points to the current row to display
kxis the total number of rows in the queried table
Aiwith i ranging from 0 to kx-1, represent the rows of the queried table. Each of the Ai's is an object with the following contents, extracted from the queried table:
firstNamea string variable that contains the value of the table 'firstName' column, e.g. "Fanny"
lastNamea string variable that contains the value of the table 'lastName' column, e.g. "Adams"
emaila string variable that contains the value of the table 'email' column, e.g. "fanny@yahoo.com"
sexa string variable that contains the value of the table 'sex' column, e.g. "F"
ridinga string variable that contains the value of the table 'riding' column, e.g. "" (2 consecutive double quotes -- void)
huntinga string variable that contains the value of the table 'hunting' column, e.g. "on"
birda string variable that contains the value of the table 'bird' column, e.g. "on"
travela string variable that contains the value of the table 'travel' column, e.g. "" (2 consecutive double quotes -- void)
The current value of i is held in the variable kk. It identifies the row being displayed.

The object tableObject has the structure tableObject={kk:0, kx:7, A0:{..}, A1:{..}, ... A6:{..} }
kk, kx, A0, A1, ... A6 are the properties of the tableObject object. They are separated by commas.
The object A0 has the structure A0:{firstName:"Fanny", lastName:"Adams", ...travel:""}. The curly braces indicate that this is an object. The variables firstName, lastName, ... are the comma separated properties of the object A0. They are string variables with values "Fanny", "Adams", ... At any level, the colon (:) follows the property name and introduces the value of the property.

If you did not know what a Javascript object is, please don't worry. Just see how it is defined here, and how it is used below. Note that the name tableObject of the object defined at the first level, is followed by an = sign, whereas the names of the objects A0, A1, ... contained in tableObject are followed by a colon sign.

The displaying of the data is controlled by a Javascript script assigned to the BUTTON labelled "DISPLAY" (named "push"). The button description with its associated onclick script is repeated below (click here to see the complete page again):

  <BUTTON type="button" value="push" name="push"
   onclick='if (tableObject.kk == tableObject.kx)tableObject.kk=0;
      record.value=tableObject.kk+1;
      firstName.value=eval("tableObject.A"+tableObject.kk+".firstName");
      lastName.value=eval("tableObject.A"+tableObject.kk+".lastName");
      email.value=eval("tableObject.A"+tableObject.kk+".email");
      sex.value=eval("tableObject.A"+tableObject.kk+".sex");
      riding.value=eval("tableObject.A"+tableObject.kk+".riding");
      hunting.value=eval("tableObject.A"+tableObject.kk+".hunting");
      bird.value=eval("tableObject.A"+tableObject.kk+".bird");
      travel.value=eval("tableObject.A"+tableObject.kk+".travel");             
      tableObject.kk++;'>DISPLAY</BUTTON>
This script displays a new table row on the user's screen, wrapping around to the first row when the last is passed.
The property kk of the object tableObject is denoted tableObject.kk. This is Javascript object notation. On the left handside, the words record, firstName, lastName, etc... are the names of the INPUT elements of the HTML page. They identify the Javascript objects that represent these elements. Whereas tableObject is defined above in the script, element objects such as record, firstName, etc. are implicitly defined by Javascript for certain types of elements. The names of these objects are the values of the element name attributes. The attributes of an element are the properties of the corresponding object. For example, the value attribute of the INPUT element 'record' is represented by the value property of the object 'record' and is denoted record.value. The text attribute of the INPUT element 'email' is represented by the text property of the 'email' object, and is denoted email.text.

The onclick attribute is assigned a script which is executed when the button is clicked. Please, click here to see how the page is displayed, and how the onclick script works (please click on the 'DISPLAY' button to see).

The index of the next row to display is readily held in the kk variable of the tableObject object. The script assings the values of this row to the INPUT elements value attributes, and increments the kk index to make it ready for the next click. It does the following:

-resets the current row pointer kk to 0, if it has passed its maximum which is kx-1 (kx is the number of rows -- in the example, there are 7 rows, the index kk ranges from 0 to 6). This way, kk wraps around after its maximum is reached
-sets the 'record' INPUT element value to the current row number plus 1 (the first row in the table being numbered '0'), to show the rank (numbered from 1) of the new row to be displayed
-sets the displayed INPUT element values to the values contained in the new row
-increments the kk variable of the tableObject by 1, to point to the next row

As an example of how column values are assigned, let's look at the assignment of the firstName INPUT element:
firstName.value = eval("tableObject.A"+tableObject.kk+".firstName");

The notation firstName.value on the left handside, represents the 'value' attribute of the firstName INPUT element. It is the text displayed in the firstName field.

The argument of the eval function, on the right handside, is the expression composed with 3 terms as follows:

-the constant string "tableObject.A"
-the variable tableObject.kk, the index of the row to be displayed
-the constant string ".firstName"
The + sign is the concatenation operator in Javascript. If e.g. tableObject is 3, the expression would be the string "tableObject.A3.firstName". The eval function is used to evaluate this expression. If you just coded

firstName.value="tableObject.A"+tableObject.kk+".firstName";

the value displayed on the user's screen would be the text "tableObject.A3.firstName". Using the eval function, you assign the value of this expression to the left handside. You have the same result as though the resulting string is directly coded in the page:

firstName.value=tableObject.A3.firstName; (without quotes)

This is the magic of the eval function. Now, tableObject.A3.firstName, is the firstName property of the A3 object, which is a property of the tableOject object (this again is Javascript object notation). Its value, as seen in the tableObject description above, is "Mary".

Generating the HTML/Javascript page on the server side

Here are now the pages used to produce the above HTML page with Javascript code.
PHPJavascript.html
<!-- PHPJavascript.html -->
<HTML><HEAD><TITLE>JAVASCRIPT</TITLE></HEAD>
<BODY>
Enter the name of the table to be displayed:
<FORM action="PHPJavascript.php" method="POST">
  <TABLE>
    <TR><TD>Host name:
        <TD><INPUT type="text" name="host"
                   value="localhost:3306">
    <TR><TD>User name:
        <TD><INPUT type="text" name="user">
    <TR><TD>Pass word:
        <TD><INPUT type="password" name="pass">
    <TR><TD>Database name:
        <TD><INPUT type="text" name="dbase">
    <TR><TD>Table name:
        <TD><INPUT type="text" name="table">
    <TR><TD>
        <TD><INPUT type="submit" 
                   name="button" value="SUBMIT">
  </TABLE>
</FORM>
</BODY></HTML>
This is the HTML code of the page through which the user enters the name of the table to query, along with the informations needed to access it. These data are contained in the following INPUT fields:
Field nameField contents
hosthost name
useruser name
passpass word
dbasedatabase name
tabletable name
These fields are transmitted to the server, where they are to be retrieved through the POST method.
 
The PHP page called in to process the request is shown below:
<?php extract("$_POST"); $ok = false; $link = mysql_connect($host, $user, $pass); if ($link) { mysql_select_db ($dbase) or die ("Unable to open $dbase: ".mysql_error()); //Get table column names $query = "DESCRIBE $table"; $desc = mysql_query($query) or die (mysql_error()); while ($row=mysql_fetch_array($desc, MYSQL_NUM)){ $name[] = $row[0]; }//end while $row mysql_free_result($desc); //Get table contents $query = "SELECT * FROM $table"; $result = mysql_query($query) or die (mysql_error()); $num = mysql_num_rows($result); $col = mysql_num_fields($result); }//end if $link else { die ("Unable to connect to DB server"); }//end else $link
The page starts with a PHP sequence that retrieves:
-the column names of the queried table, into the $name array
-the contents of the queried table, into the $result variable

The extract function creates the variables that have the names of the INPUT fields from the calling page above, and hold their values.

Retrieving data from the table

To get the table column names, the description of the table is first obtained into the $desc variable, as already seen in the above. The mysql_fetch_array is then used in a while loop to retrieve the rows of the $desc result. The first item of each row, row[0], is the name of a column in the queried table. The notation:
$name[] = $row[0]
with the empty square brackets, creates entries in the $name array with an index starting at 0 and increasing by 1 at each iteration.

The SQL statement "SELECT * FROM $table" queries all of the columns of the table. Along with the table contents, returned into the variable $return the number of rows and columns of the table are retrieved into the $num and $col variables, using the mysql_num_rows and mysql_num_fields functions respectively.

?><!-- PHPJavascript.php -->
<HTML><HEAD><TITLE>Javascript Object</TITLE>
<SCRIPT>
tableObject = {
  kk : 0,
  kx : <?php print ("$num,\n");
    $i = 0;
    while ($row=mysql_fetch_array($result,MYSQL_NUM))
    {
     if ($i > 0) print (", \nA$i: {");
     else print ("A$i: {");
     print ($name[0]:\"$row[0]\"");
     for ($j=1; $j < $col; $j++){
       print (", $name[$j]:\"$row[$j]\"");
     }//end for $col
     print ("}");
     $i++;
   }//end while
  ?>
}//end table object 
</SCRIPT></HEAD>

Creating the Javascript object

The tableObject Javascript object is created into a SCRIPT element, in the HTML page HEAD element. The characters in black outside the <?php..?> bracket are written onto the result page, as is.

The statement print ("$num,\n"); writes the number of rows ($num) followed by a comma(,) and a new-line sequence (\n) to the right of the property name kx:, in the result HTML page.

The script whithin the while loop is executed for each of the rows from the $result table, as retrieved by mysql_fetch_array.

For each row, a new object is created. First, its name Ai is written out, i being the number of the row (held in $i)
For row 0 ($i==0), just the number i is appended to the letter A, then come the required colon and opening curly brace. For the subsequent rows ($i>0), before that, a comma is added to the end of the preceding row definition, and then a new-line sequence (\n) to start the new row definition on a new line.

Finally the contents of the row object is created. This is composed of the column names ($name), each followed by a colon and the column value, as retrieved into the $row array variable. The first column ($row[0]) receives a special treatment as just its description by name, colon, and value is written out. For the subsequent columns, before their description, a comma is to be added to the end of the preceding column description.

After the column descriptions, the closing curly brace } is added. This completes the creation of one row object.

<BODY>
<?php print("<TABLE><TR><TD>Database: <TD><b style='color:red'>$dbase</b>\n"); print ("<TR><TD style='vertical-align:baseline'> Table: <TD><b style='color:red'>$table</b>\n"); print ("</TABLE>"); ?>
<FORM action="PHPJavascript.html" name="tbl"> <TABLE><TR><TD>record# <TD><INPUT type="text" name="record"> <?php for ($i=0; $i < $col; $i++){ print ("<TR><TD>$name[$i] <TD><INPUT type='text' name='$name[$i]'>\n"); }//end for $col ?> </TABLE>

Database and table names

This script creates the HTML elements that display the names of the database and the queried table from that database.

Table column names

This script creates the row elements (<TR>) of the HTML table to contain the values retrieved from the database. In each row, the label displayed on the left column (first <TD> element) and the name of the INPUT field displayed on the right column (second <TD> element) are the same: they are the column name retrieved from the queried table. Note that $name[$i] is a variable whereas the rest of the text to be printed, enclosed within the double quotes, is constant, to be printed as is. Note also that single quotes that appear within double quotes are data; therefore, the single quotes that enclose the second $name are data, and $name is considered enclosed within the outer double-quotes.
  <BUTTON type="button" value="push" name="push"
   onclick='if (tableObject.kk == tableObject.kx)
                tableObject.kk=0;
      record.value=tableObject.kk+1;
      <?php
      for ($j=0; $j < $col; $j++){
       print($name[$j].".value=eval(\"tableObject.A\"
       +tableObject.kk+\".$name[$j]\");\n");
      }?>             
      tableObject.kk++;'>
   DISPLAY
  </BUTTON>
  <TABLE><TR><TD>New table:
             <TD><BUTTON type="submit" name="next">
                        NEW</BUTTON>
  </TABLE>
</FORM>
<FORM action="TheEnd.html">
  <TABLE><TR><TD>Terminate:
             <TD><BUTTON type="submit" name="end">
              EXIT</BUTTON>
  </TABLE>
</FORM>
</BODY></HTML>      

Creating the 'onclick' script

The first lines are hard coded in the HTML part of the page (black characters). They first reset the counter kk to 0 each time it gets over its maximum, then assign it to the record field, with 1 added to present row numbers starting with 1, to the user.

The PHP script (in blue characters) creates the statements that assign the column values to the INPUT display fields, as described in the above. Note that \" is used to represent the double quote (") in strings delimited by double quotes.

For example, if firstName is the column name (held as an item in the $name array), the print function would write this out to the result page:
firstName.value=eval("tableObject.A"+tableObject.kk+"firstName");\n
This line is to be processed by Javascript as part of processing the 'onclick' script.

The last line of the 'onclick' script (in black characters) is not part of the PHP script and is written out as is. It increments the kk counter by 1, so that the next click on the button will retrieve the next row of the queried table.

 
As an application usually involves both the client and the server side, a client-side language such as Javascript is as important to know as PHP. You can see that the two languages have similarities and differences that are important to remember.

1.3.6 Table updating

This sample application can be used to update or delete selected rows in a table.
PHPModify.html
<!-- PHPModify.html -->
<HTML><HEAD><TITLE>JAVASCRIPT</TITLE></HEAD>
<BODY>
Enter the name of the table to modify:
<FORM action="PHPModify.php" method="POST">
  <TABLE>
    <TR><TD>Host name:
        <TD><INPUT type="text" name="host
                   value="localhost:3306">
    <TR><TD>User name:
        <TD><INPUT type="text" name="user">
    <TR><TD>Pass word:
        <TD><INPUT type="password" name="pass">
    <TR><TD>Database name:
        <TD><INPUT type="text" name="dbase">
    <TR><TD>Table name:
        <TD><INPUT type="text" name="table">
    <TR><TD>
        <TD><INPUT type="submit" 
                   name="button" value="SUBMIT">
  </TABLE>
</FORM>
</BODY></HTML>
 
Here is the code of the HTML page (PHPModify.html) you would use to enter the name a table from which to update or delete a selected row, along with the informations needed to access it. This repeats the PHPJavascript.html page from the foregoing example, with only slight changes, notably in the action attribute of the FORM element to call another PHP page, PHPModify.php.

The page called from the above, PHPModify.php, derives from PHPJavascript.php of the foregoing example. Sequences are added to define new control buttons and data.

Please click here to see the new code, where the old Javascript code is in green.

The new sequences are as described in the following.

  q     = "'";
  tabl = <?php print "\"$table\"\n" ?>
  save = new Array <?php print ("($col+1)\n") ?>
 
This sequence adds some Javascript constants to the SCRIPT element in the HEAD element.
In this sequence:
qcontains a single quote; it is used as a convenient way to insert a single quote into a character string delimited by single quotes (this is an alternative to the escape sequence "\'". As q is a Javascript variable, the $ sign is not needed.
tablholds the name of the queried table, in the Javascript environment; this variable is to remain in the result page sent to the client. In that page, PHP variables are no longer available. Note the use of the \" escape sequence for the double-quote (") sign, in PHP (Javascript is similar to PHP in this respect).
saveis a Javascript array, to contain the values of the current row, before manual modifications if any. It is created with a size equal to the number of columns plus 1, and is empty at this time.

<TABLE><TR><TD>
<FORM name="tbl" style="float:left;margin-right:2em;">
 <TABLE><TR><TD>record#<TD><INPUT type="text" name="record">
 <?php
  for ($i=0; $i < $col; $i++){
    print ("<TR><TD>$name[$i]
                <TD><INPUT type='text' name='$name[$i]'>\n");   
  }//end for $col
?>
</TABLE>
</FORM>
Buttons usage:
<table>
<tr><td>-<td>DISPLAY<td>displays the next row
<tr><td>-<td>CLEAR<td>clears the table
<tr><td>-<td>RESTORE<td>restores to the values as received from
 the database
<tr><td>-<td>UPDATE<td>change the content of one or more fields,
then click on the button
<tr><td>-<td>DELETE<td>deletes the current row - NO getting back
</table>
</TABLE>
The sequence in green is from the PHPJavascript.php page. It displays the fields containing the values from the queried table.
The style attribute is added to the <FORM> element, with the value float:left which causes the element to float to the left, and let the text that follows flow to its right. This is the text (described in blue characters here) which explains how to use the buttons.

Please, click here to see an instance of how the page is displayed. You can use the Display, CLEAR and RESTORE buttons which act locally, but not the buttons that connect to the database manipulating page.

The wrapping <TABLE> element (in red) is a trick to limit the effect of the float:left property of the inner TABLE, and prevent the rest of the page from coming up.

<?php
print("save[0] = tbl.record.value;\n");
for ($j=0; $j < $col; $j++){
 print("tbl[$j+1].value=eval(\"tableObject.A\"
 +tableObject.kk+\".$name[$j]\");\n");
print ("save[$j+1] = tbl[$j+1].value;\n");
}
?>             
tableObject.kk++
final.message.value=""'>
This sequence generates the value of the onclick attribute of the DISPLAY button. The PHP part prints out the Javascript code which assigns the values of the current row from the queried table to the <INPUT> elements of the displayed table. This already existed in the PHPJavacsript.html page where the INPUT elements were identified by their names. Here another identification method is used. The INPUT elements are contained in the <FORM> element the name of which is tbl (please check the <FORM> element name=tbl attribute value). With Javascript, the FORM element can be treated as an array object whose entries are the INPUT elements it contains. These are identified by an index, starting at 0: tbl[0] is the first INPUT element (named 'record'), tbl[1] is the second (named 'firstName'), etc. The new statements added to the onclick script (in red on the left) do the following:
-save the values from the queried table into the save array, as the user may manually change the values of the INPUT elements (in the sample page, you can try and modifiy these values, then restore them by clicking on the RESTORE button).
-erases the message set at the bottom of the screen so that you have it clean each time you click on the DISPLAY button to display a new row (the message is in the INPUT field named 'message', in the FORM element named 'final').

A last remark: the line save[0] = tbl.record.value; need not be printed from within the <?php ... ?> marks, but can be hard coded into the page. Did you notice that? PHP is required only for lines that contain variable data.

<BUTTON type="button" name="clear"
 onclick='for (i=0; i < <?php print "$col+1"; ?>; i++){
            tbl[i].value="";
          }'
 >
 CLEAR
</BUTTON>
This is the definition of the CLEAR button. PHP is called upon to generate the number of columns in the queried table, plus 1 (for the record number displayed in addition to the table column values) into the Javascript code. This code erases the values of the INPUT elements, i.e. the values displayed on the screen. The INPUT elements are identified by their ranks in their containing FORM element as explained above.
<BUTTON type="button" name="restore"
 onclick='for (i=0; i < <?php print "$col+1"; ?>; i++){
            tbl[i].value=save[i];
          }'
>
 RESTORE
</BUTTON>
 
This is the definition of the RESTORE button which restores the INPUT elements to the values saved in the save array.
<FORM action="PHPSql.php" method="POST" name="update" 
      onsubmit="return ok">
  <INPUT type="hidden" name="host" 
         value="<?php print $host ?>">
  <INPUT type="hidden" name="user" 
         value="<?php print $user ?>">
  <INPUT type="hidden" name="pass" 
         value="<?php print $pass ?>">
  <INPUT type="hidden" name="dbase" 
         value="<?php print $dbase ?>">
  <INPUT type="hidden" name="query">
  <BUTTON type='submit' name='update'
   onclick='_upd = <?php print ("\"UPDATE $table \"\n"); ?>
   s = 0
   _set = "SET "
   _where= " WHERE "
   for (j=0; j < <?php print $col ?>; j++){
     if (j > 0) _where += " AND "
     _where += nam[j]+"="+q+save[j+1]+q
     if (tbl[j+1].value != save[j+1]) {
        if (s > 0) $set += ", "
        _set += nam[j]+"="+q+tbl[j+1].value+q;
        s++
     }//end if !=
   }//end for col
   if (s==0){
        final.message.value="NO value is changed!"
        query.value = ""
        ok = false
   }
   else {
        _query = _upd+_set+_where;
        final.message.value=_query;
        query.value = $query
        ok = true
   }'
  >
   UPDATE
  </BUTTON>
The excerpt on the left shows the UPDATE button definition, enclosed in a <FORM> element named update. Apart from a few data related to the specific table being queried, the sequence is purely HTML and Javascript.

The action attribute points to the PHPSql.php page which does the updating. The value of the onsubmit attribute is an event handling script. When the user clicks on a submit button in the FORM, the onsubmit script is scheduled. If it returns true, the request as defined by the action attribute (for the PHPSql.php page, here) is submitted by the browser. If false, the request is not submitted. Here, onsubmit returns the variable ok, the value of which determines therefore whether the request is submitted or not.

The <FORM> element contains a number of hidden INPUT elements which do not show on the user screen, but whose contents are sent to the server along with the request for the PHPSql.php page. These elements contain the informations needed to access the table. The query INPUT element (name="query") is to hold the SQL statement to be submitted.

The onclick script defined for the submit button creates the SQL statement in the form:
UPDATE table_name SET col_name='value', ... WHERE col_name='value' AND ....
(in SQL language, a value when a string, must be enclosed within single quotes, not doubles -- here a single quote is contained in the variable q)

The first line in the onclick script creates the "UPDATE table_name" part and puts it in the _upd variable. The name contained in the $table variable is generated onto the result Javascript sequence. Note that \" represents the double quote sign in an expression enclosed within double quotes.

The for loop walks through all of the columns from the database, and:

-for all of the variables, appends the argument col_name='value' to the "WHERE" part of the statement, separating it from the preceding argument by the "AND operator, with the value taken from the save array within single quotes (contained in the q variable); these values reflect the contents from the database; this way the precise row in the database table is selected for updating
-for the values that have been changed (by the user), appends the argument col_name='value' to the "SET" part of the statement, separating it from the preceding argument by a comma, with the values taken from the tbl array which reflects the data displayed on the screen.
The number of the changed values is counted into the s variable. At the end of the loop, if this count is 0, no request is sent, as controlled by the value ok=false to be returned by the onsubmit script of the FORM element. If one or more data are changed, the SQL statement is set up by combining its 3 parts together, the ok variable is set to true to cause the request to be transmitted.

The PHPSql.php page which is requested for the handling of the SQL statement is as follows:

<HTML><HEAD><TITLE>SQL SUBMIT</TITLE>
  <META http-equiv="Content-Type" content="text/php">
</HEAD>
<BODY>
<?php
extract($_POST);
print ("$query <br><b>RECEIVED!</b><br>");
if ($user=="root")die ("User 'root' not allowed!");

$link = mysql_connect ($host,$user,$pass)
or die (mysql_error());
mysql_select_db ($dbase)
or die (mysql_error());

mysql_query($query)
or die ("<b style='color:red'>mysql_error()</b>");
print ("<b style='color:green'>Query OK!</b>");
mysql_close($link);
?>
<p>
<FORM action="PHPModify.html" name="next" 
                              style="float:left;">
  <TABLE><TR><TD>New table:
             <TD><BUTTON type="submit" name="next">
                 NEW</BUTTON>
  </TABLE>
</FORM>
<FORM action="TheEnd.html" name="final">
  <TABLE><TR><TD>Terminate:
             <TD><BUTTON type="submit" name="end">
                 EXIT</BUTTON>
  </TABLE>
</FORM>
</BODY></HTML>
This page first retrieves the data sent by the client, from the $_POST superglobal variable. The SQL statement to be submitted to the database server is in the 'query' element of the $_POST variable.

Access to the database server requires a correct user name and a correct password. A as measure of further protection, the 'root' user is not allowed, because with MySQL this user can do much harm, as it has all the rights on all of the databases.

For still better security, it is advisable to test also the statement code. If this page is intended for UPDATE and DELETE statements only, other types of statement are to be rejected, as is done for the 'root' user. Most important of all, a test must be done to reject multiple statements in one request (multiple statements are separated by semi-colons).

After these preliminaries, the script:

-connects to the database server using the mysql_connect function
-connects to the database using the mysql_select_db function
-submits the SQL statement using the mysql_query function
-closes the connection to the server using the mysql_close function

If the statement is not successfully completed, the script is terminated using the die function, with the error message from MySQL. Otherwise, the message Query OK! is written out.

<BUTTON type="submit" name="delete"
   onclick='_del = <?php 
          echo ("\"DELETE FROM $table WHERE \"\n");?>
   for (j=0; j < <?php print $col ?>; j++){
     if (j > 0) _del += " AND "
     _del += nam[j] + "=" + q+save[j+1]+q
   }
   final.message.value=_del;
   query.value=_del
   ok = true'
  >
   DELETE
  </BUTTON>
 
This is the definition of the DELETE button. Its 'onclick' script creates a SQL statement in the form:
DELETE FROM table_name WHERE col_name='value'....
Its first line generates the starting part
DELETE FROM table_name WHERE
using the table name contained in the variable $table.
Note that \" represents the double quote in a double quote delimited expression, and \n is the linefeed sequence.

The for loop appends to this the col_name='value' elements separated by the AND operator. Values are taken from the save array which holds the values as sent from the database. The q variable holds a single quote.

The SQL statement so construct is assigned to the 'query' hidden INPUT element which is sent to the PHPSql.php as part of the request data.

1.4 Generating an XML page

PHPXml.php
<?php
print ("<?xml version='1.0' ?>
<!-- Comment : this is a document generated by PHP -->
<?xml-stylesheet type='text/css' href='styles/docxml.css' ?>
<doc>
  <text>Hello World!</text>
</doc>");
?>
 
This is a PHP page which generates an XML page.

The PHP print function is in black character. The XML page to generate is in blue.

There is a style sheet with the relative URI styles/docxml.css so that the page is displayed with the presentation defined by this style sheet.

This example shows that:
1.PHP can generate XML pages
2.a PHP page can be entirely made of a PHP script

2. CONCEPTS

2.1 How a PHP page is processed

2.1.1 PHP sequences in an HTML page

A PHP page is a page of text interspersed with PHP codes. A PHP code is enclosed between special tags.

Normally these tags are:

Opening tag
<?php
Closing tag
?>

Optionally, the opening tag can be shortened to

Opening tag
<?
(closing tag: ?>)

or the tags can be set in the ASP style:

Opening tag
<%
Closing tag
%>

These options are to be authorized by special directives in the PHP configuration file.

Nowadays, the text document containing the PHP codes is generally an HTML page, because HTML is the most widely accepted document type.

In an HTML page, PHP codes can also be enclosed within the <SCRIPT> tags like this:

<SCRIPT language="php">

    ... PHP code ...

</SCRIPT>

In a text document including an HTML page, the PHP code need not lie between the <HTML> and </HTML> tags. There can be PHP codes before and after the HTML page.

2.1.2 Generating the result page

CLIENT SIDESERVER HOST
 
USERBROWSERrequest >>>
<<< processed page
 
Disk storage
PHP processor PHP pages
 
 
 
 
 
 
A user requests a PHP page by sending a request message naming this page, through a browser (most frequently, a Microsoft Internet Explorer or a Netscape Navigator). The detailed procedure for this is described below.

The requested PHP page is processed by the PHP processor, in the server host, resulting in a processed page which is sent back to the user's browser, for displaying. The user is the client of the request.

PHP PROCESSING
SERVER SIDE
CLIENT request: somefile.php >>>> somefile.php  
 
<?phpPHP code?>
 
<?php
PHP code
?>
 
PHP processing V
V
V
V
CLIENT <<<<<<<< processed page unchanged
generated text
unchanged
generated text
unchanged
 
 
From the PHP page, text sequences not contained within the PHP tags (<?php ... ?>) are written out unchanged, to compose the resulting processed page.

Text sequences enclosed within the PHP tags are part of the PHP script which is executed as it is found in the PHP page. The script can use data stored in files or databases and accessed from the server host. Results to be sent to the client must be written out to the processed page using functions such as print or echo. These results are placed in the resulting page, at the locations where these functions occur, and are thus mixed with the text sequences from outside the <?php...?> tags (which are transferred to the processed page "as is").

No other data are written to the resulting processed page. The PHP script can contain secret data; as long as you don't write them out using one of the appropriate functions, they will not be transmitted to the client (however, some ill intended outsider may try and read the page code itself by some other mean than a regular request, to find out your secrets, but this is another problem).

2.1.3 Generating an HTML page with Javascript

There is nothing special to Javascript when coding PHP pages. Javascript text, as any text, is handled according to the simple rules presented in the above:
-text outside the <?php ... ?> tags are transferred as is to the result page
-text inside these tags constitute the PHP script that is run as encountered, any print output from the script is placed in the result page, at the position of the printing function
The present paragraph is here just to restate this.

Also, keep in mind that Javascript is a script that runs on the client side. Therefore the variables defined in the PHP script are not available for reference. To use these variables, you have to generate (by printing out) the statements that assigns their values to Javascript variables. For example, if you wish to use the value of a $var PHP variable, you would create a Javascript variable, say xxx, then write out the statement that, in the Javascript program would assign it the value of $var:
print ("xxx == '$var'");

In the resulting page, you would have: xxx = 'var_value'
where var_value is the value of $var at the time when the print function is executed.

This is illustrated in 1.3.5 and 1.3.6 above. A simple illustration is to be found in 2.8 below.

Finally generating a good HTML page with Javascript scripts is a matter of good HTML and Javascript designing. PHP can be viewed as simply the means to generate the designed page.

2.1.4 Generating an XML page

To generate an XML page write out the XML code using a print or echo function. However, PHP does not mix with XML as easily as it does with HTML.

2.1.5 Submitting a request

The Internet Explorer or Netscape Navigator browser has an address input field which generally is the first field in their window. This is the field where you should see the address of the present page, which ends with :
 .../PHP/body/PHPIntro.html"
or maybe something like:
 .../PHP/body/PHPIntro.html#2.1.5"
depending on what you did to get here (you have the above line if you came here by clicking on the "2.1.5 Submitting a request" line, in the table of contents).

To request a PHP page, you enter its Internet address in this field, then click the sending button. If you do not know which it is, just press the 'ENTER' key on your key board, it generally works.

For example, you can enter http://localhost/hpp/PHPInfo.php.

Details on the format of a request can be found in Appendix - 1.3.2 Requesting a file.

2.2 Data and variables

2.2.1 Data types

In computations you commonly use 3 types of data:
-numeric data
-string data
-boolean data

The numeric data seen in the samples in the present chapter are integers, represented by string of digits. Other types of numeric data will be seen in the next chapter.

String data are strings of characters enclosed within single or double quotes

The 2 boolean values are noted true and false, without quotes.

Numeric data are used in arithmetic operations such as addition, subtraction, multiplication, division, etc. String data are used in string operations such as concatenation, search, splitting, etc... Boolean data are used in logical operations such as AND, OR, etc. or may be tested for their value true or false.

But in PHP a datum is not precluded from being used in operations of another type. Depending on the operation they are involved in, the data have a value of the type required by the operation: they have a numeric value in an addition, a string value in a concatenation, a boolean value in a logical operation or a test for true or false.

Thus, numeric data can be concatenated. In this case, each of them is used for the digits they are composed of.

String data can be used in arithmetic operations. If they start with a number (e.g. "123ABCD"), this number is used as the numeric data (123 in the example). If not they have the numeric value of 0.

Numeric or string data can be used in a boolean operation. Boolean values are assigned as follows:

Numeric
non-zero(strictly positive or negative): true
zerofalse
String
non-emptytrue
emptyfalse
nullfalse
Bw: using an undefined variable, e.g. in a test, causes an error. You must test its being defined or not, using the isset function.

Boolean data can be used in numeric or string operations:

In numeric operations
truehas the value 1
falsehas the value 0
In string operations
truehas the value "1"
falseis an empty string

This will be illustrated in below.

2.2.2 Variable names and types

Variable names

A variable name is preceded by the $ sign. The first character in a name is a letter or an underscore. This is followed by an unlimited number of characters which can be alphabetic, upper or lower case, numeric, underscore, or any character with ASCII code from 127 to 255, inclusively (the latter are also referred to as "letters" in PHP documentation). See 3.3 below for a summary.

As there is no real distinction between the different types of data, a given variable can be assigned a number, a string or a boolean value, as needed.

Variable types

A variable can be a scalar containing one value, or an array containing multiple values.

Array variables

The values in an array are identified by a key.

In the arrays shown in the foregoing examples the keys are character strings. A key can also be a number. A character string key is called an associative index. A numeric key is called an number index .

A key and value pair is called an item or an element. The word item is to be preferred, because so many other things are called elements.

An item is designated by appending its key designation enclosed within square square brackets, to the name of the array. Thus:
$_POST['firstName'] or $_POST["firstName"]
where $_POST is the array name, firstName one of the keys in the array.

By putting an item designation on the right side of an = sign, you assign a value to it. This also creates the array if it did not exist. This is one of the ways to create an array. Examples -- consider the sequence:

$a[3] = 10;
$a["5"] = "string value";
$a["key"] = 1126;
$a[] = "some value";
The value "5" of the index is equivalent to 5, without quotes. If the $a array is assigned only these values, the array elements at indices 0 to 2, and 4 are null.

In the third line, the index is a character string, or associative index.

The square bracket can also be empty, as in the fourth line. In this case the index is numeric, and has as a value the next available, i.e. that of the highest in use, incremented by 1. Here, it is 6.

The values assigned to the different items of an array can be a mix of numeric, string data or boolean data. Actually as will be seen, the value of an item can be a data of any type. The key can only be a string or a number.

2.2.3 Superglobal arrays

When a PHP program is scheduled, informations defined in its environment by the PHP processor are made available to it through a number of array variables called superglobal arrays.

Superglobal arrays used in the present chapter contain the data received in a message processed by the GET or the POST method:

$_GETcontains data received by the GET method
$_POSTcontains data received by the POST method

Data in a message have a name and a value, in the form name=value. The names make up the associative indices of the array items. The values are assigned as values to the items.

Usually the messages come from a FORM element of an HTML page. The method, GET or POST to receive the data is specified by the METHOD attribute of the FORM element. The data mostly come from the INPUT or BUTTON elements of the FORM. Their names are the names of these elements, as defined by the latter's name attributes. Their values are the values of these elements as defined by their value attributes. The data coming from the INPUT element <INPUT name="firstName" value="Fanny"> is stored in the $_GET or $_POST array at the index 'firstName' associated with the value 'Fanny'.

2.3 Conditions

A condition is a boolean datum which has the value true of false.

Conditions are used in control statements, such as if ... else, for, while, etc...

Two common ways of expressing a condition are:

-as a comparison
-as a more general datum used for its boolean value

Conditions expressed as a comparison are common sense. Example: $a < 10. This needs no explanation, except perhaps that < stands for 'less than'. Comparisons are boolean data that have a value true or false. You can assign them to a variable:

$x = $a < 10

More generally, any boolean data can be used as a condition.

Finally, as in PHP data of any type have a boolean value, any datum can be used as a condition.

2.4 Operations

The operations used in the chapter were:
-the arithmetic addition (+)
-the string concatenation (.)
-the logical operation OR
-the increment operation(++)
-the comparison operation (<)
Operations are indicated by an operation sign or operator.

Of course, all of the common arithmetic operations are available:

+addition
-subtraction
*multiplication
/division

So are the common AND and OR logical operations.

Concatenation is the only string operation. The other operations on strings are performed through a function, as will be seen in the next chapter.

The increment operator ++ operates on a single variable which it increments by 1. Example: $x++ adds 1 to $x.

More operations are examined in the next chapter.

2.5 Expressions

2.5.1 Expressions explained

An expression is any mix of data, constants or variables, linked together by operators. An expression can be made of a single constant or variable:
10a numeric constant
"this is a string"a string constant
$a < 10a boolean datum
$varcan be of any data type

Some more complex expressions are:

($a+10)*$xa numeric expression
$b.10a string expression
"Database $dbname opened!"a string expression within double quotes
'Database $dbname opened!'a string expression within single quotes
$row = mysql_fetch_array($res) an expression the value and type of which are that of the result returned by the mysql_fetch_array function
mysql_connect($dbname) OR die("Unable to connect to $dbname") a logical expression

An expression can be evaluated, carrying out the operations indicated by the operators. The result is the value of the expression.

In the above, the first example is a numeric expression: 10 is added to $a, then the result is multipled by $x, giving the final result.

The second is a string expression: the string value of $b is concatenated with the characters "10".

The third is a string expression within double quotes, which mixes string constants and a variable. As the variable is within double quotes, it is expanded before the expression is evaluated. If $dbname is "mydatabase", then the value of the expression is
Database mydatabase opened!

The fourth is a string expression within single quotes. The variable is not expanded. The value of the expression is
Database $dbname opened!, whatever the value of $dbname is.

The fifth involves an assignment operation. It assigns a value to the variable $row. But it also has a value which is the value assigned to $row

The last is a logical expression which involves two functions linked by the OR operator.

2.5.2 Precedence

When evaluating an expression, the operations are executed in the order defined by their precedences. Operations of the same precedence are executed from left to right.

The operators exemplified in the above are given in the following table, by decreasing precedence order. Operators of the same precedence are in the same line, separated by a space

Operators
++increment
* /multiplication, division
+ - .addition, subtraction, concatenation
=assignment
ORor
The addition, subtraction and concatenation operators have the same precedence. Example - in the following:
$a=1;
$b=2;
$c=5;
$d=$a+$b.$c;

when evaluating the right hand side of the last line, as + and . have the same precedence, the operations are carried out from left to right: 2 is added to 1, giving 3, and the result is concatenated to 5, finally giving 35.

The logical expression mysql_connect($dbname) OR die("Unable to connect to $dbname") seen above is usually part of an assignment expression like this:
$link = mysql_connect($dbname) OR die("Unable to connect to $dbname")

Precedence is important to know, to determine how the whole expression is evaluated. To see the precedence table, please, click here. The = operator is seen to have a higher precedence than OR. Therefore, the expression is evaluated in the following order:

-$link = mysql_connect($dbname) is evaluated first, i.e. the result returned by mysql_connect is assigned to $link
-the expression remaining to evaluate is link$ OR die ("Unable to connect to $dbname")
-if mysql_connect did return the connection to the database server, the result has a boolean value of true, so the remaining expression is ascertained to be true, without any need to go further; the evaluation stops here
-if mysql_connect fails to set up the connection, it returns false, in the expression to evaluate, the first term $link is false. The second term die("Unable to connect $dbname") has to be evaluated, i.e. the die function is called. It usually returns true, but as it also terminates the script, what it returns is generally unimportant.

There is another operator for "or". This is || which has a higher precedence than = (see precedence table). Let's look at how the processor evaluates an expression like:
$link = mysql_connect($dbname) || print("Unable to connect to $dbname")

The processing order is:

-first mysql_connect($dbname) || print("Unable to connect to $dbname") is evaluated
-if mysql_connect returns a connection, the expression is ascertained to be true; else the print function is called; if no problem arises, it returns true; therefore this expression is generally the boolean true
-the $link variable is assigned a boolean value which is true if print has no problem.
-the whole expression has the value assigned to $link (therefore, true of false)

2.6 Functions

In this chapter two categories of functions were used:
-the PHP core functions which are always available
-the extended functions provided by extension modules

2.6.1 Core functions

The core functions used in the chapter are:
- echo
- print
- die
- eval

The echo function has the syntax:

echo (string_expression)
where:
string_expression is an expression the value of which is a string data.
The function writes out the value of the string expression to the result page.

The print function has the syntax:

print (string_expression)
where:
string_expression is an expression the result of which is a string data.
The function writes out the value of the string expression to the result page (the same as echo).

The die function has the syntax:

die (string_expression)
where:
string_expression is an expression the result of which is a string data.
The function writes out the the value of the string expression to the result page, then terminates the script.

The eval function has the syntax:

eval (string_expression)
where:
string_expression is an expression the result of which is a string data.
The function produces the same result as though the value of the string expression is hard coded in the script.

2.6.2 The MySQL extended functions

The extension functions used in the chapter are from the MySQL module. They are the following:
mysql_connectconnects to the MySQL database server
mysql_select_dbconnects to a database
mysql_querysubmits a SQL statement
mysql_num_rowsretrieves the number of rows contained in a query result
mysql_num_fieldsretrieves the number of columns contained in a query result
mysql_fetch_arrayretrieves the next row from the query result
mysql_data_seeksets the pointer in the query result, for the next row reference
mysql_free_resultfrees the resources held by the query result
mysql_errorreturns the latest MySQL error
mysql_closecloses the connection to the database server

Unless otherwise stated, the functions return the value true when successfully executed, false when the execution fails.

The mysql_connect function (connect to a server) has the following syntax:

mysql_connect(host:port, username, password)
where:
hostidentifies the host where the database server is -- this can be the host name or its Internet Protocol address like 192.123.212.12
:(colon) is coded as is, if the opional port argument is present
portis the number of the port that the database server is monitoring for incoming requests -- this value defaults to 80
useris the user name under which the script requests a connection to the server
passwordis the password assigned to the user name
The function returns a connection object that is to be used in other functions to communicate with the server.

The mysql_select_db function (connect to a database) has the syntax:

mysql_select_db(databasename)
where databasename is the name of the database that the script is to connect to. The script has first to connect to the database server.

The mysql_query function (submit a SQL statement) has the syntax:

mysql_query(statement)
where statement is the SQL statement to be submitted.
The function returns a table when a SQL statement such as SELECT or DESCRIBE is submitted and successfully executed. It returns a boolean value when a statement such as CREATE DATABASE, CREATE TABLE or INSERT is submitted.

The mysql_num_rows function (return result row number) has the syntax:

mysql_num_rows(result)
where result is the result returned from a mysql_query function.
It returns the number of rows contained in the result.

The mysql_num_fields function (return result column number) has the syntax:

mysql_num_fields(result)
where result is the result returned from a mysql_query function.
It returns the number of columns contained in the result.

The mysql_fetch_array function (returns a result row) has the syntax:

mysql_fetch_array(result, indexMode)
where:
resultis the result table returned by a mysql_query function
indexModeindicates the type of index that can be used to identify an element in the returned row. It can have the values:
MYSQL_ASSOCthe returned array has associative indices
MYSQL_NUMthe returned array has number indices
MYSQL_BOTHthe returned array has both indices -- this is the default
The function returns the next row from the result table:
-the first time it returns the first row
-after the last row has been returned, it returns the boolean value of false
-the next row to be returned can be set by the mysql_data_seek function

The mysql_data_seek function (set next row in the result table) has the syntax:

mysql_data_seek(result, next_row)
where:
resultis the result table returned by a mysql_query function
next_rowis the number of the next row to be accessed when a function such as mysql_fetch_array is executed (the first row has the number 0).

The mysql_free_result function (free resources) has the syntax:

mysql_free_result(result)
where result is a result table returned by a mysql_query function.
The function frees the resources held by the result table.

The mysql_error function (return the latest MySQL error message) has the syntax:

mysql_error()
with no argument.

The mysql_close function (close a server connection) has the syntax:

mysql_close(link)
where link is a connection object returned by the mysql_connect function.

Further details are to be found in the reference manual

2.7 Control statements

The samples in the present chapter made use of the following functions:
if ... elsedepending on the outcome of a test, executes one set of statements or optionally another
forexecute a loop until an ending condition is met
whileexecute a loop as long as a condition is true

2.7.1 The if ... else statement

The if ... else statement has the syntax:
if (condition) {
  if_statements
}
else {
  else_statements
}
where:
conditionis a condition
if_statementsis a set of statements executed if the condition is true
else_statementsis a set of statements executed if the condition is false
The else part of the statement may be omitted.

2.7.2 The while statement

The while statement repeatedly executes a set of statements based on a condition tested at the beginning of each iteration. It has the syntax:
while (condition) 
{
   loop_body
}
where:
conditionis a condition tested at the beginning of each iteration
- if true the body statements are executed
- if false no more execution occurs, the while statement is terminated
loop_bodyis the set of statements to be executed at each iteration, enclosed within curly braces

2.7.3 The for statement

The for statement repeatedly executes a set of statements based on a condition tested at the beginning of each iteration. It has the syntax:
for (initial_set ; condition ; end_set) 
{
   loop_body
}
where:
intitial_setis a set of comma separated statements, executed once before the first iteration
conditionis a condition tested at the beginning of each iteration:
- if true the body statements are executed
- if false no more execution occurs, the for statement is terminated
end_seta set of comma separated statements, executed at the end of each iteration
loop_bodyset of statements to execute at each iteration, enclosed within curly braces; the curly braces may be omitted if the set contains only one statement

2.7.4 More ...

Other statements are investigated in the next chapter.

The reference document can be consulted for more ...

2.8 Illustration

<!-- TestData -->
<HTML><TITLE></TITLE><BODY>
<PRE>
<?php
$a = "1";
$b = "2";
$c = "7ABC";
$d = 5;
$e = $a > 10;

$f = $a + $b;
$g = $a . $b;
$h = $b + $c;
$i = $d.$b;
$j = "$d.$b";
$k = $a+$b.$d;
$l = $d + $e;
print ("f=$f g=$g h=$h i=$i");
print (" j=$j k=$k l=$l\n");

print ("<br>");
if ($a) print ("$a is true\n");
print ("<br>");
if ($e) print ('$e is true');
else print ('$e is false');

print ("<br>xxx = '$c'");
?>
</PRE></BODY></HTML>
The script shown on the left illustrate the behaviour of the data in some typical situations. Five variables are defined and assigned values:
-$a, $b, $c have string values
-$d has a numeric value
-$e has a boolean value
The results of the operations are displayed by the print function as follows:
f=3 g=12 h=9 i=52 j=5.2 k=35 l=5

1 is true
$e is false
xxx = '7ABC'
in $f$a and $b are treated as numeric data
in $g$a and $b are treated as string data (which they natively are)
in $h$c is used for the numeric value of the 7 that starts the string
in $i$d is treated as a string data and concatenated with $b
in $jwithin the double quotes, the dot "." is a character datum, not the concatenation operator
in $k$b is added to $a, the result is concatenated with $d
in $lthe boolean variable $e is treated as a number. Its value false yields the numeric 0.
The test if ($a) shows that $a can be used as a boolean datum and has the value of true
The test if ($e) confirms that $e has a boolean value, which is false.

One remark about the arguments of the print functions following the if ($e) test. They are enclosed within single quotes so that the $e do not expand into the value of the $e variable (within double quotes, to print the $ sign you have to escape it as \$).
In the next line, $c is within single quotes. But then the single quotes are within the outer double quotes. Therefore they are data characters, not quote operators.

3. Syntax summary

This section summarizes the language elements as seen or alluded to in the present chapter. This summary does not exhaust the options of each element. These will be studied more extensively in future chapters. An exhaustive presentation of the language is to be found in the reference documentation

3.1 PHP tags

PHP tags are:
NormalOpening tag<?php(recommended)
Closing tag?>
Short openingOpening tag<?
Closing tag?>
ASP styleOpening tag<%
Closing tag%>

3.2 Data types

The data types examined in this chapter are:
- numeric
- string
- boolean
A given datum is treated as one of these types to suit the operation in which it is involved
- string as numeric:the starting characters if numeric, else, 0
- string as boolean:true if exists and non-empty, false if empty
- numeric as string:digit string
- numeric as boolean:true if non-zero, false if 0 or not a number
- boolean as numeric:1 if true, 0 if false
- boolean as string:1 if true, empty if false

Variable name

$variable_name
where:
$$ sign to appear as is
variable_namehas the following structure:
size:unlimited number of characters
case:case sensitive
first character:alphabetic or underscore
the rest:alphabetic, underscore, numeric or ASCII code 127 to 255 (x'8F' to x'FF')

3.4 Variable types

Some of the variable types are:
- scalar
- array

Array element -- using square brackets:

$varname[number]
$varname["string"]
numeric index or key
string index or key

3.5 Operations

Some of the operations are:
Numeric +addition
-subtraction
*multiplication
/division
String .(dot sign) concatenation
Boolean ANDthe first operand is evaluated first, if false the evaluation is terminated, the result is false
ORthe first operand is evaluated first, if true the evaluation is terminated, the result is true

Use of quotes:

"double quote -- enclosed variables are expanded, enclosed functions are evaluated
'single quote -- enclosed characters are data, no variable expansion or function evaluation

3.6 Functions

The functions used in this chapter are
Core functionsprintwrites out the argument to the result page
diewrites out the argument to the result page and terminates the script
MySql functions
mysql_connectmysql_connect($host, $username, $password)
connects to the MySQL database server
mysql_select_dbmysql_select_db($databasename")
connects to a database
mysql_querymysql_query($statement)
submits a SQL statement
mysql_num_rowsmysql_num_rows($result)
retrieves the number of rows contained in a query result
mysql_num_fieldsmysql_num_fields($result)
retrieves the number of columns contained in a query result
mysql_fetch_arraymysql_fetch_array($result, indexMode)
retrieves the next row from the query result
mysql_data_seekmysql_data_seek($result, next_row)
sets the pointer in the query result, for the next row reference
mysql_free_resultmysql_free_result($result)
frees the resources held by the query result
mysql_closemysql_close($link)
closes the connection to the database server

3.7 Control statements

The program flow control statements used in this chapter are:
if (condition)
   {if_statements}
   else {else_statement}
- condition to be tested
- if_statements executed if condition is true
- else_statements executed if condition is false
The curly braces may be omitted when statement set contains just one statement
for (initial;
condition;
end_loop)
{loop_statements}
- initial: comma separated statement set, executed before the first loop
- condition tested before each loop
- end_loop comma separated statement set, executed at the end of each loop
- loop_statements statements composing the loop
while (condition) {
      loop_statement
}
- condition tested before each loop
- loop_statement statements composing the loop

top Cover  Copyright  Contents  Reference  Index  previous  next