unimportant logo identifying Barry Cornelius

University of Oxford

Computing Services

An Introduction to PHP

  Author: Barry Cornelius Date: 26th November 2003; first created: 16th November 2003

Contents

1. Introduction

PHP is a server-side scripting language. When a visitor to a WWW page visits a page that is a PHP page, the WWW server gets a PHP processor to examine the page. The PHP processor will produce some HTML which is then shipped by the WWW server to the visitor's computer.

As well as the usual constructs that most languages have, in PHP, you can read from files, write to files and execute system commands; you can send mail; you can interrogate an IMAP server; you can access LDAP servers; you can process XML documents; you can do sophisticated mathematical calculations; you can access most of the popular database servers including Oracle, Sybase, Generic ODBC, MSQL and MySQL; and you can do many other things.

In this document, we look at the language and at some of the above possibilities.

2. What is PHP?

PHP was conceived sometime in the Autumn of 1994. Its manual says that ‘PHP's syntax is borrowed primarily from C. Java and Perl have also influenced the syntax’.

Back in mid-1998, PHP's manual boasted that using ‘a conservative estimate ... PHP is in use on 150000 sites around the world’. Nowadays, their WWW site (http://www.php.net/) cites a Netcraft Survey as saying ‘14,528,748 Domains, 1,328,604 IP Addresses’.

You can download PHP from http://www.php.net/. It is available in source form. You can also get binary versions for Windows 98/Me and Windows NT/2000/XP. Although they do not distribute UNIX/Linux binaries, most Linux distributions come with PHP. Binaries are also available on other WWW sites for AmigaOS, Mac OS X, Novell NetWare, OS/2, RISC OS, SGI IRIX 6.5.x and AS/400.

Instead, you could obtain a software bundle containing Apache's WWW server (httpd), PHP and MySQL (a database server). For example, there are many such bundles for Windows, including EasyPHP, FoxServ, sokkit (which evolved from PHPTriad) and Uniform Server. More details about these products are available at: http://www.easyphp.org/, http://www.foxserv.net/, http://www.sokkit.net/ and http://sourceforge.net/projects/miniserver/.

3. Simple PHP scripts

3.1. A simple example

Here is a simple example of a PHP script:

0001: <HTML><BODY>
0002: <?php
0003:    $numrows = 3;
0004:    for ($rownum = 0; $rownum<$numrows; $rownum++)
0005:    {
0006: ?>
0007:       <P>hello world</P>
0008: <?php
0009:    }
0010: ?>
0011: </BODY></HTML>
Suppose that the file hellothree.php contains this code. It can be executed by passing it to a WWW server that understands PHP. Click on the following link to see what happens: http://www.barrycornelius.com/papers/phpintro/code/hellothree.php

If a WWW server is configured to handle PHP, it will pass any file with a php extension to a PHP processor. The PHP processor knows it has to interpret the bits between the <?php and ?> symbols. When given the above script, the PHP processor will output the following HTML and this is what is sent to the visitor's browser:

0012: <HTML><BODY>
0013:       <P>hello world</P>
0014:       <P>hello world</P>
0015:       <P>hello world</P>
0016: </BODY></HTML>

3.2. Outputting HTML from PHP

Instead of switching between HTML and PHP, it is possible to stay in PHP, using the PHP command echo (or print or printf) to output HTML.

So the PHP script given above can instead be written as:

0017: <?php
0018:    echo "<HTML><BODY>\n";
0019:    $numrows = 3;
0020:    for ($rownum = 0; $rownum<$numrows; $rownum++)
0021:    {
0022:       echo "<P>hello world</P>\n";
0023:    }
0024:    echo "</BODY></HTML>\n";
0025: ?>
Go to the script at: http://www.barrycornelius.com/papers/phpintro/code/hellothreeecho.php

3.3. Using a form to supply data

Often the author of a WWW page will want to get data for his/her PHP script from the visitor. This can be done using a WWW form:

0026: <HTML><BODY>
0027: <FORM METHOD="POST" ACTION="helloform.php">
0028:    How many times? 
0029:    <INPUT TYPE="text" NAME="numrows">
0030:    <P>
0031:    <INPUT TYPE="submit" VALUE="submit">
0032: </FORM>
0033: </BODY></HTML>

This WWW form uses a text field to ask the visitor to the WWW page for the number of rows. When the visitor clicks on the submit button, the ACTION attribute of the WWW form indicates that the helloform.php script will be executed. Because the text field of the WWW form has the name numrows, the contents of this text field can be accessed in helloform.php by using this name as an index to PHP's $_POST array. Here is a PHP script that does this:

0034: <HTML><BODY>
0035: <?php
0036:    $numrows = $_POST["numrows"];
0037:    for ($rownum = 0; $rownum<$numrows; $rownum++)
0038:    {
0039: ?>
0040:       <P>hello world</P>
0041: <?php
0042:    }
0043: ?>
0044: </BODY></HTML>
Go to the WWW form at: http://www.barrycornelius.com/papers/phpintro/code/helloform.htm

3.4. Using your own functions

Before long, you will want to use your own functions. Here is an example of some code that declares and uses a function:

0045: <?php
0046:    function in_range($numrowspara)
0047:    {
0048:       if ($numrowspara>=1 && $numrowspara<=10)
0049:          return true;
0050:       else
0051:          return false;
0052:    }
0053:    echo "<HTML><BODY>\n";
0054:    $numrows = $_POST["numrows"];
0055:    if (! in_range($numrows))
0056:    {
0057:       echo "<P>numrows is not within range: $numrows</P>\n";
0058:       echo "</BODY></HTML>\n";
0059:       return;
0060:    }
0061:    for ($rownum = 0; $rownum<$numrows; $rownum++)
0062:    {
0063:       echo "<P>hello world</P>\n";
0064:    }
0065:    echo "</BODY></HTML>\n";
0066: ?>
Go to: http://www.barrycornelius.com/papers/phpintro/code/helloformcheck.htm to access a WWW form that actions the above PHP script.

3.5. Is it possible to execute an infinite loop?

Is it possible for a PHP script to execute an infinite loop and eat up lots of cpu-time on the WWW server? Here is a PHP script to try this:

0067: <HTML><BODY>
0068: <?php
0069:    $count = 0;
0070:    while (true) {
0071:       $today = date("Y-m-d");
0072:       $count++;
0073:       print "count is: $count and today is: $today.<BR>";
0074:    }
0075: ?>
0076: </BODY></HTML>

Note: this PHP script uses a pre-defined function called date: this will be discussed later.

Go to the script at: http://www.barrycornelius.com/papers/phpintro/code/loop.php

The default is to allow a PHP script 30 seconds of cpu-time: it is possible to configure PHP so as to use a different value.

3.6. Using PHP from the command line

Although the code of a PHP file is normally triggered into action by a webserver, it is now possible to run standalone PHP programs, i.e., to run PHP programs from a Unix prompt or from a Windows command shell window.

So, if EasyPHP is being used on a Windows platform, you could type something like the following at a command prompt:

"C:\Program Files\EasyPHP1-7\php\php.exe" hellothree.php
and the PHP processor in the file php.exe would execute hellothree.php. It would output something like:
0077: Content-type: text/html
0078: X-Powered-By: PHP/4.3.3
0079: 
0080: <HTML><BODY>
0081:    <P>hello world</P>
0082:    <P>hello world</P>
0083:    <P>hello world</P>
0084: </BODY></HTML>

4. Calling pre-defined functions

4.1. Introduction

As has already been indicated, PHP allows you to access a lot of different things. Because of this, PHP has a large number of pre-defined functions. This is the main reason why the manual for PHP is enormous. Most of the sections of the manual you can ignore until you need the topic described by the section.

Here is a simple example of a call of a pre-defined function. The date function can return the current date (and time) in various formats:

0085: <HTML><BODY>
0086: <?php
0087:    $today = date("Y-m-d");
0088:    print "<CENTER>today is: $today.</CENTER>";
0089: ?>
0090: </BODY></HTML>
Go to the script at: http://www.barrycornelius.com/papers/phpintro/code/today.php

4.2. Finding out what is available

Related functions are grouped together in the various sections of the PHP manual. Besides the core sections, there are sections which are optional. So what you get in your version of PHP depends on how it was built. There is a function called phpinfo that can be used to determine what is available in the version of PHP you are using:

0091: <HTML><BODY>
0092: <?php
0093:    phpinfo();
0094: ?>
0095: </BODY></HTML>
Go to the script at: http://www.barrycornelius.com/papers/phpintro/code/phpinfo.php

4.3. Including other files and executing OS commands

The next example contains two unrelated topics:

Here is a WWW form that asks a visitor for a command:

0096: <HTML><BODY>
0097: <FORM METHOD="POST" ACTION="system.php">
0098:    <P>
0099:    Enter the command to be executed:<INPUT TYPE="Text" NAME="command">
0100:    <INPUT TYPE="Submit" VALUE="Execute command">
0101: </FORM>
0102: </BODY></HTML>

And here is a PHP script to execute the visitor's OS command:

0103: <HTML><BODY>
0104: <?php
0105:    $command = $_POST["command"];
0106:    require("head.htm");
0107:    if ( $command == "DIR" )
0108:       system("$command");
0109:    else
0110:       echo "<P>not executing: $command</P>";
0111:    require("foot.htm");
0112: ?>
0113: </BODY></HTML>

Go to the WWW form at: http://www.barrycornelius.com/papers/phpintro/code/system.htm

4.4. Accessing an LDAP server

LDAP (Lightweight Directory Access Protocol) provides a way of storing data such as Directory information (or White Page information).

The University of Durham's LDAP server enables anyone who has access to the WWW to find out the e-mail address and phone number of members of the University. Here is a WWW form that asks the visitor to the WWW page to type in part of a person's name:

0114: <HTML><BODY> 
0115: <FORM METHOD="POST" ACTION="ldap.php"> 
0116:    To search for someone from an LDAP server,
0117:    type in the name of the server:
0118:    <INPUT TYPE="text" NAME="server">
0119:    <P>
0120:    type in the search base:
0121:    <INPUT TYPE="text" NAME="search_base">
0122:    <P>
0123:    type in part of their surname:
0124:    <INPUT TYPE="text" NAME="part_name">
0125:    <P> 
0126:    <INPUT TYPE="submit" VALUE="Run query"> 
0127: </FORM> 
0128: </BODY></HTML> 

And here is some PHP code to access the LDAP server. It uses six functions:

Here is the code of the ldap.php script:

0129: <HTML><BODY>
0130: <?php
0131:    $server = $_POST["server"];
0132:    $search_base = $_POST["search_base"];
0133:    $part_name = $_POST["part_name"];
0134:    $c_result = ldap_connect("$server");
0135:    $b_result = ldap_bind($c_result);
0136:    $s_result = ldap_search($c_result, "$search_base", "cn=*$part_name*");
0137:    $info = ldap_get_entries($c_result, $s_result);
0138:    $numrows = $info["count"];
0139:    if ( $numrows == 0 ) {
0140:       echo "<P>There is no entry with a name of $part_name</P>";
0141:       echo "</BODY></HTML>";
0142:       ldap_close($c_result);
0143:       exit;
0144:    }
0145: ?> 
0146:    <TABLE BORDER="1">
0147: <?php
0148:    for ($rownum = 0; $rownum<$numrows; $rownum++) {
0149: ?>
0150:       <TR>
0151:          <TD>
0152:             <?php echo $info[$rownum]["cn"][0]; ?>
0153:          </TD>
0154:          <TD>
0155:             <?php echo $info[$rownum]["ou"][0]; ?>
0156:          </TD>
0157:          <TD>
0158:             <?php echo $info[$rownum]["telephonenumber"][0]; ?>
0159:          </TD>
0160:          <TD>
0161:             <?php 
0162:                echo "<A HREF=mailto:"; 
0163:                echo $info[$rownum]["mail"][0];
0164:                echo ">";
0165:                echo $info[$rownum]["mail"][0];
0166:                echo "</A><BR>";
0167:             ?>
0168:          </TD>
0169:       </TR>
0170: <?php
0171:    }
0172: ?> 
0173:    </TABLE>
0174: <?php
0175:    ldap_close($c_result);
0176: ?>
0177: </BODY></HTML>

Go to the WWW form at: http://www.barrycornelius.com/papers/phpintro/code/ldap.htm

4.5. Sending electronic mail

Here is a WWW page containing a WWW form to obtain the details of an e-mail message from a visitor to this WWW page:

0178: <HTML><BODY>
0179: <FORM METHOD="POST" ACTION="mail.php">
0180:    <P>
0181:    Enter the name of the sender:    <INPUT TYPE="Text" NAME="from">
0182:    <P>
0183:    Enter the name of the recipient: <INPUT TYPE="Text" NAME="to">
0184:    <P>
0185:    Enter the subject of the message:<INPUT TYPE="Text" NAME="subject">
0186:    <P>
0187:    Enter the text of the message:   <INPUT TYPE="Text" NAME="message">
0188:    <P>
0189:    Enter the name of the server:    <INPUT TYPE="Text" NAME="server">
0190:    <P>
0191:    <INPUT TYPE="Submit" VALUE="Send message">
0192: </FORM>
0193: </BODY></HTML>

And here is a PHP script to send an e-mail message:

0194: <HTML><BODY>
0195: <?php
0196:    $to      = $_POST["to"];
0197:    $subject = $_POST["subject"];
0198:    $message = $_POST["message"];
0199:    $from    = $_POST["from"];
0200:    $server  = $_POST["server"];
0201:    ini_set("SMTP", "$server");
0202:    $result = mail("$to", "$subject", "$message", "From: $from");
0203:    print "<CENTER>result is: $result.</CENTER>";
0204: ?>
0205: </BODY></HTML>

Go to the WWW form at: http://www.barrycornelius.com/papers/phpintro/code/mail.htm

Note: it is possible to configure PHP to disable any attempt to send e-mail.

4.6. Manipulating XML documents

XML is a markup language that allows data to be described using your own tags.

PHP comes with an XML parser that allows you to write PHP code that walks through an XML document. It generates events for each part of the document, generating an event for each start tag, for each end tag, and for each occurrence of characters appearing between a start tag and an end tag. In a PHP program, you can nominate functions to be called when these events occur. Note that each part of the XML document is visited only once. If instead you want the ability to wander around an XML document, it is possible to put the representation of the XML document into an array. For more details about parsing XML documents from PHP, look at my document 'Processing XML using PHP': http://www.barrycornelius.com/papers/xml.processing.using.php/

PHP provides an extension that can do XSL transformations. In order to use this extension, the person installing PHP needs to build it with a library that implements XSLT. Suppose we have a file (consumables.xml) that contains the following XML document:

0206: <?xml version="1.0"?>
0207: <consumables>
0208:    <product>
0209:       <category>cassette tape</category>
0210:       <item>DC6150 cartridge</item>
0211:       <price>9.50</price>
0212:    </product>
0213:    <product>
0214:       <category>cassette tape</category>
0215:       <item>DC4-60</item>
0216:       <price>6.00</price>
0217:    </product>
        ...
0428:    <product>
0429:       <category>writeable media</category>
0430:       <item>writeable CD</item>
0431:       <price>1.75</price>
0432:    </product>
0433: </consumables>

Also, suppose the following XSL instructions have been stored in a file called consumables.xsl:

0434: <?xml version="1.0"?>
0435: <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
0436: <xsl:output method="html"/>
0437: <xsl:template match="consumables">
0438:    <html>
0439:    <body>
0440:    <table>
0441:    <tr bgcolor="yellow">
0442:    <td>category</td>
0443:    <td>item</td>
0444:    <td>price</td>
0445:    </tr>
0446:       <xsl:apply-templates/>
0447:    </table>
0448:    </body>
0449:    </html>
0450: </xsl:template>
0451: <xsl:template match="product">
0452:    <tr>
0453:    <td><xsl:value-of select="category"/></td>
0454:    <td><xsl:value-of select="item"/></td>
0455:    <td><xsl:value-of select="price"/></td>
0456:    </tr>
0457: </xsl:template>
0458: </xsl:stylesheet>
Here is a PHP script that takes the consumables.xml file and transforms it using the rules in the consumables.xsl file:
0459: <HTML><BODY>
0460: <?php
0461:    chdir('/users/dcl0bjc/public_html/papers/phpintro/code');
0462:    $xsltproc = xslt_create();
0463:    $html = xslt_process($xsltproc,'consumables.xml','consumables.xsl');
0464:    if (!$html) {
0465:       die('XSLT processing error:' . xslt_error($xsltproc));
0466:    }
0467:    xslt_free($xsltproc);
0468:    echo $html;
0469: ?> 
0470: </BODY></HTML>

Go to the script at: http://www.barrycornelius.com/papers/phpintro/code/xslt.php

My document 'Processing XML using PHP' gives more details about performing XSL transformations in PHP. It is available at: http://www.barrycornelius.com/papers/xml.processing.using.php/

5. Session handling

We may want a WWW page that can retain information from one visit to the WWW page to the next. What we can do is to indicate in the PHP script that we want to use session variables. Then, when a visitor visits our PHP script, they will be assigned a unique id called the session id. Either this can be stored in a cookie in the visitor's browser or the author of the PHP script can arrange for it to be propagated in the URL.

Suppose we want to collect the visitor's name and then greet him/her with this name whenever they visit the WWW page. So we will use a session variable to store the visitor's name. The PHP script can start by checking whether the session variable is set. If it is not set, the PHP script can display a WWW form to collect this information from the visitor. That gets us to the following code. Suppose this code is in a file called intro.php:

0471: <?php
0472:    session_start();
0473:    if (isset($_SESSION["visitors_name"])) {
0474:       $visitors_name = $_SESSION["visitors_name"];
0475:       echo "Hello $visitors_name<br>\n";
0476:    }
0477:    else {
0478: ?>
0479:       <FORM METHOD="post"   ACTION=...">
0480:       Type in your name:
0481:       <INPUT  TYPE="text"     NAME="visitors_name"/>
0482:       <INPUT  TYPE="submit"  VALUE="Register"/>
0483:       </FORM>
0484: <?php
0485:    }
0486: ?>

The ACTION attribute in the above WWW form is incomplete. So what script do we want to execute when the visitor clicks on the Register button? What we could do is to invoke the same script provided we alter the script so that one of the first things it does is to check whether it was triggered into action by the WWW form. So, we can add some code to check whether the appropriate $_POST variable is set, and, if it is, the code can then set the session variable:

0489:    if (isset($_POST["visitors_name"])) {
0490:       $_SESSION["visitors_name"] = $_POST["visitors_name"];
0492:    }
The resulting script is given below. It also includes some code that counts the number of times the visitor has visited this WWW page.
0487: <?php
0488:    session_start();
0489:    if (isset($_POST["visitors_name"])) {
0490:       $_SESSION["visitors_name"] = $_POST["visitors_name"];
0491:       $_SESSION["num_visits"] = 0;
0492:    }
0493:    if (isset($_SESSION["visitors_name"])) {
0494:       $visitors_name = $_SESSION["visitors_name"];
0495:       $_SESSION["num_visits"]++;
0496:       $num_visits = $_SESSION["num_visits"];
0497:       echo "Hello $visitors_name on visit number $num_visits<br>\n";
0498:       echo "<a href=\"intro.php\">click here</a>\n";
0499:    }
0500:    else {
0501: ?>
0502:       <FORM METHOD="post"   ACTION="intro.php">
0503:       Type in your name:
0504:       <INPUT  TYPE="text"     NAME="visitors_name"/>
0505:       <INPUT  TYPE="submit"  VALUE="Register"/>
0506:       </FORM>
0507: <?php
0508:    }
0509: ?>
Go to the script at: http://www.barrycornelius.com/papers/phpintro/code/intro.php

As mentioned above, there are two ways in which a session id can be propagated. The manual says that ‘Cookies are optimal’, but because the visitor can disable support in his/her browser for cookies, PHP provides the alternative way of embedding a session id directly into a URL. The manual points out that ‘URL based session management has additional security risks compared to cookie based session management. Users may send an URL that contains an active session ID to their friends by email or users may save an URL that contains a session ID to their bookmarks and access your site with the same session id always, for example.’

6. Object oriented programming

PHP has some support for object-oriented programming. As shown below, it is possible to declare a class that has variables, constructors and functions.

Here is a file (called person.php) that declares a class called Person:

0510: <?php
0511:    class Person {
0512:       var $iName, $iAge;
0513:       function Person($pName, $pAge) {
0514:          $this->iName = $pName;
0515:          $this->iAge = $pAge;
0516:       }
0517:       function getName() {
0518:          return $this->iName;
0519:       }
0520:       function setName($pName) {
0521:          $this->iName = $pName;
0522:       }
0523:       function getAge() {
0524:          return $this->iAge;
0525:       }
0526:       function setAge($pAge) {
0527:          $this->iAge = $pAge;
0528:       }
0529:       function hasSameAge($pPerson) {
0530:          return $this->iAge==$pPerson->getAge();
0531:       }
0532:       function display() {
0533:          echo "<P>$this->iName's age is $this->iAge</P>\n";
0534:       }
0535:    }
0536: %>

And here is a file (called persontest.php) that declares and uses objects that are of this class:

0537: <?php
0538:    require("person.php");
0539:    // tom and dick
0540:    $tFirstPerson = new Person("tom", 25);
0541:    $tFirstPerson->display();
0542:    $tSecondPerson = new Person("dick", 24); 
0543:    $tSecondPerson->display();
0544:    $tSameAge = $tFirstPerson->hasSameAge($tSecondPerson);
0545:    if ($tSameAge)
0546:       echo "<P>they have the same age</P>\n";
0547:    else
0548:       echo "<P>they have different ages</P>\n";
0549:    // fred and barney
0550:    $tFirstPerson = new Person("fred", 55);
0551:    $tFirstPerson->display();
0552:    $tSecondPerson = new Person("barney", 55); 
0553:    $tSecondPerson->display();
0554:    $tSameAge = $tFirstPerson->hasSameAge($tSecondPerson);
0555:    if ($tSameAge)
0556:       echo "<P>they have the same age</P>\n";
0557:    else
0558:       echo "<P>they have different ages</P>\n";
0559: %>

Go to the script at: http://www.barrycornelius.com/papers/phpintro/code/persontest.php

Other possibilities include:

In a paper entitled 'The Object Oriented Evolution of PHP', Zeev Suraski explains some of the limitations of PHP 4 and outlines what is likely to be provided in PHP 5.

Some of the limitations of PHP 4 are:

Many of the above limitations are being removed in PHP 5. Beta 2 of PHP 5.0.0 has been released. Probably, the most up-to-date statement about the OO features of PHP 5 can be found at: http://www.php.net/zend-engine-2.php. Here is a summary of some of the new features in PHP 5:

Suraski's paper is at: http://www.zend.com/images/press/Feb_2003-4_Zeev_PHP5.pdf. Another useful paper is at: http://www.zend.com/engine2/ZendEngine-2.0.pdf

7. Using MySQL

7.1. What is MySQL?

MySQL is software that is a database server. For more details, go to: http://www.mysql.com/.

7.2. Accessing a MySQL server from PHP

We now move on to produce WWW pages that can manipulate databases. To do this, all we have to do is call the appropriate functions of PHP that enable us to pass SQL statements to a MySQL database.

The PHP scripts that follow use these functions:

7.3. Providing a WWW page to query a table

Suppose we have created a database called Pdcl0bjc_prices; that a table of this database is called consum; and that this table has columns called ID, goods and price. The idea is that each row of this table contains the details about an item of consumables that is for sale; the columns headed goods and price contain the description and the price of the item, and the column headed ID contains a unique number for this item.

If we want to supply a WWW page that can be used to query this table, we need first to obtain from the person visiting the page the name of the item of consumables in which he/she is interested. We can do this by providing a WWW page that contains:

0561: <HTML><BODY>
0562: <FORM METHOD="POST" ACTION="pricesquery.php">
0563:    To search for an item of consumables,
0564:    type in the name of the MySQL server:
0565:    <INPUT TYPE="Text" NAME="server">
0566:    <P>
0567:    and type in part of the name of the item (e.g., Series IV):
0568:    <INPUT TYPE="Text" NAME="goods">
0569:    <P>
0570:    <INPUT TYPE="Submit" VALUE="Run query">
0571: </FORM>
0572: </BODY></HTML>
Go to the WWW form at: http://www.barrycornelius.com/papers/phpintro/code/pricesquery.htm

When the visitor to the page clicks on the Run query button, the pricesquery.php script will be executed. The code of this PHP script appears below.

This script first uses mysql_connect to attempt to connect to the MySQL server. It then uses mysql_select_db to choose a database called Pdcl0bjc_prices. It then assigns to the SQLQuery variable a string containing the characters:

0573: SELECT * FROM consum WHERE goods LIKE '%$goods%'

i.e., a string containing the query in which the visitor is interested. It then calls the function mysql_query to send this SELECT statement to the database Pdcl0bjc_prices. If this is successful, the variable q_result now contains a pointer to a temporary table that has just been created; it contains only those rows satisfying the query.

The call of mysql_num_rows finds out how many rows are in this table. And if this is not zero, the script generates an HTML table containing the rows of data that are in this table. It does this by using a for command to wander through each row of the table. For each row, it generates HTML containing the contents of the ID, goods and price columns.

0574: <HTML><BODY>
0575: <?php
0576:    $server = $_POST["server"];
0577:    $goods  = $_POST["goods"];
0578:    $c_result = mysql_connect($server, "", "");
0579:    $s_result = mysql_select_db("Pdcl0bjc_prices", $c_result);
0580:    $SQLQuery = "SELECT * FROM consum WHERE goods LIKE '%$goods%'";
0581:    $q_result = mysql_query($SQLQuery, $c_result);
0582:    $numrows = mysql_num_rows($q_result);
0583:    if ( $numrows == 0) {
0584:       echo "<p>There are no consumables with a name like $goods</p>";
0585:    }
0586:    else {
0587: ?>
0588:       <TABLE BORDER="1">
0589:       <?php
0590:       for ($rownum = 0; $rownum<$numrows; $rownum++) {
0591:       ?>
0592:          <TR>
0593:             <TD ALIGN="right">
0594:                <?php echo mysql_result($q_result, $rownum, "ID"); ?>
0595:             </TD>
0596:             <TD>
0597:                <?php echo mysql_result($q_result, $rownum, "goods"); ?>
0598:             </TD>
0599:             <TD BGCOLOR="yellow" ALIGN="right">
0600:                <?php printf("%01.2f", mysql_result($q_result, $rownum, "price")); ?>
0601:             </TD>
0602:          </TR>
0603:       <?php
0604:       }
0605:       ?>
0606:       </TABLE>
0607: <?php
0608:    }
0609: ?>
0610: </BODY></HTML>

7.4. Providing a WWW page to insert a new row

We can proceed in a similar way if we want to insert a new row in this table. Besides a box asking for the name of the item, the HTML form also has a box asking for details of its price. And, as we wish to change the database, we will need to supply the MySQL username and password that is appropriate for this database. So the form also has boxes asking for a username and a password:

0611: <HTML><BODY>
0612: <FORM METHOD="POST" ACTION="pricesinsert.php">
0613:    To insert a new item of consumables,
0614:    type in the following information:
0615:    <P>
0616:    name of MySQL server: <INPUT TYPE="Text"     NAME="server">
0617:    <P>
0618:    your username:        <INPUT TYPE="Test"     NAME="username">
0619:    <P>
0620:    your password:        <INPUT TYPE="Password" NAME="password">
0621:    <P>
0622:    name of the item:     <INPUT TYPE="Text"     NAME="goods">
0623:    <P>
0624:    price, e.g. 18.45:    <INPUT TYPE="Text"     NAME="price">
0625:    <P>
0626:    <INPUT TYPE="Submit" VALUE="Update consumables">
0627: </FORM>
0628: </BODY></HTML>
Go to the WWW form: http://www.barrycornelius.com/papers/phpintro/code/pricesinsert.htm

When the person using this WWW form clicks on the Update consumables button, the PHP script in the file pricesinsert.php gets executed. This time, because it wants to update the database, the script's call of mysql_connect needs to provide a username and a password. And, this time, because the query is actually an INSERT, the call of mysql_db_query returns either true or false depending on whether the INSERT was successful or not. The script outputs an appropiate message:

0629: <HTML><BODY>
0630: <?php
0631:    $server   = $_POST["server"];
0632:    $username = $_POST["username"];
0633:    $password = $_POST["password"];
0634:    $goods    = $_POST["goods"];
0635:    $price    = $_POST["price"];
0636:    $c_result = mysql_connect("$server", "$username", "$password");
0637:    $s_result = mysql_select_db("Pdcl0bjc_prices", $c_result);
0638:    $SQLQuery = "INSERT INTO consum SET goods='$goods', price=$price";
0639:    $q_result = mysql_query($SQLQuery, $c_result);
0640:    if ( $q_result == 0) {
0641:       echo "<P>There seems to be a problem with updating the table</P>";
0642:    }
0643:    else {
0644:       echo "<P>The table has been updated.</P>";
0645:    }
0646: ?> 
0647: </BODY></HTML>

8. PHP Applications

8.1. Introduction

Once you have a PHP processor installed, there are plenty of pieces of software written in PHP that you can download from the WWW. There are a number of different lists of such software. The URLs of some of these lists are given at: http://www.php.net/links.php

Here we will look at two PHP applications.

8.2. IMP

At the University of Durham, one of the e-mail products we support is called IMP. This product is accessed using a WWW browser. It provides the visitor with a login screen and, once he/she has authenticated, IMP uses IMAP to contact the machine containing their e-mail. So the product enables a member of the University to handle their e-mail, e.g., to look at their messages, store messages, reply to messages, and compose messages. And they can do this on any machine anywhere in the world provided it has a WWW browser. All the code of IMP is written in PHP.

For more details about IMP, go to: http://www.horde.org/imp/

8.3. JpGraph

JpGraph is a collection of PHP code for producing graphs, pie-charts, bar-charts, etc. The WWW site for JpGraph is at: http://www.aditus.nu/jpgraph/. The developers say that JpGraph ‘makes it easy to draw both "quick and dirty" graphs with a minimum of code and complex professional graphs which requires a very fine grain control’. The product comes with lots of examples and useful documentation.

9. Conclusions



Date: 26th November 2003; first created: 16th November 2003 Author: Barry Cornelius.
This page is copyrighted