PHP Basics: PHP & MySQL Error Checks

Use error checking when making an SQL query.

Often I’ll find on IRC or Forums new developers searching for help because they’re unable to discover what’s broken.

“Was working fine yesterday, now it’s broken.”
“Can someone tell me why this doesn’t work?”
“Why doesn’t this work? It does nothing.”

You need to check for errors when you run a query. This is generally done like so:

1
$get = mysql_query($sql) or die (mysql_error());

Now, that in itself is rather simple to understand. If there are any error’s with your query ($sql), your script will die() and tell you the error.

An even better implementation of this would be:

1
2
3
if(!$get = mysql_query($sql)) {
die("Get query evaluated to false. SQL : {$sql} MySQL Error: ".mysql_error());
}

Now, this is great for debugging purposes. It won’t fly on a live front end site. So you’d swap out the die() with:

1
2
3
4
5
if(!$get = mysql_query($sql)) {
error_log("Get query evaulted to false. SQL : {$sql} - MySQL Error: ".mysql_error());
} else {
/* Continue on with logic that relies upon this query */
}

Now, what happens is if your query failed, you will get an error_log message, and you do check your error logs? Right? Of course! I thought so.
Also, this ensures that after we know our query was successful do we continue on with our logic that relies upon it.