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.
Leave a comment
Most Popular Posts
Most Recent
- RockMelt Browser – Future of Browsers?
- Adding Syntax Highlighting – Yay!
- PHP Tip: Handling Form Data
- Q&A: Which Framework Should I Use?
- Make an Impact
- Someone Failed to Inform Me
- Modrewrite and Short Urls – What you really want to know.
- Professional PHP
- Google Speaks on Net Neutrality and Benefits of caching
- Screen Scraping made too easy
Categories
- Computers (4)
- JavaScript (1)
- MySQL (3)
- Personal Life (4)
- PHP (9)
- Software Development (6)
- Technology (3)
- Tips (5)
- Tutorials (1)
- Uncategorized (3)
- Web Development (10)
- Work Life (1)