mysqli_multi_query:需要检查单个结果吗?

时间:2018-02-01 10:52:06

标签: php mysqli

我使用此代码插入具有唯一ID的记录,然后返回刚创建的id-string:

$sql ="set @id=UUID();";
$sql .="INSERT INTO `items` (`id`,`parent`, `text`, `type`) VALUES(@id,'".$parent."', '".$text."', '".$type."');";
$sql .="select @id;";


if (mysqli_multi_query($conn, $sql)) {
  while (mysqli_more_results($conn)) {
    mysqli_use_result($conn);
    mysqli_next_result($conn);
  }//while

  $result = array('id' => mysqli_store_result($conn)->fetch_row()[0]);

  }//if

如果一切正常,三个查询应返回:

  1. 1 / true(我猜)
  2. 1 /真
  3. 物体
  4. 之前我从未使用过此功能,我想知道:如果插入查询失败会发生什么?

    还会执行第三个查询吗?

    在这种情况下,我该如何检查第二个查询的结果?

    修改:

    或者一般来说:

    有一组10个查询,如果失败,我该如何检查哪一个失败?

2 个答案:

答案 0 :(得分:0)

经过一些测试......

假设我们有以下3个查询:

$sql ="INSERT INTO `items` (`id`,`parent`) VALUES ('id',WRONG_NO_QUOTES);";
$sql .="INSERT INTO `items` (`id`,`parent`) VALUES ('id','right2');";
$sql .="INSERT INTO `items` (`id`,`parent`) VALUES ('id','right3');";

使用手册提供的代码......

if (mysqli_multi_query($conn,$sql)) {
    do {
        /* store first result set */
        if ($result = mysqli_store_result($conn)) {
            while ($row = $result->fetch_row()) {
                printf("%s\n", $row[0]);
            }
            $result->free();
        }
        /* print divider */
        if (mysqli_more_results($conn)) {
            printf("-----------------\n");
        }
    } while (mysqli_next_result($conn));
}
//...plus this....
if(mysqli_errno($conn)){
        echo 'mysqli_errno:';
        var_dump(mysqli_errno($conn));
        echo'<br>';
    }

...输出是:

mysqli_errno:
[...]test.php:39:int 1146

...并且数据库没有变化。

结论:

当出现错误时,不执行下一个查询。 并且在do / while循环结束时可以很容易地捕获错误。

修改

上面的代码生成严格的标准通知。

我编辑它以避免通知并获得错误的(基本)回溯:

$n=1;
$i=1;
if (mysqli_multi_query($conn,$sql)) {
    do {
        /* store first result set */
        if ($result = mysqli_store_result($conn)) {
            while ($row = $result->fetch_row()) {
                echo $row[0];
            }
            $result->free();
        }
        /* print divider */
        if (mysqli_more_results($conn)) {
            echo "<hr>";
            $n++;
            mysqli_next_result($conn);
        }else{$i=0;}
    } while ($i>0);
}
if(mysqli_errno($conn)){
  echo 'mysqli error on query number '.$n;
  var_dump(mysqli_errno($conn));
}

答案 1 :(得分:0)

由于我的实际问题是避免查询之间的竞争并获得正确的标识符(检查:this question)我意识到有一种更简单(也许更好)的方法来达到预期的结果(这里使用pdo扩展) :

$db = new PDO ("mysql:host=$hostname;dbname=$dbname", $user, $pass);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 

//No user defined variable here inside (safe)
$identifier=db->query("SELECT UUID();")->fetch()[0];

将标识符存储到PHP变量中,然后我可以使用pdo和prepared语句单独处理每个后续查询。