首页 > 解决方案 > PHP 变量不可用 - 尝试分配/使用它时脚本停止

问题描述

我刚刚在我的代码中发现了一个在过去几个小时内无法修复的错误。我正在从数据库中查询某些内容,然后尝试使用结果。但是,每当我尝试访问查询结果的内容时,脚本就会停止。

$recordcount = $db->query("SELECT optin_mail FROM games WHERE id = $game_id");
$result = $db->getrec();
echo "This will be executed without a problem";
if (isset ($result) && $result != null) echo $result;
echo "This won't be executed. The script stops in the line above";

我做了很多测试,发现每次我尝试分配 $result,例如,$newVariable = $result;或者我尝试访问$content = $result["name"];它停止的内容。即使回显它或使用它print_r($result);也会让脚本立即崩溃。

我真的不知道该怎么办了。我检查了查询,result_count 为 1。该函数getrec()基本上只是mysqli_fetch_assoc($queryResult);并且工作得很好,我在同一个文件中多次使用它。

标签: phpsql

解决方案


好的,首先,如果不了解方法的内部,很难说出哪里出了问题getrec()。我的猜测是您试图回显错误类型的数据。函数mysqli_fetch_assoc返回一个数组,因此回显$result不起作用。

尝试

$recordCount = $db->query(sprintf('SELECT optin_main FROM games WHERE id = %s', $game_id));
$results = $db->getrec();
if ($results ?? null) {
    echo $results[0]['optin_main'];
}

推荐阅读