我正在尝试使用 php 中的 json 从我的数据库中提取数据。我需要指定一些元素,然后将它们发布到页面上。
我想从 mysql 中“获取”数据并将其返回给 json_encode。我如何使用 SELECT 方法执行此操作。有些人使用了 PDO 方法,而其他人使用了 mysql_assoc,这让我很困惑。
例如,
我有以下行:'id'、'title'、'start'、'backgroundColor'...等。以及所有这些的默认值。 ($array[] = "someValue = default")
我希望它像这样导出:
array(
'id' => 1,
'title' => "someTitle",
'start' => "2012-04-16",
'backgroundColor' => "blue",
'someValue' = > "default",
...
), ....
));
如果有人能以最详细的方式帮助我解决这个问题,我会很棒!
最佳答案
如果您想使用 PDO 执行此操作,那么这里有一个示例:
<?php
$dbh = new PDO("mysql:host=localhost;dbname=DBNAME", $username, $password);
$sql = "SELECT `id`, `title`, `time`, `start`, `backgroundColor`
FROM my_table";
$result = $dbh->query($sql)->fetchAll(PDO::FETCH_ASSOC);
//To output as-is json data result
//header('Content-type: application/json');
//echo json_encode($result);
//Or if you need to edit/manipulate the result before output
$return = [];
foreach ($result as $row) {
$return[] = [
'id' => $row['id'],
'title' => $row['title'],
'start' => $row['start'].' '.$row['time'],
'backgroundColor' => $row['backgroundColor']
];
}
$dbh = null;
header('Content-type: application/json');
echo json_encode($return);
?>
关于php - 从 MySQL 中提取数据到 json 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10184655/