Better method to delete multiple rows in a MySQL database with PHP?

为君一笑 提交于 2019-12-11 08:58:15

问题


Let's say I have an array with a bunch of ids for a mysql table:

$idList = array('1','2','3','4','5');

I want to delete the rows associated with each id. Which method is more preferable/better/faster (IYO)?

$idListString = implode(",",$idList);
mysql_query("DELETE FROM this_table WHERE id IN ($idListString)");

or

foreach($idList as $value) {
mysql_query("DELETE FROM this_table WHERE id = '$value'");
}

回答1:


I'm no expert, but I believe

$idListString = implode(",",$idList);
mysql_query("DELETE FROM this_table WHERE id IN ($idListString)");

is faster. The reason is, it only makes one query. Less data is sent to the server and it's all processed in one go, in one command.

In general, with the other method, if you have say 300 values, that means you're making 300 additional function calls, 300 communications to the server, etc. though in practice that may vary.

edit: Further, you should always use proper MySQL escaping, even if you can be sure the data is not malicious. See http://php.net/manual/en/function.mysql-real-escape-string.php and consider using mysqli or PDO.




回答2:


I think you should the first one

$idListString = implode(",",$idList);
mysql_query("DELETE FROM this_table WHERE id IN ($idListString)");

Because it cost less traffic than the second one. In the second solution, it called mysql server 5 times. It means

1.Request <--> Response
2.Request <--> Response
3.Request <--> Response
4.Request <--> Response
5.Request <--> Response
...

In my opinion If you have a lot of ids in forloop it may causes bottle neck.

But if you use the 1st, it just has one Request <---> Response.




回答3:


The first method is faster, since it deletes multiple rows in single statement.



来源:https://stackoverflow.com/questions/8542737/better-method-to-delete-multiple-rows-in-a-mysql-database-with-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!