-1

我正在尝试将 mySQL 编码为 JSON。我已经尝试过这个流行的链接 JSON 编码 MySQL 结果,但答案对我不起作用。我会感谢你的帮助。

这是我的代码:

<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 新手。

4

3 回答 3

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);
于 2013-07-16T15:35:20.977 回答
2

您正在混合和匹配mysqlmysqli库。

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

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

注意:顺便说一句,我鼓励你使用mysqli 面向对象的风格。

于 2013-07-16T15:36:23.403 回答
0

如果您使用面向对象的接口来执行以下操作,这可能会更清楚mysqli

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

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

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

$result->close();

当你直接在$result.

于 2013-07-16T15:38:33.427 回答