我正在尝试使用 php 中的 json 从数据库中提取数据。我需要具体说明一些元素,然后将它们发布到页面上。
我想从 mysql“获取”数据并将其返回到 json_encode。我怎样才能使用 SELECT 方法来做到这一点。有些使用了 PDO 方法,有些则使用了 mysql_assoc,这让我很困惑。
例如,
我有几行: 'id' 、 'title' 、 'start' 、 'backgroundColor'...等。以及所有这些的默认值。 ($array[] = "someValue = 默认值")
我希望它像这样导出:
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);
?>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)