Detecting errors generated by $wpdb->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;
}

Leave a Comment