11 April 2010

Display number of items in category / subcategory

In many cases, one might want to display the number of items found in a category / subcategory. This is specially the case for classifieds websites.

For example,

Vehicles (30)
  • Cars  (15)
  • Bikes (13)
  • Other (2)

This can be done by querying the database. In this case, I am using MySQL.

Let’s assume that we are passing the category id in the URL. So,
  1. Get the category id from the URL
  2. $cat = mysql_real_escape_string($_GET['category']);
  3. Query the database with that id
  4. $query = 'SELECT COUNT(*) as count FROM vehicles WHERE catId = '$cat'";
  5. Build the query
  6. $result = mysql_query($query);
  7. Get the resulting row
  8. $row = mysql_fetch_array($result);
  9.  Finally, get the count field from the resulting row (this is the data we want)
  10. $num_items_in_category = $row['count'];
Your comments are welcomed.

No comments:

Post a Comment