Successful or Error Message after running mysql code in functions.php

Just for this article, suppose there is a code that I want to run on my WordPress’ functions.php file. It’s a code to delete mysql table on my database. For example, here’s the code:

$wpdb->query( "
DELETE FROM $wpdb->posts
WHERE anything = 'whocares'
" );

The code works, but I want to show a Successful or Failed message after running the code. I also have a code which shows the success message after running, which is here:

function remove_contributors() {
    global $wpdb;
    $args = array( 'role' => 'Contributor' );
    $contributors = get_users( $args );
    if( !empty($contributors) ) {
        require_once( ABSPATH.'wp-admin/includes/user.php' );
        $i = 0;
        foreach( $contributors as $contributor ) {
            if( wp_delete_user( $contributor->ID ) ) {
                $i++;
            }
        }
        echo $i.' Contributors deleted';
    } else {
        echo 'No Contributors deleted';
    }
}
remove_contributors();

Tell me how I can do it in my simple code. Thanks for the time!

1 Answer
1

From the Codex page for $wpdb:

The function [$wpdb->query] returns an integer corresponding to the number of rows affected/selected. If there is a MySQL error, the function will return FALSE.

So in order to display a success/failure message, it should be a simple matter:

$result = $wpdb->query( "
    DELETE FROM $wpdb->posts
    WHERE anything = 'whocares'
" );

if( FALSE === $result ) {
    echo( "Failed!" );
} else {
    echo( "Great success!" );
}

Leave a Comment