使用 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);