1

I have this query for counting the number of items in a category:

SELECT category, COUNT(*) AS category_count FROM users GROUP BY category

Which creates results looking like:

category   category_count
========== ================
X          3
Y          2

Now, In PHP I want to display the counts of the categories. For example, I might want to echo the count from category X, how would I do it?

Thanks in advance

6 Answers 6

2

Assuming $result holds the result of your query:

while ($row = mysql_fetch_array($result))
{
    echo 'Category: ' . $row['category'];
    if ($row['category'] == 'X')
    {
       echo  ' Count: ' . $row['category_count'];
    }
    echo '<br/>';
}
Sign up to request clarification or add additional context in comments.

2 Comments

I'm wanting to only display the count where category = x, this is going to display all the counts.
Check my edit and you should really catch up with the basics first
0
$res = mysql_query("SELECT category, COUNT(*) AS category_count FROM users GROUP BY category");
while($row = mysql_fetch_assoc($res)){
   echo $row['category'].": ".$row['category_count']."<br/>";
}

Comments

0
$result = mysql_query("SELECT category, COUNT(*) AS category_count FROM users GROUP BY     category");

while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
{
   if ( $row['category'] == 'x' )
   {
      echo $row['category_count'];
   }
}

Comments

0
while ($row = mysql_fetch_array($result))
{
    echo 'Category: ' . $row['category'] . ' Count:' . $row['category_count'];
    echo "<br>";
}

Comments

0

It would be better if you use the where clause in your query.

SELECT COUNT(*) AS category_count FROM users WHERE category = 'x'

Comments

0
$conn = mysql_connect("address","login","pas s");
mysql_select_db("database", $conn);

$Var = mysql_query("query");

While ($row = mysql_fetch_assoc($var) {   echo $var["column"] }.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.