我如何使用json_encode()函数与MySQL查询结果?我是否需要遍历这些行,或者我可以将其应用到整个结果对象?


当前回答

根据我的经验,在命名根元素之前,上述方法是行不通的 数组中的东西,我还没有能够访问任何东西 最后的json。

$sth = mysql_query("SELECT ...");
$rows = array();
while($r = mysql_fetch_assoc($sth)) {
    $rows['root_name'] = $r;
}
print json_encode($rows);

这应该能奏效!

其他回答

使用PDO时

使用fetchAll()获取所有行作为关联数组。

$stmt = $pdo->query('SELECT * FROM article');
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($rows);

当你的SQL有参数时:

$stmt = $pdo->prepare('SELECT * FROM article WHERE id=?');
$stmt->execute([1]);
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($rows);

当需要重新输入表的键时,可以使用foreach循环并手动构建数组。

$stmt = $pdo->prepare('SELECT * FROM article WHERE id=?');
$stmt->execute([1]);

$rows = [];
foreach ($stmt as $row) {
    $rows[] = [
        'newID' => $row['id'],
        'Description' => $row['text'],
    ];
}

echo json_encode($rows);

使用mysqli时

使用fetch_all()获取所有行作为关联数组。

$res = $mysqli->query('SELECT * FROM article');
$rows = $res->fetch_all(MYSQLI_ASSOC);
echo json_encode($rows);

当你的SQL有参数时,你需要执行prepare/bind/execute/get_result。

$id = 1;
$stmt = $mysqli->prepare('SELECT * FROM article WHERE id=?');
$stmt->bind_param('s', $id); // binding by reference. Only use variables, not literals
$stmt->execute();
$res = $stmt->get_result(); // returns mysqli_result same as mysqli::query()
$rows = $res->fetch_all(MYSQLI_ASSOC);
echo json_encode($rows);

当需要重新输入表的键时,可以使用foreach循环并手动构建数组。

$stmt = $mysqli->prepare('SELECT * FROM article WHERE id=?');
$stmt->bind_param('s', $id);
$stmt->execute();
$res = $stmt->get_result();

$rows = [];
foreach ($res as $row) {
    $rows[] = [
        'newID' => $row['id'],
        'Description' => $row['text'],
    ];
}

echo json_encode($rows);

当使用mysql_* API时

请尽快升级到受支持的PHP版本!请认真对待。如果你需要一个使用旧API的解决方案,这是可以做到的:

$res = mysql_query("SELECT * FROM article");

$rows = [];
while ($row = mysql_fetch_assoc($res)) {
    $rows[] = $row;
}

echo json_encode($rows);

我们可以这样简化Paolo Bergantino的答案

$sth = mysql_query("SELECT ...");
print json_encode(mysql_fetch_assoc($sth));

例如 $result = mysql_query("SELECT * FROM userprofiles where NAME='TESTUSER' ");

1.)如果$result只有一行。

$response = mysql_fetch_array($result);
echo json_encode($response);

2.)如果$result多于一行。你需要迭代这些行,并将其保存到一个数组中,并返回一个包含数组的json。

$rows = array();
if (mysql_num_rows($result) > 0) {
    while($r = mysql_fetch_assoc($result)) {
       $id = $r["USERID"];   //a column name (ex.ID) used to get a value of the single row at at time
       $rows[$id] = $r; //save the fetched row and add it to the array.
    }
}    
echo json_encode($rows);
$sth = mysqli_query($conn, "SELECT ...");
$rows = array();
while($r = mysqli_fetch_assoc($sth)) {
    $rows[] = $r;
}
print json_encode($rows);

函数json_encode需要PHP >= 5.2和PHP -json包-正如这里提到的

注意:mysql在PHP 5.5.0已弃用,请使用mysqli扩展http://php.net/manual/en/migration55.deprecated.php。

http://www.php.net/mysql_query说“mysql_query()返回一个资源”。

http://www.php.net/json_encode说它可以编码任何值,“除了资源”。

您需要在数组中遍历和收集数据库结果,然后对数组进行json_encode。