gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 11:40:00 25 4
gpt4 key购买 nike

我在这个问题上挣扎了一段时间,并到处寻找答案。帖子: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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com