0

所以,我有这个 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}}

但是,我想获取此处显示的数据:

东西

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

4

1 回答 1

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,请查看如何创建 PDO 对象,然后使用以下假设这$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'];
于 2013-04-07T17:56:01.163 回答