php - 在 mysqli 中使用准备好的语句时获取数据

标签 php mysql mysqli prepared-statement

这是我在网上找到的标准代码,在使用 mysqli 准备好的语句时 eclipse 刻数据:

$sql = "SELECT Title, CopyrightYear FROM Books WHERE ID=?";

if ($statement = mysqli_prepare($connection, $sql)) {

    mysqli_stmt_bindm($statement, 'i', $id);
    mysqli_stmt_execute($statement); //Question 1 
    mysqli_stmt_bind_result($statement, $title, $year);

    while (mysqli_stmt_fetch($statement)) {  //Question 2 
        echo $title . '-' . $year . '<br/>';
    }
}

我有一些问题:

  1. 为什么我们不存储 mysqli_stmt_execute 的结果?我们可以使用类似的东西:

$result = mysqli_stmt_execute($statement); 那么我们可以从结果集中检索每条记录吗?

  1. 既然我们已经执行了查询,那么 mysqli_stmt_fetch($statement) 是什么意思?我们不是已经执行了$语句了吗,不应该是这样的:mysqli_stmt_fetch($result)吗?

最佳答案

执行函数不返回结果,但mysqli_stmt_get_result()做。然后您可以一次从结果资源中获取一行。这种用法可能对您更有意义:

if ($statement = mysqli_prepare($connection, $sql)) {

    mysqli_stmt_bind_param($statement, 'i', $id);
    mysqli_stmt_execute($statement);
    $result = mysqli_stmt_get_result($statement);

    while ($row = mysqli_fetch_assoc($result)) {
        echo $row['title'] . '-' . $row['year'] . '<br/>';
    }
}

执行函数未返回结果集的一个原因是某些 SQL 语句(如 INSERT、UPDATE、DELETE、CREATE、DROP 等)没有结果集。所以execute函数只返回一个 bool 值来指示语句是否运行成功。

关于php - 在 mysqli 中使用准备好的语句时获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44888125/

相关文章:

php - 如何检查mysql数据库是否存在?

php - 使用关联的 SQL 查询到 cakephp 查询

mysql - "... Where field ON (SELECT ..)"不能与工作 where 子句中的 "select"一起使用

php - 动态 &lt;title&gt; 与 PHP 和 MySQL 错误

php - mysqli::准备 SQL 错误

php - 子查询返回多行

即使 shell 客户端成功,php mysql 连接也会失败

php - Laravel:运行队列:在 Windows Azure Web App 上连续监听

php - 如何使用 PHP 从存储在 MYSQL 中的字符串计算公式

mysql - 删除今天创建的表