我正在使用以下未经深思熟虑的代码块来检索类别及其主题。
$query1 = "SELECT * from categories";
$result = mysql_query($query1);
while ($out = mysql_fetch_assoc($result)){
//category
print '<h2>' . $out['name'] . '</h2>';
$query2 = "SELECT * from topics where fkid = $out[id]";
$result2 = mysql_query($query2);
while($top = mysql_fetch_assoc($result2)){
//topic
print $top['name'] . '<br>';
}
}
上面的技巧。我知道这不是最实用的,这就是我问这个小组的原因。
我怎样才能改进它,让它更实用、更简单?
最佳答案
JOIN 的经典案例:
SELECT * FROM categories JOIN topics ON categories.id = topic.fkid ORDER BY categories.name;
然后要打印,我们只打印标题是否已更改(感谢 Rajasur!):
$catname = "";
while ($out = mysql_fetch_assoc($result))
{
if ($out["name"] != $catname) // maybe need strcmp here
{
$catname = $out["name"];
print($catname)
}
/* print the rest */
}
关于php - 我怎样才能使这个简单的 block 更短更好?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6557277/