0
$ids = $_POST['ids'];

// sky***earth***sea***sun***...

$ids = explode("***", $ids);

foreach ($ids as $id) {
    $st = $db->query("delete from tags where id = " . $id);
}

Is there a more elegant way to delete multiple rows, especially regarding peformances in case of huge array? Something like:

$st = $db->query("delete from tags where id in " . $ids);

Any suggestion?

qadenza
  • 9,025
  • 18
  • 73
  • 126
  • 1
    This is a duplicate of https://stackoverflow.com/questions/17657760/mysql-delete-multiple-row-in-array. On top of that, your code is vulnerable to SQL Injections, please learn about them here: https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php – Paul May 06 '18 at 17:42
  • @Paul, on client side there is no any input, just user click event. Is the code still vulnerable to sql injeciton? – qadenza May 06 '18 at 17:45
  • 2
    Possible duplicate of [Better method to delete multiple rows in a MySQL database with PHP?](https://stackoverflow.com/questions/8542737/better-method-to-delete-multiple-rows-in-a-mysql-database-with-php) – Pradeep May 06 '18 at 17:45
  • 1
    @bonaca you are using the superglobal $_POST. There is no need for any form in the frontend. I can just send a POST request to that specific file and my payload in ids will be passed to the query without any filtering, escaping or something related. – Paul May 06 '18 at 17:48
  • 1
    If your `id` is a text column i.e. `sky`, `earth` etc Then the `$id` needs to be wrapped in quotes like `$st = $db->query("delete from tags where id = '$id' ");` **But do pay heed to the [SQL Injection Attack](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) Even [if you are escaping inputs, its not safe!](http://stackoverflow.com/questions/5741187/sql-injection-that-gets-around-mysql-real-escape-string) Use [prepared parameterized statements](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php) in either the `MYSQLI_` or `PDO` API's** – RiggsFolly May 06 '18 at 17:56

2 Answers2

1

$kk= ''; foreach ($ids as $id) { $kk.=$id. ','; } $kk = rtrim($kk, ','); $st = $db->query("delete from tags where id In($kk))";

1

Just replace the exploded *** with a comma(,)

$st = $db->query("delete from tags where id in (" . implode(",", explode("***", $ids)) .")");

Source: https://stackoverflow.com/a/17657893/5837918

Kearl
  • 86
  • 5