Detecting errors generated by $wpdb->get_results()

The question:

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()?

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

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;
}

Method 2

The best I can find is:

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

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


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment