728x90
3

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?

Follow
asked May 16, 2018 at 12:27
Willem van der Veen
27.8k15 gold badges162 silver badges139 bronze badges

3 Answers

                                              Highest score (default)                                                                   Trending (recent votes count more)                                                                   Date modified (newest first)                                                                   Date created (oldest first)                              
1

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.

Follow
answered May 16, 2018 at 13:22
Ankit Panchal
1494 bronze badges
  • 1
    This is probably the most correct solution. Those using DELETE FROM will work, but that isn't how wpdb is intended to work. A little explanation would work - the critical piece being the user of array('%d') which converts the integer appropriately. 
    – Brian C
     Jul 14, 2021 at 12:27
 
2
 

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 :)

Follow
answered May 16, 2018 at 13:18
treyBake
6,2876 gold badges25 silver badges54 bronze badges
-2

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)"));

}
Follow
answered May 16, 2018 at 13:10
raju_odi
1,38112 silver badges27 bronze badges

+ Recent posts