【发布时间】:2016-02-23 17:24:56
【问题描述】:
如何正确回显一对多查询结果?
对于一个表的查询结果,我会在获取每一行后回显它,例如:
+---+------+
|ID | title|
|1 | a |
|2 | b |
|3 | c |
+---+------+
$smtp->bind_result($ID, $title);
while($smtp->fetch()) {
\\echo here
}
但是在使用带有自然连接的查询(下面的示例)之后,我不知道如何在 PHP 中将其回显为:
“3 - c - Action, Fantasy, Military”
+----+-------+----------+
| ID | title | genre |
| 3 | c | Action |
| 3 | c | Fantasy |
| 3 | c | Military |
+----+-------+----------+
编辑:
让我重新表述这个问题。使用一对多关系时,如何正确展示“多”表中的结果?
这是我目前使用的代码。
//connect to database with self made db class object.
$db = new db();
$db = $db->connect();
$smtp = $db->prepare('select ID, title, description, genre from movie NATURAL JOIN movie_genres WHERE date >= ? AND date < ?');
$smtp->bind_param('ss', $seasonStart, $seasonEnd); //variables defined based on current date.
$smtp->execute();
$smtp->bind_result($ID, $title,$description, $genre));
while($smtp->fetch()) {
echo '
<div class="upcoming">
<div id="upcomingPoster" style="background-image: url(images/' . $ID . '.jpeg)">
<div>
<a href="">' . $title . '</a>
</div>
</div>
<div class="upcomingInfo">
<h2>Description</h2>
<p class="upcomingInfoDescription">' . $description .'</p>
<div></div>
<p>' . $genre . '</p>
</div>
</div>';
}
现在,当使用它时,我的代码基本上循环每一行。但我试图将所有类型放在一起,然后再循环到下一部电影。
【问题讨论】:
-
你能分享你的尝试吗?
-
还有您正在使用的查询,请在使用时。
-
也许你正在搜索array_merge() php.net/manual/es/function.array-merge.php
-
通常不是 PHP 必须处理它,您在 SQL 查询中使用
JOIN,MySQL 会为您提供及时关联的结果。这就是使用 DBMS 的全部意义所在,这样您就不必自己编写代码了。