1

I need to do a mass delete from a MySQL table via PHP (using PDO). The table has a field called 'id' and all the id's to be deleted are stored in an array. There may be 5 rows to delete from the table or there may be 5000+.

My immediate thought is to use a foreach and iterate through the array deleting one at time. However something tells me that may not be a very good method if there are a lot of elements in the array.

Any thoughts on a best method for doing this type of delete?

2
  • 2
    Use IN: DELETE FROM table WHERE id IN (1,2,3,4,5) Commented Jun 13, 2014 at 14:48
  • @mcryan is right. But, honestly, iterating over 5,000 array elements containing SQL record ids for a SQL Delete command isn't really detrimental to performance, unless you plan to integrate the process into a public user interface on a high-traffic domain. Basically, it might take 10 seconds for you. Which isn't a bad thing. It's bad when a user waits 10 seconds. You can also iterate over your array and build a query string. In some cases, using a where clause with OR is better for performance than using IN. If performance matters, test. Commented Jun 13, 2014 at 14:50

2 Answers 2

3

Use the following query replacing table_name with the name of the table. $listofIdsToDelete is the the comma separated string obtained by exploding the array of ids'

$query = "DELETE FROM `table_name` WHERE id IN ($listofIdsToDelete)";

EDIT:

You will get a better performance if you prepare:

$pQuery = "DELETE FROM table_name WHERE id = ?" 

and bind each id item in the loop and execute .

Thanks to UselessIntern for the correction mentioned below and the suggestion to include this comment in the answer

Sign up to request clarification or add additional context in comments.

4 Comments

It's an array use implode(',' , $listofIdsToDelete) instead.
You will get a better performance if you prepare $pQuery = "DELETE FROM table_name WHERE id = ?" and bind each item in the array
Ah so add that tidbit of information to your answer. It's not clear, to me at least, at a glance.
Thanks! Didn't know about IN and I wondered if there was prepared statement way of doing it...will look into that.
2

use WHERE IN:

$ids = array(1,2,3,5,6,7);
$db->exec('DELETE from table WHERE id IN ?', [implode(',' $ids)]);

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.