我如何使用json_encode()函数与MySQL查询结果?我是否需要遍历这些行,或者我可以将其应用到整个结果对象?
当前回答
下面的代码在这里可以正常工作!
<?php
$con=mysqli_connect("localhost",$username,$password,databaseName);
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$query = "the query here";
$result = mysqli_query($con,$query);
$rows = array();
while($r = mysqli_fetch_array($result)) {
$rows[] = $r;
}
echo json_encode($rows);
mysqli_close($con);
?>
其他回答
使用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);
$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。
例如 $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);
我们可以这样简化Paolo Bergantino的答案
$sth = mysql_query("SELECT ...");
print json_encode(mysql_fetch_assoc($sth));
if ($result->num_rows > 0) {
# code...
$arr = [];
$inc = 0;
while ($row = $result->fetch_assoc()) {
# code...
$jsonArrayObject = (array('lat' => $row["lat"], 'lon' => $row["lon"], 'addr' => $row["address"]));
$arr[$inc] = $jsonArrayObject;
$inc++;
}
$json_array = json_encode($arr);
echo $json_array;
} else {
echo "0 results";
}