php - 重用准备好的语句会产生段错误

标签 php mysql stored-procedures prepared-statement

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

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

This page isn’t working localhost didn’t send any data. 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 中的错误还是我的代码有问题?谢谢!

最佳答案

试试这个:

$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

关于php - 重用准备好的语句会产生段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57134980/

相关文章:

mysql - 无法保存存储过程 : #1064 - You have an error in your SQL syntax;

php - 如何在 MySQL 表中存储格式化文本?

php - 在 Laravel 中查询关系

mysql - SQL查询: Select all references after a specific item

php - 通过AJAX和PHP更新MySQL数据库

c# - 从Mysql中检索字段到gridview

java - SQL服务器异常: when using jdbc connection to retrieve data

sql - 如何从 SQL 存储过程调用 shell 应用程序?

php - 如何从 jQuery 调用中创建/检索数组

PHP MVC,局部 View ?