Show errors:
$wpdb->show_errors = true
shows errors automatically, if WP_DEBUG
is set to true
.
$wpdb->suppress_errors = false
stops suppressing errors.
Multisite need special treatment
// Show errors in Multisite:
global $wpdb, $blog_id;
// There's no is_multisite(), so we need to check the ID
// This means, that we can't debug the blog with the ID 1 as MU-blog by default
// Check if we are on Blog ID#1 and if not, check the defines and add error handling
if ( 1 !== $blog_id )
! defined( 'DIEONDBERROR' ) AND define( 'DIEONDBERROR', true );
Output handling
The $wpdb->update()
method has three different outputs. To check against it, you must save the result i a var: $result = $wpdb->update( /* ... */ );
.
The handle those scenarios:
false === $result
: Fail
0 === $result
: Success, but no update
0 < $result
: Success
Class output
$wpdb->last_error
will show you the last error, if you got one.
$wpdb->last_query
will assist you with showing the last query (where the error occurred). It is basically the same as array_pop( $wpbd->queries );
.
Important (security) Note
Please do NOT add this codes on live site. Especially not if caching plugins are involved. This may expose important DB-related data to visitors!
If you can't do otherwise: always wrap your code in conditional statements to prevent public facing debug output!
// Example
function debug_query( $result, $data )
{
global $current_user;
get_currentuserinfo();
if ( current_user_can( 'manage_options' ) )
{
global $wpdb, $blog_id;
1 !== $blog_id
AND ! defined( 'DIEONDBERROR' )
AND define( 'DIEONDBERROR', true );
$wpdb->show_errors = true;
$wpdb->suppress_errors = false;
$output = '<pre style="white-space:pre-line;">';
$output .= 'Last Error: ';
$output .= var_export( $wpdb->last_error, true );
$output .= "\n\nLast Query: ";
$output .= var_export( $wpdb->last_query, true );
if ( false === $result )
{
$result = new WP_Error( 'query_failed', 'No update.', $data );
}
elseif ( 0 === $result )
{
$result = new WP_Error( 'update_failed', 'Updated zero rows.', $data );
}
elseif ( 0 < $result )
{
$result = 'Success';
}
$output .= '</pre>';
// Only abort, if we got an error
is_wp_error( $result )
AND exit( $output.$result->get_error_message() );
}
}
Exposing the $wpdb
object might also expose your database username and password!