Specifications

If an error occurs, you can access the text of the error message using the function
mysql_error(),or an error code using the function mysql_errno(). If the last MySQL func-
tion did not generate an error, mysql_error() returns an empty string and mysql_errno()
returns 0.
For example, assuming that we have connected to the server and selected a database for use,
the following code snippet
$result = mysql_query( ‘select * from does_not_exist’ );
echo mysql_errno();
echo ‘<BR>’;
echo mysql_error();
might output
1146
Table ‘dbname.does_not_exist’ doesn’t exist
Note that the output of these functions refers to the last MySQL function executed (other than
mysql_error() or mysql_errno()). If you want to know the result of a command, make sure
to check it before running others.
Like file interaction failures, database interaction failures will occur. Even after completing
development and testing of a service, you will occasionally find that the MySQL daemon
(mysqld) has crashed or run out of available connections. If your database runs on another
physical machine, you are relying on another set of hardware and software components that
could failanother network connection, network card, routers, and so on between your Web
server and the database machine.
You need to remember to check if your database requests succeed before attempting to use the
result. There is no point in attempting to run a query after failing to connect to the database
and no point in trying to extract and process the results after running a query that failed.
It is important to note at this point that there is a difference between a query failing and a
query that merely fails to return any data or affect any rows.
An SQL query that contains SQL syntax errors or refers to databases, tables, or columns that
do exist might fail. The following query, for example
select * from does_not_exist;
will fail because the table name does not exist, and it generates an error number and message
retrievable with mysql_errno() and mysql_error().
A SQL query that is syntactically valid, and refers only to databases, tables, and columns that
exist will not generally fail. The query might however return no results if it is querying an
Debugging
C
HAPTER 23
23
DEBUGGING
483
29 7842 CH23 3/6/01 3:41 PM Page 483