gpt4 book ai didi

php - 函数内 fetch_assoc 发生 fatal error

转载 作者:行者123 更新时间:2023-11-29 07:29:26 24 4
gpt4 key购买 nike

我真的需要你的帮助。我已经看到了答案,甚至遵循了之前发布的建议,但没有解决方案显示如何使用 PREPARED STATMENTS 使用 fetch 关联数组,因此我不会尝试提交已经回答的问题。我已遵循其他问题的建议,但我仍然得到:

Fatal error: Call to a member function fetch_assoc() on a non-object in /xxx/xxxxxx.php on line 75

我正在向您展示使用 MySQL 的旧代码以及如何使用准备好的语句将其更改为 MySQLi,但我仍然遇到相同的 fatal error 。有人可以帮助我吗,我快疯了,我真的需要找出我做错了什么。感谢您的帮助。

//*******************************************************************
// OLD CODE:
// Called by: $theme=$log->get_theme();
//*******************************************************************
class redirect
{
function __construct()
{

}

function get_theme()
{
$rs=mysql_query("select * from theme where status='yes'");
if(mysql_num_rows($rs)>0)
{
$data=mysql_fetch_array($rs);
return $data['theme_name'];
}

}
}

//*********************************************************************
// OLD CODE:
// Called by: $theme=$log->get_theme($cn);
//*********************************************************************

class redirect
{
public $cn;

function __construct()
{

}
function get_theme($cn)
{
$themeStatus = 'yes';

if ($stmt = $cn->prepare("SELECT * FROM theme WHERE status = ? "))
{
$stmt->bind_param("s", $themeStatus);
$result = $stmt->execute();
$stmt->store_result();
if ($stmt->num_rows >= "1")
{
$data = $result->fetch_assoc(); // ERROR LINE
return $data['theme_name'];
}
}
else
{
echo "Failed to execute prepared statement: " . mysqli_connect_error();
}
}
}

最佳答案

mysqli_stmt::execute根据定义,方法仅返回 bool。因此调用 $result->any_method_name() 将失败,因为 $result 是一个 bool 值。

要使用 MySQLi 库从准备好的语句中获取值,请使用 $stmt->bind_result(...) 绑定(bind)目标变量,然后使用 $stmt->fetch( ) 在 while 循环中获取绑定(bind)变量中的查询结果。之后,您从 MySQLi 切换到 PDO因为它有一个更好的 API 来解决这个问题......

关于php - 函数内 fetch_assoc 发生 fatal error ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33220057/

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