0

I want to run one query with multiple statements to delete records from my database all at once. I construct a mysql query like so:

$query  = "DELETE FROM myTable1 WHERE indexID = '".$myVar."' LIMIT 1; ";
$query .= "DELETE FROM myTable2 WHERE indexID = '".$myVar."' LIMIT 1; ";
$query .= "DELETE FROM myTable3 WHERE indexID = '".$myVar."' LIMIT 6; ";

Then, I call my query something like this:

if(!$result = mysqli_query($db, $query)) { 
   echo "error with $query"; 
} 

Am I doing something incorrect? The query that gets printed out, when copied and run inside phpMyAdmin works just fine.

4

3 回答 3

1

我认为您应该创建一个查询数组,然后像这样在循环中执行

       $query  = array["DELETE FROM myTable1 WHERE indexID = '".$myVar."' LIMIT 1",
         "DELETE FROM myTable2 WHERE indexID = '".$myVar."' LIMIT 1",
          DELETE FROM myTable3 WHERE indexID = '".$myVar."' LIMIT 6"];

然后你循环执行

        for($i=0; $i<sizeof($query);$i++)
            {
               $result[$i]=mysql_query($con,$query[$i]);
            }
于 2013-10-02T06:13:02.123 回答
1

这个问题的答案是使用内置的 php 函数:

mysqli_multi_query($db, $query)

它不仅限于 DELETE 查询,还包括任何多语句查询。但是由于 DELETE 不会像 SELECT 那样返回任何我感兴趣的值,所以我们不需要太担心查询的结果集。

如果我们关心结果集,那么由 kushal 提供的带有循环答案的数组可能是一个有用的起点。

于 2013-10-02T15:05:39.497 回答
0

您需要单独执行这些语句。我不相信 mysqli_query() 函数支持多个语句。

$query[] = "DELETE FROM myTable1 WHERE indexID = '".$myVar."' LIMIT 1; ";
$query[] = "DELETE FROM myTable2 WHERE indexID = '".$myVar."' LIMIT 1; ";
$query[] = "DELETE FROM myTable3 WHERE indexID = '".$myVar."' LIMIT 6; ";

foreach($query as $q) {
    $result = mysqli_query($db, $q);
}
于 2013-10-01T20:48:42.433 回答