更新时间:2022-12-09 15:11:16
作为我第一个回答的后续,下面的示例展示了如何使用单个查询来完成此操作.恕我直言,您应该始终选择这种方法.如果您只有少数几个类别要钻取,如果您坚持使用查询嵌套在循环内的方法,则性能消耗可能不会太大.但如果您有大量类别,下面的方法应该会更有效:
As a follow-up to my first answer, the example below shows how you can do this with a single query. IMHO, you should always opt for this approach. If you only have a handful of categories to drill into, it may not be much of a performance drain if you stick with the query-nested-inside-a-loop approach. But if you have a sizable number of categories, the approach below should be significantly more efficient:
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>";