MySQL JSON编码数据

时间:2013-04-07 17:35:14

标签: php javascript mysql json mysqli

所以,我有这个PHP文件,它以JSON:

的形式回显数据

这是PHP:

// Recieved the user id:
$userId = $_POST['userId'];

// Create connection
$con = mysqli_connect("123.com", "123", "123", "123", "1234");


// Check connection
if (mysqli_connect_errno($con)) {
    echo "Failed to connect to database " . mysqli_connect_error();
}

// Work with the database to grab user statistics..
$getQuizMode      = "SELECT `QuizModeScore` FROM `userstats` WHERE UserId = $userId";
$getChallengeMode = "SELECT `ChallengeModeScore` FROM `userstats` WHERE UserId = $userId";

$quizModeData      = mysqli_query($con, $getQuizMode);
$challengeModeData = mysqli_query($con, $getChallengeMode);

// Build the response
$arr = array('Quiz' => $quizModeData, 'Challenge' => $challengeModeData);

// echo the json back:
echo json_encode($arr);

现在这是我的客户端javascript:

var variableToSend = "109607962907537440488";

$.post('manageUserStats.php', {userId: variableToSend}, function(data){
    console.log("Got these user stats: ", data);
});

当我看到控制台时,我发现这是记录的:

Got these user stats:  {"Quiz":{"current_field":null,"field_count":null,"lengths":null,"num_rows":null,"type":null},"Challenge":{"current_field":null,"field_count":null,"lengths":null,"num_rows":null,"type":null}}

但是,我想获得这里描述的数据:

Stuff

我做错了什么?为什么我不能得到这两个数字?

1 个答案:

答案 0 :(得分:3)

要获得您的工作,请使用:

$getQuiz = "SELECT QuizModeScore, ChallengeModeScore FROM userstats WHERE UserId = $userId";

$res = mysqli_query($con, $getQuiz);
$row = mysqli_fetch_assoc($res);
$quizModeData = $row['QuizModeScore'];
$challengeModeData = $row['ChallengeModeScore'];

而不是:

$getQuizMode      = "SELECT `QuizModeScore` FROM `userstats` WHERE UserId = $userId";
$getChallengeMode = "SELECT `ChallengeModeScore` FROM `userstats` WHERE UserId = $userId";

$quizModeData      = mysqli_query($con, $getQuizMode);
$challengeModeData = mysqli_query($con, $getChallengeMode);

此外,您应该在查询中使用它之前验证$_POST['userId']。我建议使用PDO,因为在参数化thogh时,mysqli很难开始工作。

修改

要用作PDO,请查看如何create a PDO object然后使用以下内容,假设$pdo是您用于构建PDO的变量的名称。

$query = "SELECT QuizModeScore, ChallengeModeScore FROM userstats WHERE UserId = ?";
$st = $pdo->prepare($query);
$st->execute(array($userId));
$row = $st->fetch(PDO::FETCH_ASSOC);
$quizModeData = $row['QuizModeScore'];
$challengeModeData = $row['ChallengeModeScore'];