Site.php

By way of illustration, we produced a little package to allow a client to search a database of people (see Chapter 13). PHP syntax is not hard and the manual is at http://www.php.net/manual/en/ref.mysql.php.The database has two fields: xname and sname.

The first page is called index.html so it gets run automatically and is a standard HTML form:

<HTML>
<HEAD>
<TITLE>PHP Test</TITLE>
</HEAD>

<BODY>
<form action="lookup.php" method="post">
Look for people. Enter a first name:<BR><BR>
First name:&nbsp <input name="xname" type="text" size=20><BR>
<input type=submit value="Go">
</form>
</BODY>
</HTML>

In the action attribute of the form element, we tell the returning form to run lookup.php. This contains the PHP script, with its interface to MySQL.

The script is as follows:

<HTML>
<HEAD>
<TITLE>PHP Test: lookup</TITLE>
</HEAD>

<BODY>
Lookup:
<?php print "You want people called $xname"?><BR>
We have:

<?php
/* connect */
mysql_connect("127.0.0.1","webserv","");
mysql_select_db("people");
/* retrieve */
$query = "select xname,sname from people where xname='$xname'";
$result = mysql_query($query);
/* print */
while(list($xname,$sname)=mysql_fetch_row($result))
	{
	print "<p>$xname, $sname</p>";
}
mysql_free_result($result);
?>

</BODY>
</HTML>

The PHP code comes between the <?php and ?> tags.[1] Comments are enclosed by /* and */, just as with C.

The standard steps have to be taken:

  • Connect to MySQL — on a real site, you would want to arrange a persistent connection to avoid the overhead ...

Get Apache: The Definitive Guide, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.