Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - Delete many items from database with one array of IDs

I have this array

array(4) { [0]=> string(1) "1" [1]=> string(1) "3" [2]=> string(1) "4" [3]=> string(1) "5" }

Where every element of this array is ID of post. In mysql, table posts, column ID.

DELETE query for one ID would be something like

DELETE FROM posts WHERE id = $id

I can make look through this array and make delete query on each of them.

But they are 4. So it will be 4 queries. And If I had 70? 70 queries....

And question is, how to delete all posts at once having this array of IDs?

like image 228
Krystian Polska Avatar asked Jun 23 '17 13:06

Krystian Polska


Video Answer


1 Answers

First use implode() to create a string from your array, then use WHERE id IN ():

$ids = implode("','", $array);
queryMethod("DELETE FROM posts WHERE id IN ('".$ids."')");

PHP Manual: Implode

like image 158
modsfabio Avatar answered Oct 08 '22 06:10

modsfabio