Marco Luthe Online! » WordPress Stuff » Handling MySQL Errors Using The $wpdb Class
Handling MySQL Errors Using The $wpdb Class
When you write a WordPress plugin, there is almost no way around executing queries to the WordPress database. The $wpdb class provides all the necessary tools to do so.
Now, I wondered how one could figure out if there was a MySQL error while executing a query – be it a typo in the actual query, an error while establishing a connection to the database or a missing table.
$wpdb->get_results($your_query) always seems to return an object, even if there was an error, so there is no way of finding out if your query has been parsed correctly or not.
With $wpdb->query($your_query) you’re able to find out:
If there was an error, the method will return “FALSE”, otherwise it will return the number of rows affected. Please note that FALSE and 0 (ZERO) are not the same here, so you will have to use “===” (identical) instead of “==” (equal), as it is also mentioned on the WordPress Codex.
So, here we go… I take my “block_ip” function as reference here:
function block_ip($ip) {
global $wpdb;
$query = "INSERT IGNORE INTO wp_blocked_ips (ip) VALUES ('$ip')";
if ($wpdb->query($query) === FALSE) {
return FALSE;
} else {
return $wpdb->get_results($query);
}
}
Then, all you have to do is check the returned value:
$blocked = block_ip('123.456.789.012');
if (!($blocked === FALSE)) {
echo "Everything went fine.";
} else {
echo "An error has occured!";
}
The only problem is that you actually run the query twice, so you should not use the descibed method if this query is executed very often, e.g. on every page.
Special thanks to Johannes Ruthenberg (aka Ammaletu) who helped me see the difference between the methods query() and get_results() in the German WordPress forum.
Filed under: WordPress Stuff · Tags: class, error, MySQL, troubleshooting, wordpress, wpdb
-
http://apartmentonesix.com Peter
-
nb000
-
http://www.saphod.net/ Marco











