php - 准备好的语句检索结果 : Why does bind_result() work and get_result() doesn't?

标签 php mysql

我在这个问题上挣扎了一段时间,并到处寻找答案。帖子:Example of how to use bind_result vs get_result很好地解释了如何使用两种不同的方法来检索已执行的准备语句的结果。这也与我找到的其他答案一致。我使用的是 PHP 版本 5.6.15,因此对于 get_result() 这也不应该成为问题(仅适用于 > 5.3)。

我有一个面向对象的编程环境,但为了测试目的,我将示例 strip 化到最低限度的程序,并从数据库中选择一行来查找错误。

结果:我的“bind_result()”版本完美运行并返回:

ID: 1
Content: Test1

“get_result()”版本返回:

"Call to a member function fetch_assoc() on boolean in ...".

我尝试了很多变体来使其工作,但将其恢复到以下应该工作的最小值,但事实并非如此。有人可以帮忙吗?

我在数据库中的测试表有两列:“id”和“content”。

使用bind_result()的工作版本:

<!DOCTYPE html>
<html lang="en">
    <?php 
        static $connection;
        $config = parse_ini_file('../config.ini');
        $connection = new mysqli('localhost',$config['username'],$config['password'],$config['dbname']);    

        $query = "SELECT * FROM test WHERE id = ?";
        $id = 1;
        $stmt = $connection->prepare($query);
        $stmt->bind_param('i',$id);
        $stmt->execute();

        $stmt->store_result();
        $stmt->bind_result($id, $content);
        while ($stmt->fetch()) {
          echo 'ID: '.$id.'<br>';
          echo 'Content: '.$content.'<br>';
        }

        $stmt->free_result();
        $stmt->close();
        $connection->close();

    ?>
</html>

所以带有 get_result() 的版本不起作用:

<!DOCTYPE html>
<html lang="en">
    <?php 
       static $connection;
       $config = parse_ini_file('../config.ini');
       $connection = new mysqli('localhost',$config['username'],$config['password'],$config['dbname']); 

       $query = "SELECT * FROM test WHERE id = ?";
       $id = 1;
       $stmt = $connection->prepare($query);
       $stmt->bind_param('i',$id);
       $stmt->execute();

       $stmt->store_result();
       $result = $stmt->get_result();
       while ($row = $result->fetch_assoc()) {
        echo 'ID: '.$row['id'].'<br>';
        echo 'Content: '.$row['content'].'<br>';
       }

       $stmt->free_result();
       $stmt->close();
       $connection->close();

    ?>
</html>

最佳答案

终于找到问题所在了。通过这篇文章:Example of how to use bind_result vs get_result 以及@Coolen 的评论。 在 get_result 版本中,该行: $stmt->store_result(); 应该被删除!

关于php - 准备好的语句检索结果 : Why does bind_result() work and get_result() doesn't?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35957739/

相关文章:

PHP preg_replace 符号

php - PubNub 推送通知

PHP 数组键存在于字符串中

javascript - 如何在php中解析javascript数组

mysql - 从命令行下载 MySQL 转储

mysql - 为分片选择下一个最佳最大 id 的更好方法

javascript - 如何在 PHP foreach 中使用 ajax?

php - 单个 CakePHP query() 调用中的多个 SQL 语句?

MySQL - 当日销售的特定产品的平均数量

php - 我无法在实时服务器上的 mysql phpmyadmin 中导入 450 .sql.zip 文件