[英]PHP MySQL Treat GROUP_CONCAT results as separate items
I am making a music classification database using PHP and MySQL. 我正在使用PHP和MySQL创建音乐分类数据库。 I have three tables: 我有三个表:
Song: 歌曲:
ID | Title
------------------------
1 | Example Song
Genre: 类型:
ID | Name
------------------------
1 | Classical
2 | Instrumental
SongGenre 歌曲类型
SongID | GenreID
----------------
1 | 1
1 | 2
My Query is: 我的查询是:
SELECT s.title, GROUP_CONCAT(DISTINCT g.name SEPARATOR ', ')
FROM song s
LEFT JOIN songgenre sg ON s.id=sg.s_id
LEFT JOIN genre g ON sg.genreid = g.id
I'm using GROUP_CONCAT to allow for multiple genres as shown: 我正在使用GROUP_CONCAT允许多种流派,如下所示:
Title: "Example Song" Genres: Classical, Instrumental 标题:“歌曲范例”类型:古典,器乐
I wish to generate a link in PHP for each genre, so that if the user clicks on "Classical" they are brought to more songs listed as Classical. 我希望为每种流派在PHP中生成一个链接,这样,如果用户单击“古典”,它们就会被带到更多列为古典的歌曲中。 The issue is, I am unsure how to give each genre its' own link. 问题是,我不确定如何赋予每种类型自己的链接。 The issue with GROUP_CONCAT is that both genres are returned together in the same row, and I am unsure how to split the row apart to add a link to each separate genre. GROUP_CONCAT的问题在于两种类型都在同一行中一起返回,我不确定如何将行分开以为每个单独的类型添加链接。
Don't group within the database layer—return an ungrouped ( but sorted ) recordset to PHP and handle it from there: 不要在数据库层内分组-将未分组( 但已排序 )的记录集返回给PHP并从那里进行处理:
$qry = $pdo->query('
SELECT sg.SongID, sg.GenreID, s.Title, g.Name
FROM song s
LEFT JOIN songgenre sg ON s.ID = sg.SongID
LEFT JOIN genre g ON sg.GenreID = g.ID
ORDER BY sg.SongID, sg.GenreID
');
if ($qry) {
echo '<ul class="songs">';
$row = $qry->fetch();
while ($row) {
$current_song = $row['SongID'];
echo '<li>'
, '<span class="title">', htmlentities($row['Title']), '</span>'
, '<ul class="genres">';
do {
echo '<li>'
, '<a href="genre.php?id=', intval($row['GenreID']), '">'
, htmlentities($row['Name'])
, '</a>'
, '</li>';
} while ($row = $qry->fetch() and $row['SongID'] == $current_song);
echo '</ul>'
, '</li>';
}
echo '</ul>';
}
a very basic example as requested by OP OP要求的一个非常基本的示例
$var="Classical, Instrumental";
$each=explode(', ',$var);
foreach($each as $v){
echo '<a href="search.php?genre='.$v.'">'.$v.'</a>';
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.