Simple $wpdb error handling
For my own copy and paste pleasures, here are some wpdb error handling examples. It will grow over time:
A very simple non-failing method for in a function:
if ($wpdb->query($query) === FALSE) { return FALSE; } else { return $wpdb->get_results($query); }
A more complex method for in a function. It uses WordPress’s built in WP_Error class:
if ( false === $wpdb->query($sql)) { if ( $wp_error ) { return new WP_Error( 'db_query_error', __( 'Could not execute query' ), $wpdb->last_error ); } else { return 0; } }
A very simple flow breaking method, in-line procedural:
if ($wpdb->query($query) === FALSE) { wp_die( __('Crap! well that’s screwed up: ' . $wpdb->last_error) ); }
T H A N K Y O U !!! you saved me today… 😉
Glad to be of service!
By the way, do you know how to cath error from $wpdb->get_results ?? thanx
If an error were to occur, it would more than likely occur on the query() call. However, you can look to see if get_results has returned valid data and handle the exception there. So you could modify the last example in my post and instead of a === false do a === NULL
That should get you where you need to be.
Good job man!
Thanks for the advice. Do you know how to get the last error NUMBER? Not just the error text? For example, if a user tried to insert a duplicate key I want to handle that differently than any other error.
I can point you to a couple things.. first take a look at using mysql’s “ON DUPLICATE KEY UPDATE” (Google for that) and you can handle updates right from within you query.
Second look at $wpdb->insert_id or mysql_insert_id(). I don’t know what it will return for a duplicate key error, but it might have what you want.