18

So I can delete one row using:

$this->db->delete($tableName,array("id"=>4));

...but I can't figure out how to delete multiple rows. I tried:

$this->db->delete($tableName,array("id"=>4,"id"=5));

as well as:

$this->db->delete($tableName,array(array("id"=>4),array("id"=5)));

...but they both don't work. I feel like this should be pretty easy. Any answers?

6 Answers 6

40

Have you tried this ?

$names = array(4,5);
$this->db->where_in('id', $names);
$this->db->delete('mytable');
Sign up to request clarification or add additional context in comments.

2 Comments

How can I delete multiple records with delete condition on multiple columns like delete from tbl where col1 = 1 AND col2 = 2; I have this condition in multidim array
great finding ..!! this was not documented in CI docs. Works like a charm
7

not need of associative array.

$ids[] = 1;
$ids[] = 2;

$this->db->where_in( id, $ids );
$this->db->delete('Table_Name');

Comments

4

write custom query for it

$this->db->query("DELETE FROM `TABLE_NAME` WHERE `id` IN(1,2,3,4,5)");

1 Comment

This looks like it should work as it's the manual version of @MoyedAnsari's answer which uses CI's where_in function. Thanks.
3

it is not work

$names = array(4,5);
$this->db->where_in('id', $names);
$this->db->delete('mytable');

DELETE FROM table_name WHERE id IN ('4,5')

notice one thing not single string/digit ('4,5') we should be dived each and every id with single quotation like this ('4','5')

The best and good way

        //$ids = 1,2,3.....
        $ids_exp = explode(',',$ids);
        $this->db->where_in('id',$ids_exp);//
        $this->db->delete('table_name')
        return $this->db->affected_rows();

the above query will be work enjoy..........

1 Comment

why return always 1 when using return $this->db->affected_rows();
1

To delete a single use row:

$this->db->delete('TABLE_NAME', array('id' => 5));

Have you tried doing this? I'm pretty sure it should work.

$this->db->delete('TABLE_NAME', array(array('id' => 5), array('id' => 3), ...));

Comments

0

This is an old question, but I'll answer it since I had to research the same question 8 years later.

I checked the source code of $wpdb->delete(), and it will basically only delete 1 row. It works by matching 1 col to 1 val, and then joining with AND. So if you do array("id"=>4,"id"=>5), it will read it as row with (id==4 AND id==5). No rows will match that condition.

So to delete multiple rows, the only way (as far as i've seen) is to use a custom query:

$wpdb->query("DELETE FROM `TABLE_NAME` WHERE `id` IN(1,2,3,4,5)");

Comments

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.