如何让这个简单的块更短更好?

时间:2011-07-02 13:25:32

标签: php mysql

我正在使用以下没有深思熟虑的代码块来检索类别及其主题。

$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>';
    }

}

以上就是诀窍。我知道这不是最实际的,这就是我问小组的原因。

我怎样才能更好地做到这一点,这样更实用,更简单?

2 个答案:

答案 0 :(得分:1)

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 */
}

答案 1 :(得分:0)

只需使用一个连接两个表的查询。

$query = "SELECT categories.name AS category_name, topics.name AS topic_name
          FROM categories JOIN topics ON categories.id = topics.fkid
          ORDER BY categories.name ASC, topics.name ASC";

$resultSet = mysql_query($query);

$currentCategory = "";
while ($cRecord = mysql_fetch_assoc($resultSet)) {
    if ($currentCategory != $cRecord['category_name']) {
        $currentCategory = $cRecord['category_name'];
        echo "<h2>" . $currentCategory . "</h2>";
    }

    echo $cRecord['topic_name'] . "<br/>";
}

mysql_close($resultSet);