feed Posts (RSS | eMail)
feed Comments (RSS | eMail)
Loading in process - please be patient.

Please consider signing the Google Gmail Automatic BCC Option Petition
and spread the word. Thanks!

I need more signatures - at least, help me reach the 100 for starters! :-)
[click box to close]

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.

The post ends here. Wanna leave a response? Have Your Say!

Next post: Amazon Pricewatcher
Previous post: ActiveSync Troubleshooting

Trackback URI | Comments RSS | Permalink

del.icio.us del.icio.us eMail this post eMail Print Print
Did you like this post? NoYes
No votes yet, be the first!
Loading ... Loading ...

Have Your Say!

back to top