我在尝试在while循环中创建while循环时遇到了很大的麻烦。第一个while循环应该输出类别。第二个while循环应该输出与类别关联的链接。链接信息在链接表中,类别信息在类别表中。我正在尝试在category.ID的links.catID上进行JOIN。
链接表:
id链接url catID类型
类别表:
id猫类型
links.catID应该等于int中的category.id。然后category.cat将输出类别的名称。
我的代码是:
require 'db/connect.php';
$sql = "SELECT * FROM category";
$results = $db->query($sql);
echo "<p class='post-footer align-left'><span class='pageName'><span
class='style3'>Links</span></span></p>";
if($results->num_rows){
while($row = $results->fetch_object()){
echo "<table width='507' border='1'>";
echo " <p class='post-footer align-left'><span class='pageName'><span class='style3'>{$row->cat}</span></span></p>";
$sql1 = "SELECT links.url, links.links, links.catID FROM links INNER JOIN category on category.id WHERE category.id = links.catID";
$results1 = $db->query($sql1);
if ($results1->num_rows > 0) {
while($row1 = $results1->fetch_object()){
echo "<th><span class='pageName'><span class='style3'>{$row1->links}</span></span></th>";
}
}
}
}
请对我好一点,我经验很少,上面很可能表明了这一点。我已经坚持了一段时间,只是想不通。我真的很感谢某人的帮助。
我想我已经在上面正确解释了:)
不用担心PHP的CSS。CSS很容易修复。只需要列出具有正确类别的正确链接。
作为我的第一个答案的后续操作,以下示例显示了如何使用单个查询即可完成此操作。恕我直言,您应该始终选择这种方法。如果您只有少数几类可以钻取,那么坚持使用“查询嵌套内部循环”方法可能不会浪费很多性能。但是,如果您有相当多的类别,则下面的方法应该会大大提高效率:
require 'db/connect.php';
$sql = "
SELECT
category.id
, links.links
FROM
category
LEFT JOIN
links ON links.catID = category.id
ORDER BY
category.id ASC
-- this ORDER BY is critical, it ensures that all of the
-- records will be lumped by category
";
// (yes, this query will create multiple rows for every category, but that's OK,
// we're going to deal with that in the while() loop
$results = $db->query($sql);
echo "<p class='post-footer align-left'><span class='pageName'><span class='style3'>Links</span></span></p>";
if($results->num_rows){
$previousId = '';
while($row = $results->fetch_object()){
$currentId = $row->id;
if ($currentId !== $previousId) {
// we only show the wrapper <table>, and the category header, if we've encountered a new
// batch of rows which signifies that a new category is being processed
echo "<table width='507' border='1'>";
echo " <p class='post-footer align-left'><span class='pageName'><span class='style3'>{$row->cat}</span></span></p>";
}
echo "<th><span class='pageName'><span class='style3'>{$row->links}</span></span></th>";
if ($currentId !== $previousId and $previousId !== '') {
echo "</table>"; // this wasn't in your original code, but I assume it should be here
}
$previousId = $currentId;
}
}
echo "</table>";
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句