PHP在数据存在时返回空值

时间:2013-10-14 03:14:39

标签: php sql mysqli

我正在运行一个使用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);

任何帮助都会很棒!

2 个答案:

答案 0 :(得分:1)

我可以建议你尝试一些更简单的东西吗?

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

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

答案 1 :(得分:0)

阅读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);
}