JSON编码mySQL结果说明

时间:2013-07-16 15:26:38

标签: php mysql

我很想将mySQL编码为JSON。我试过这个流行的链接 JSON encode MySQL results但答案对我不起作用。我会认可你的帮助。

这是我的代码:

<html>
<body>

<?php
    header('Content-Type: text/html; charset=utf-8');
    $con=mysqli_connect("localhost","root","root","Theory");
    // Check connection
    if (mysqli_connect_errno())
    {
        echo "Failed to connect to MySQL: " . mysqli_connect_error();
    }
    $result = mysqli_query($con,"SELECT `questions`.`questionID` AS question,
                                        `questions`.`questionText` AS questionText,
                                        `questions`.`categoryID` AS categoryID,
                                        `answers`.`answerID` AS answerID,
                                        `answers`.`answerText` AS answerText,
                                        `answers`.`isTrue` AS isTrue
                                 FROM `questions`,`answers`
                                 WHERE `questions`.`questionID`=`answers`.`questionID`");

    if (!$result)
    {
        die('Error: ' . mysqli_error($con));
    }

   $rows = array();
   while($r = mysql_fetch_assoc($result)) {
   $rows[] = $r;
   }
   print json_encode($rows);

    mysqli_close($con);
    ?>

</body>
</head>

我得到:“[]” 对不起,如果我做了一些愚蠢的事,我是php的新手。

3 个答案:

答案 0 :(得分:3)

也许试试:

$rows = array();
$i = 0;
while($r = mysqli_fetch_assoc($result)) {
    $rows[$i] = $r;
    $i++;
}
print json_encode($rows);

或者也许:

$rows = array();
while($r = mysqli_fetch_assoc($result)) {
    array_push($rows, $r);
}
print json_encode($rows);

答案 1 :(得分:2)

您正在混合和匹配mysqlmysqli库。

如果您使用的是mysqli(代码的其余部分),则需要使用mysqli functions。在这种情况下mysqli_fetch_assoc()

while($r = mysqli_fetch_assoc($result)) {
  $rows[] = $r;
}

注意:另外,我建议您使用mysqli Object Oriented样式。

答案 2 :(得分:0)

如果您使用object-oriented interfacemysqli,这可能会更加清晰:

$mysqli = new mysqli("localhost", "root", "root", "Theory");

$result = $mysqli->query("...");

while ($row = $result->fetch_object())
{
  ...
}

$result->close();

当你直接在$result上调用方法时,很难混淆方法。