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

2 s
2

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

Leave a Reply

Your email address will not be published. Required fields are marked *