Detecting errors generated by $wpdb->get_results()

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

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

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

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x