Php JSON对象中的两个MySQL查询
我正在尝试通过MySQL和PHP构建以下JSON。Php JSON对象中的两个MySQL查询,php,mysql,arrays,json,Php,Mysql,Arrays,Json,我正在尝试通过MySQL和PHP构建以下JSON。 每个章节都有一个id、一个章节标题和一个主题列表。 每个主题都有一个id和一个主题区域 { "Chapters": [ { "id": "1", "chapterTitle": "Introduction", "Topics": [ { "id": "1", "topicArea": "C++"
每个章节都有一个id、一个章节标题和一个主题列表。
每个主题都有一个id和一个主题区域
{
"Chapters": [
{
"id": "1",
"chapterTitle": "Introduction",
"Topics": [
{
"id": "1",
"topicArea": "C++"
},
{
"id": "2",
"topicArea": "Java"
}
]
},
{
"id": "2",
"chapterTitle": "Getting Started",
"Topics": [
{
"id": "1",
"topicArea": "Start Here"
}
]
}
]
}
但是,如果我尝试下面的PHP代码()
请不要再使用
mysql.*
函数。mysqli
和PDO
都允许您使用准备好的语句
话虽如此,您认为
$json['Topics]=$json2代码>是问题所在:这需要是$json['Topics'][]=$json2代码>
最后,出于性能原因(请看),您可能希望查看一个JOIN
。总而言之:
$dbh = new PDO("mysql:host=$db_host;dbname=$db_name", $db_user, $db_pass);
$query = 'SELECT c.id AS chapter_id, c.chapterTitle, t.id as topic_id, t.topicArea FROM chapters c INNER JOIN topics t ON c.id = t.chapterid';
$json = array();
foreach ($dbh->query($query) as $row) {
$json[$row['chapter_id']]['id'] = $row->chapter_id;
$json[$row['chapter_id']]['chapter_title'] = $row->chapter_title;
$json[$row['chapter_id']]['Topics'][] = array(
'id' => $row->topic_id,
'topicArea' => $row->topicArea,
);
}
print json_encode(array_values($json));
请不要再使用mysql.*
函数。mysqli
和PDO
都允许您使用准备好的语句
话虽如此,您认为$json['Topics]=$json2代码>是问题所在:这需要是$json['Topics'][]=$json2代码>
最后,出于性能原因(请看),您可能希望查看一个JOIN
。总而言之:
$dbh = new PDO("mysql:host=$db_host;dbname=$db_name", $db_user, $db_pass);
$query = 'SELECT c.id AS chapter_id, c.chapterTitle, t.id as topic_id, t.topicArea FROM chapters c INNER JOIN topics t ON c.id = t.chapterid';
$json = array();
foreach ($dbh->query($query) as $row) {
$json[$row['chapter_id']]['id'] = $row->chapter_id;
$json[$row['chapter_id']]['chapter_title'] = $row->chapter_title;
$json[$row['chapter_id']]['Topics'][] = array(
'id' => $row->topic_id,
'topicArea' => $row->topicArea,
);
}
print json_encode(array_values($json));
查看SQL注入和SQL参数来修复它代码>否则会被覆盖你告诉我们出了问题,但你没有告诉我们结果如何。为了指出逻辑缺陷,我们需要了解这一点。查看SQL注入和SQL参数以修复它代码>否则会被覆盖你告诉我们出了问题,但你没有告诉我们结果如何。我们需要看到这一点,以便不仅仅指出逻辑上的缺陷。