PHP and MySQL Tip #1 – Error Checks
I'd like to share with all of you some PHP Tips.
Use error checking when making an SQL query.
All too often I see on IRC & Forums people complaining/asking for help, regarding their mysql_query(). "It was working fine yesterday, now it''s broken." "Can someone tell me why this doesn''t work?" "Why doesn''t this work? It just doesn''t do anything."
People, you need to check for errors when you run a query. This is generally done like so:
$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:
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 really fly on a live front end site. So you'd swap out the die() with:
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 only after we know our query was successful do we continue on with our logic that relies upon it.
No comments yet.