2

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
  • The global $wpdb; line in your 2nd code snippet appears to be unnecessary, as you don't use $wpdb anywhere in your remove_contributors() function. Commented Jan 18, 2014 at 21:32

1 Answer 1

3

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!" );
}
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.