PHP使用MySQL'mysqli_multi_query'不止一次?

时间:2013-07-10 09:15:59

标签: php mysql mysqli

尝试执行以下PHP代码,但只有第一个语句成功执行,其余的跟随不执行。

<?php

$link = mysqli_connect('localhost', 'root', '');
mysqli_select_db($link, 'database_name');


$update = " UPDATE `temp` SET `price` = 1000 WHERE `id` = 1;
            UPDATE `temp` SET `price` = 2000 WHERE `id` = 2;
            UPDATE `temp` SET `price` = 3000 WHERE `id` = 3;
            UPDATE `temp` SET `price` = 4000 WHERE `id` = 4;
            UPDATE `temp` SET `price` = 5000 WHERE `id` = 5;";

mysqli_multi_query($link, $update);

$update2 = "UPDATE `temp` SET `price` = 6000 WHERE `id` = 6;
            UPDATE `temp` SET `price` = 7000 WHERE `id` = 7;
            UPDATE `temp` SET `price` = 8000 WHERE `id` = 8;
            UPDATE `temp` SET `price` = 9000 WHERE `id` = 9;
            UPDATE `temp` SET `price` = 10000 WHERE `id` = 10;";

mysqli_multi_query($link, $update2);

?>

mysqli_multi_query($ link,$ update); - 成功执行

mysqli_multi_query($ link,$ update2); - 未执行。

任何人都可以指导,如果我可能遗漏某些内容,或者有关语法的话。

4 个答案:

答案 0 :(得分:1)

如何只使用一个查询

UPDATE `temp` 
SET `price` = case when id = 1 then 1000 
                   when id = 2 then 2000
                   when id = 3 then 3000
                   when id = 4 then 4000
                   when id = 5 then 5000
                   when id = 6 then 6000
                   when id = 7 then 7000
                   when id = 8 then 8000
                   when id = 9 then 9000
                   when id = 10 then 10000
                   else price
              end

答案 1 :(得分:0)

$sql = "UPDATE temp SET price = ? WHERE id = ?";
$stm = $link->prepare($sql);
$link->autocommit(FALSE);
$stm->bind_param("ii" $row['price'], $row['id']);
foreach ($array as $row) {
    $stm->execute();
}
$link->commit();

这样的事情但未经过测试。我总是鄙视mysqli处理预备陈述的方式

答案 2 :(得分:0)

您必须获取所有结果 - 例如:

// here: first multi query

// fetch all results
while( mysqli_more_results($link) ){
    $result = mysqli_store_result($link);
    mysqli_next_result($link);
}

// here: second multi query

某些语言中的某些SQL系统“懒惰”。它们仅在您请求结果时发送查询(例如,C#中的LINQ)。也许PHP会这样做。它会阻止等待结果提取的连接。

答案 3 :(得分:-2)

您是否尝试将所有更新合并为一个然后再运行?

 $link = mysqli_connect('localhost', 'root', '');
 mysqli_select_db($link, 'database_name');


 $update = " UPDATE `temp` SET `price` = 1000 WHERE `id` = 1;
        UPDATE `temp` SET `price` = 2000 WHERE `id` = 2;
        UPDATE `temp` SET `price` = 3000 WHERE `id` = 3;
        UPDATE `temp` SET `price` = 4000 WHERE `id` = 4;
        UPDATE `temp` SET `price` = 5000 WHERE `id` = 5;
        UPDATE `temp` SET `price` = 6000 WHERE `id` = 6;
        UPDATE `temp` SET `price` = 7000 WHERE `id` = 7;
        UPDATE `temp` SET `price` = 8000 WHERE `id` = 8;
        UPDATE `temp` SET `price` = 9000 WHERE `id` = 9;
        UPDATE `temp` SET `price` = 10000 WHERE `id` = 10;";

  mysqli_multi_query($link, $update);