首页 > 解决方案 > 重用准备好的语句会产生分段错误

问题描述

我必须编写一个调用存储过程的准备好的语句,并且我需要遍历一个数组,为数组中的每个元素调用该过程。所以我想利用您可以设置语句然后多次运行它的效率,只需将值发送到插入。

但是,当我这样做时,我得到的不是 php 错误,而是浏览器错误:

此页面不工作 localhost 没有发送任何数据。ERR_EMPTY_RESPONSE

apache2 日志显示存在分段错误。

我想做这个:

$sql = $this->conn->prepare("call add_instrument(?, @instrument_id)");

for ($i = 0; $i <= count($new_instrument_names)-1; $i++) {
    $sql->bind_param("s", $new_instrument_names[$i]);
    $sql->execute();
    $sql->store_result();
    $sql->bind_result($this->new_instrument_ids[]);
    $sql->fetch();
}

$sql->close();

但是上面会产生分段错误。

所以我必须这样做,将准备好的语句放在循环中,以便它发生在 $new_instrument_names 数组中的每个项目上:

for ($i = 0; $i <= count($new_instrument_names)-1; $i++) {
    $sql = $this->conn->prepare("call add_instrument(?, @instrument_id)");
    $sql->bind_param("s", $new_instrument_names[$i]);
    $sql->execute();
    $sql->store_result();
    $sql->bind_result($this->new_instrument_ids[]);
    $sql->fetch();

    $sql->close();
}

这可能是php7中的错误还是我的代码有问题?谢谢!

标签: phpmysqlstored-proceduresprepared-statement

解决方案


尝试这个:

$name = ""; //variable to bind your statement with
$response = ""; // get results
$sql = $this->conn->prepare("call add_instrument(?, @instrument_id)");
$sql->bind_param("s", $name);
for ($i = 0; $i <= count($new_instrument_names)-1; $i++) {
    $name = $new_instrument_names[$i];
    $sql->execute();
    $sql->store_result();
    $sql->bind_result($response);
    while ($sql->fetch())
        array_push($this->new_instrument_ids,$response);
}
$sql->close();
$this->conn->close(); //close the mysqli connection too

推荐阅读