MySQL Error Reporting In PHP

Using MySQL as a database engine in PHP is very powerful, but one thing that can be a pain is trying to debug code. Spotting the difference between a PHP error and a MySQL error can be hard with larger systems.

A good way of debugging MySQL code is by using the mysql_errno() and mysql_error() functions. These functions print off the last error that yuour MySQL server encountered so it can tell you exactly what is wrong with your SQL statements.

The following example code tries to get data from a non-existent table. The $result variable is set to false as the call failed so the error functions print off the SQL error.

<?php
// set up database connection
$dbh = mysql_connect("localhost","root", "wibble");
 
// select database
mysql_select_db("test",$dbh);
 
// execute query
$result = mysql_query("SELECT * FROM table;",$dbh);
if ( !$result ) {
  // print off errors...
  echo mysql_errno($dbh).$quot;: ".mysql_error($dbh)."<br />";
} else {
  $row = mysql_fetch_array($result);
  echo $row[0];
};
?>

It must be noted that you probably shouldn't print this sort of stuff on a live web site. It can give away lots of information about the structure of your database which can be used against you.

Add new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
2 + 4 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.