'Wordpress wpdb->delete issue

I'm trying to delete a record from the database programmatically. When I have it hardcoded like this it does delete a record from the database:

$wpdb->delete( $table_name, array( 'user_id' => 1, 'timeMin' => 10), array('%d', '%d') );

However, when I try to do it in a dynamic manner with variables, it doesn't work. I even tried casting the variables to int to make sure they are they right type.

$id = (int) wp_get_current_user()->ID;
$time = (int) $_POST['umjp_time'];

$wpdb->delete( $table_name, array( 'user_id' => $id, 'timeMin' => $time), array('%d','%d'));

Why doesn't the dynamic code using variables work and how do I fix this?



Solution 1:[1]

this is how I would recommend doing it:

function vendor_module_remove_dealer($data)
{
    global $wpdb;

    $sql = 'DELETE FROM `'. $wpdb->prefix .'my_table` WHERE `primary_id` = %d;';

    try {
        $wpdb->query($wpdb->prepare($sql, array($data['primary-id'])));

        return true;
    } catch (Exception $e) {
        return 'Error! '. $wpdb->last_error;
    }
}

this will prevent SQL Injection and delete your record safely, if it fails an error msg will be returned :)

Solution 2:[2]

I tried like this and it's working for me.

global $wpdb;

$id = (int) wp_get_current_user()->ID;
$time = (int) '4';
$table_name = 'testtable';
$wpdb->show_errors(); 
$wpdb->delete( $table_name, array( 'user_id' => $id, 'timeMin' => $time), array('%d','%d'));
$wpdb->print_error();

What errors you are getting please can you explain? You can print errors by using show_errors() and print_error() methods.

Solution 3:[3]

Please use below code i think it will work.

global $wpdb;

$id = (int) wp_get_current_user()->ID;
$time = (int) $_POST['umjp_time'];

$table_name = $wpdb->prefix . 'table_name';
if (!empty($id)) 
{

  $wpdb->query($wpdb->prepare("DELETE FROM $table_name WHERE user_id IN($id)"));

}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 treyBake
Solution 2 Ankit Panchal
Solution 3