I have two tables in my database.
cat – catid, catname
articles – id, catid, content
so what i want to display is category name (catname) and how many articles are there in that category.
This is my code but it dosent work.
$query = "SELECT cat.cname, COUNT(articles.cat_id)".
"FROM cat, articles ".
"GROUP BY cat_id";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
echo $row['cname']. " - ". $row['COUNT(cat_id)'];
echo "<br />";
}
Any help will be most aprriceated. thanks.
So this is a 1:many relationship. i.e. 1 Category -> Many articles.
The best way to do this is to create a third table, an adjacency list.
Keep your ‘category_id’ and ‘article_id’ unique in tables ‘cat’ and ‘article’.
In your third table you define the 1 : many relationships.
Now join the tables:
This takes the adjacency table, preserves it’s format(due to left join) and appends the tables
articleandcategoryto it, giving you a categorised table of all your articles. You can now usemysql_fetch_array()to get your results.Edit: reference first comment, displaying number of rows
You can either, as you have done, use SQL’s function
COUNTto return a count of a specific column.Or, with PHP, run the query, and then use
mysql_num_rows($result)to return the number of rows SQL has in its buffer.Alternatively, retrieve results using
mysql_fetch_array($result)and usecountto return the number of paired values in the array.