Why $wpdb->show_errors() and print_error() is showing an output even if the query output is correct?

The output that you posted above is expected behaviour for $wpdb->print_error() if the following is true –

  • You are running a single site, not multisite
  • $wpdb->suppress_errors is set to false
  • $wpdb->show_errors is set to false

From the looks of your code, you meet all those conditions.

Note also that, unless you have turned them off previously, $wpdb->show_errors is set to true by default, so you don’t need to call $wpdb->show_errors().

To output something only when there is a DB error you can do one of these two things –

1 – Output the error and add the error to the log

As well as outputting on the screen, the $wpdb->print_error() method will log your error. If this is desirable behaviour (recommended), you can do this –

if($wpdb->last_error !== '') :
    $wpdb->print_error();
endif;

2 – Output the error but do not log it

If you are not interested in logging the error, you can add your own my_print_error() funciton and use that instead of $wpdb->print_error()

function my_print_error(){

    global $wpdb;

    if($wpdb->last_error !== '') :

        $str   = htmlspecialchars( $wpdb->last_result, ENT_QUOTES );
        $query = htmlspecialchars( $wpdb->last_query, ENT_QUOTES );

        print "<div id='error'>
        <p class="wpdberror"><strong>WordPress database error:</strong> [$str]<br />
        <code>$query</code></p>
        </div>";

    endif;

}

Last Edit: Syntax Mistake

Leave a Comment