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

7 thoughts on “Simple $wpdb error handling”

  1. 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.

  2. 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.

  3. 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.

Leave a Reply

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