将数据从MySQL提取到json数组中 [英] Pulling data from MySQL into json array
问题描述
我正在尝试使用php中的json从数据库中提取数据.我需要具体说明一些要素,然后将它们发布在页面上.
I'm trying to pull data from my database using json in php. I have a few elements I need to specific then to post them on a page.
我想从mysql中获取"数据并将其返回给json_encode.如何使用SELECT方法执行此操作.有些人使用了PDO方法,另一些人使用了mysql_assoc,这使我感到困惑.
I want to "fetch" the data from mysql and return it to a json_encode. How can I do this using the SELECT method. Some had used PDO methods and other have used mysql_assoc, which confuses me.
例如,
我有以下行:'id','title','start','backgroundColor'...等.以及所有这些的默认值. ($ array [] ="someValue = default")
I have rows of: 'id' , 'title' , 'start', 'backgroundColor'...etc. along with a default value for all of them. ($array[] = "someValue = default")
我希望它像这样导出:
array(
'id' => 1,
'title' => "someTitle",
'start' => "2012-04-16",
'backgroundColor' => "blue",
'someValue' = > "default",
...
), ....
));
如果有人能以最好的细节帮助我,我会很棒的!
If anyone could help me with this with the best detail, I'd be awesome!
推荐答案
如果您想使用PDO进行此操作,请参见以下示例:
If you wanted to do this with PDO then here is an example:
<?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);
?>
这篇关于将数据从MySQL提取到json数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!