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

我有一个面向对象的编程环境,但是为了测试起见,将示例缩小到了最低的过程,并从数据库中选择一行来查找错误。

结果:我的带有“ 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 - 准备好的语句检索结果:为什么bind_result()有效,而get_result()不起作用?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35957739/

10-13 07:53
查看更多