home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam  


Apache The Definitive Guide, 3rd EditionApache: The Definitive GuideSearch this book

15.2. 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.[54] Comments are enclosed by /* and */, just as with C.

[54]There are other formats: see the .ini file.

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 of reconnecting for each query

  • Invoke a particular database — here, people

  • Construct a database query:

    select xname,sname from people where xname='$xname'
  • Invoke the query and store the result in a variable — $result

  • Dissect $result to reveal the various records that have satisfied the query

  • Print the returned data, line by line

  • Free $result to make its memory available for reuse

And we see on the screen:

Lookup: You want people called jane
We have: 
Jane, Smith
Jane, Jones

The content of the variable $query is exactly what you would type into MySQL. A point worth remembering is that while the query:

select * from name where xname='$xname'

would work if you were using MySQL on its own, you have to specify the variable fields so that PHP can pick them up:

select xname, sname from name where xname='$xname'

But this can be fixed by using a more sophisticated extraction of data:

...
$query = "select * from people where xname='$xname'";
$result = mysql_query($query);

/* print */
while($row=mysql_fetch_array($result,MYSQL_NUM))
	printf("<BR>%s %s",$row[0],$row[1]);

mysql_free_result($result);
...

When we came to run all this, our only difficulty was in getting the script to connect to the database. This was the original code, from the PHP manual:

mysql_connect("localhost","myusername","mypass");

In keeping with the setup on our test machine from the first three chapters of the book, we used:

mysql_connect("localhost","webserv","");

This produced an unpleasant message:

Warning: MySQL Connection Failed: Can't connect to local MySQL server through
socket '/tmp/mysql.sock' (38) in /usr/www/APACHE3/site.php/htdocs/test.php on 
line 7

This was probably caused by our odd setup where DNS was not available to resolve the URL. According to the PHP documentation, there were a number of ways of curing this:

  • Inserting the default port number:

    mysql_connect("localhost:3306","webserv","");
  • Editing /usr/local/lib/php.ini. to include the line:

    mysql.default_port = 3306
  • Inserting this in the Config file:

    SetEnv MYSQL_TCP_PORT 3306

None of them worked, but happily, it was enough to change the line of PHP code to this:

mysql_connect("127.0.0.1","webserv","");

15.2.1. Errors

If you make a syntax error, say by including a } after the printf( ) line, you get a sensible error message on the browser:

Parse error: parse error in /usr/www/APACHE3/site.php/htdocs/lookup2.php on line 25

However, syntax errors are not the only ones. We wanted to leave the previous examples simple, to illustrate what is happening. In real life you have to deal with more sinister errors. PHP has a syntax derived from Perl:

mysql_connect("127.0.0.1","webserv","") or die(mysql_error( ));
mysql_select_db("people")  or die(mysql_error( ));

The function die( ) prints a message — or executes a function that gets and prints a message and then exits. If, for instance we try to select the nonexistent database people2, the function mysql_select_db( ) will fail and return 0. This will invoke die( ), which will run the function mysql_errr( ), which will return the error message generated by MySQL inserted into the HTML. So, on the browser we have the following:

Lookup: You want people called jane
We have: Unknown database 'people2'  

In development you should use or die( ) wherever something might not happen as planned.

However, when the pages are visible to the Web and to the Bad Guys, you would not want so revealing a message made public. It is possible (though too complicated to explain here) to define your own error handler. You might have a global variable — say $error_level is set to develop or live as the case may be. If it is set to develop, your error handler would invoke die( ). If it is set to live, a different function is called, which prints a polite message:

We are sorry that an error has occured

and writes a message to a log file on the server. It might also send you an email using the PHP command mail( ).



Library Navigation Links

Copyright © 2003 O'Reilly & Associates. All rights reserved.