PHP 在数据存在时返回空值


PHP returning null values when the data exists

我正在运行一个移动应用程序,该应用程序使用PHP从Web服务器检索数据。

当我在 sql 查询中运行 SQL 语句时,它会返回正确的数据。

当我运行 PHP 时,它会返回 gameArray 中位置 0 的项目的空值,数组中的所有其他项目都显示正确的值

代码如下

$userResponse = array(
            'login' => $userName,
            'nickname' => $userNickName); 
$stmt = $conn->gamedb->prepare("SELECT player1, player2, currentturn, question1, question2, question3, question4, question5, question6, question7, question8, question9 FROM Game WHERE Player1 = ? OR Player2 = ?");
$stmt->bind_param('ss', $userName, $userName);
$stmt->execute();
$result = $stmt->store_result();
//create games array to be filled when stepping through the games
$gameResponse = array();
if($conn->gamedb->affected_rows > 0)
{
    while ($stmt->fetch())
    {
        $stmt->bind_result($player1, $player2, $currentTurn,
                           $question1, $question2, $question3,
                           $question4, $question5, $question6,
                           $question7, $question8, $question9);
        $gameArray = array($player1, $player2, $currentTurn,
                           $question1, $question2, $question3,
                           $question4, $question5, $question6,
                           $question7, $question8, $question9);

        //stores the game data into an array
        $gameResponse[] = $gameArray;
    }
    //close stmt
    $stmt->close();
}
$response = array(
            $userResponse,
            $gameResponse
            );
echo json_encode($response);

任何帮助都会很棒!

我能建议你尝试更简单的东西吗?

while($row = $result->fetch_assoc()) {
    $gameResponse[] = $row;
}

这样,您就不必经历分配变量等的所有回旋。PHP 会为你做到这一点。

阅读手册页以获取mysqli_stmt::fetch,它清楚地指出

请注意,在调用 mysqli_stmt_fetch() 之前,应用程序必须绑定所有列。

试试这个...

$gameResponse = array();
$stmt->bind_result($player1, $player2, $currentTurn,
                   $question1, $question2, $question3,
                   $question4, $question5, $question6,
                   $question7, $question8, $question9);
while ($stmt->fetch()) {
    $gameResponse[] = array($player1, $player2, $currentTurn,
                            $question1, $question2, $question3,
                            $question4, $question5, $question6,
                            $question7, $question8, $question9);
}