Jump to content

Recommended Posts

Im trying to while loop my categories with another table called product so multiple table.

 

I wanted to display my categories like the following:

 

cat1 (658)

cat2 (556)

etc

 

Here is the select clause im using, but it only seems to display the category name???

 

$numprodscat ="SELECT pcatid,pcatname,

  (SELECT COUNT(*) FROM product WHERE parents_id = c.pcatid) as 'count'

FROM parent_cats AS c";

 

thanks

Link to comment
https://forums.phpfreaks.com/topic/141922-cateories-with-number-of-rows/
Share on other sites

Ok i have this:

 

$numprodscat="select cats.pcatid,cats.pcatname,

  (select count(*) from product as nums where nums.parents_id = cats.pcatid)

FROM parent_cats as cats";

 

How do i display the count of the product of that category in my php script, ive tryed  mysql_num_row() but that just displays the number of parent categories i have....

 

thanks

I strongly believe what you are trying to do can not be done with a subquery because count(*) only returns one row and you need more than one row of data.  This would be far better as separate queries.

 

#not tested

$results = mysql_query('select pcatid,pcatname from parent_cats');
while($row = mysql_fetch_row($results))
{
  $r2 = mysql_query('select count(*) from products where parents_id = "$row[0]";');
  $num = mysql_result($r2,0,'count(*)');
    echo $row[1] . '('. $num .') <br />';
}

mysql_free_result($results);
mysql_free_result($r2);

 

I strongly believe what you are trying to do can not be done with a subquery because count(*) only returns one row and you need more than one row of data.  This would be far better as separate queries.

COUNT() return a single value, not a single row -- try this:

 

SELECT c.pcatid,c.pcatname, p.cnt
FROM parent_cats AS c
INNER JOIN 
( SELECT parents_id, COUNT(*) AS cnt FROM product GROUP BY parents_id ) AS p ON ( p.parents_id = c.pcatid )

 

 

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.