Specifications

but except in the, possibly rare, case in which the variable $var has the value 4, the call to
strstr() will not occur, and no warning will be issued.
Calling functions incorrectly is easy to do, but as the resulting error messages identify the
exact line and function call that are causing the problem, they are equally easy to fix. They are
only difficult to find if your testing process is poor and does not test all conditionally executed
code. When you test, one of the goals is to execute every line of code exactly once. Another
goal is to test all the boundary conditions and classes of input.
Reading or Writing Files
Although anything can go wrong at some point during your programs useful life, some things
are more likely than others. Errors accessing files are likely enough to occur that you need to
handle them gracefully. Hard drives fail or fill up, and human error results in directory permis-
sions changing.
Functions such as fopen() that are likely to fail occasionally generally have a return value to
signal that an error occurred. For fopen(), a return value of false indicates failure.
For functions that provide failure notification, you need to carefully check the return value of
every call and act on failures.
Interaction with MySQL or Other Databases
Connecting to and using MySQL can generate many errors. The function mysql_connect()
alone can generate at least the following errors:
MySQL Connection Failed: Can’t connect to MySQL server on ‘hostname’
(111)
MySQL Connection Failed: Can’t connect to local MySQL server through
socket ‘/tmp/mysql.sock’ (111)
MySQL Connection Failed: Unknown MySQL Server Host ‘hostname’ (2)
MySQL Connection Failed: Access denied for user: ‘username@localhost’
(Using password: YES)
As you would probably expect, mysql_connect() provides a return value of false when an
error occurs. This means that you can easily trap and handle these types of common errors.
If you do not stop the regular execution of your script and handle these errors, your script will
attempt to continue interacting with the database. Trying to run queries and get results without
a valid MySQL connection will result in your visitors seeing an unprofessional-looking screen
full of error messages.
Many other commonly used MySQL related PHP functions such as mysql_pconnect(),
mysql_select_db(), and mysql_query() also return false to indicate that an error occurred.
Building Practical PHP and MySQL Projects
P
ART V
482
29 7842 CH23 3/6/01 3:41 PM Page 482