开发者

How can I make this simple block shorter and better?

I'm using the following not well thought code block to retrieve categories and it's topics.

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

}

The above 开发者_JAVA技巧does the trick. I know this is not the most practical and this being the reason I ask the group.

How can I better this so it's more practical and simple?


A classical case for a JOIN:

SELECT * FROM categories JOIN topics ON categories.id = topic.fkid ORDER BY categories.name;

Then to print, we only print the header if it has changed (thanks, Rajasur!):

$catname = "";
while ($out = mysql_fetch_assoc($result))
{
  if ($out["name"] != $catname) // maybe need strcmp here
  {
    $catname = $out["name"];
    print($catname)
  }
  /* print the rest */
}


Just use a single query that joins the two tables.

$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);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜