0

I am trying to make a page that displays articles in a database but it is to be organised in by category.

The categories are stored in a table categories with id and category as its fields/ The articles are stored in a table articles with its different fields for various information about the article.

The code I have:

<?php

$sql = "SELECT * FROM `categories`";
$query = mysql_query($sql) or die("Could not get CATEGORIES ".mysql_error());

while($category = mysql_fetch_array($query)){

$cat = $category['category'];

$sql = "SELECT * FROM `articles` WHERE `category` = '$cat'";
$query = mysql_query($sql) or die(mysql_error());
$articles = mysql_fetch_array($query);

$size = count($articles);

echo $size;

}   

?>

Results that I expect are a list of each category, then underneath each category, the number of articles with that category.

Some help would be much appreciated.

Thanks :D

4

2 回答 2

1

我认为你想做的事情可以更容易和更高效地完成:

<?php
$sql = "SELECT categories.name, COUNT(articles.id) AS cnt
    FROM categories
    LEFT JOIN articles ON articles.category=categories.category";
$query = mysql_query($sql);
while ($category = mysql_fetch_assoc($query)) {
    echo $category['name'].' - '.$category['cnt'];
}
?>

(当然我不知道你的表结构并且不得不猜测字段名称,但它应该让你了解它是如何工作的)。关于 JOIN,您应该阅读MYSQL 文档

于 2012-07-22T16:05:08.040 回答
1

试试这个……也许这就是你要找的。我们也可以使用单个 mysql 查询找到相同的结果。

$sql = "SELECT * FROM `categories`";
$query = mysql_query($sql) or die("Could not get CATEGORIES ".mysql_error());

$result = array();
while($category = mysql_fetch_array($query)){

$cat = $category['category'];

$sql = "SELECT count(*) as numberOfArticles FROM `articles` WHERE `category` = '$cat'";
$query2 = mysql_query($sql) or die(mysql_error());

$articles = mysql_fetch_array($query2);
$category['numberOfArticles'] = $articles['numberOfArticles'];
$result[] = $category;

}   

print_r($result);
于 2012-07-22T16:07:16.547 回答