How do I detect errors when using $wpdb->get_results()?

For example:

$result = $wpdb->get_results("SELECT * FROM this is not a valid query");

The preceding code doesn't generate any exceptions or errors; it simply sets $result to an empty array. How do we reliably detect errors generated by get_results()?


There is a class variable that stores the last error string - $wpdb->last_error. By the looks of the way $wpdb is coded, if the query succeeds, $wpdb->last_error will be an empty string, if it fails, it will be the error string returned by MySQL. So something like this would do the trick.

$result = $wpdb->get_results("SELECT * FROM this is not a valid query");
if ($wpdb->last_error) {
  echo 'You done bad! ' . $wpdb->last_error;
  • Sounds reasonable - I can't look into this right now, but if this works, it would come in handy in the future! Thanks! :) – rinogo Apr 23 '15 at 16:49
  • Came back to this on a later assignment - works great! I've put this code into a function; I updated your answer; I hope you don't mind! – rinogo Nov 6 '17 at 18:53

The best I can find is:

$result = $wpdb->get_results("SELECT * FROM this is not a valid query");

Unfortunately, that hardly solves the problem. I want to handle the error programmatically, not just echo it to the output stream.

  • I suppose I could always do something nasty with intercepting the output buffer... :/ – rinogo Apr 17 '14 at 22:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.