00 Votes

PHP/MySQL: How can I save the output values of $result['COUNT(id)']?

Question by Guest | 2014-02-14 at 08:22

I would like to output the number of data rows belonging to different groups from my database.

For this, I am doing a "COUNT(id)" query combined with a "GROUP BY" like this:

$query = "SELECT COUNT(id) FROM tab GROUP BY col";

mysql_select_db('db');

$result = mysql_query($query) or die(mysql_error());

while($result = mysql_fetch_assoc($result)) {
  echo $result['COUNT(id)'];
  echo "/n";
}

Unfortunately, the output is resulting in an error. How can I save the output values from "COUNT(id)"?

ReplyPositiveNegativeDateVotes
00 Votes

Just try the following instead:

$query = "SELECT COUNT(id) as c FROM tab GROUP BY col";
 
mysql_select_db('db');
 
$result = mysql_query($query) or die(mysql_error());
 
while($row = mysql_fetch_assoc($result)) {
  echo $row["c"];
  echo "/n";
}

You cannot set $result to another value at the same time you are still retrieving values from $result. Just use another variable like $row instead.

On the other hand it is better to use "COUNT(id) as c", so that you have stored the values in "c".
2014-03-11 at 13:02

ReplyPositive Negative
00 Votes

Why not try the following approach:

$query = "SELECT COUNT(id) FROM tab GROUP BY col";
 
mysql_select_db('db');
 
$result = mysql_query($query) or die(mysql_error());
 
while(list($c) = mysql_fetch_row($result)) {
  echo $c;
  echo "/n";
}

With using list($c) and mysql_fetch_row you do not have the problems arising from the associated array construct.

The function mysql_fetch_row retrieves data row for data row from the result and stores the values of the fields in an array. With list(), you can easily store the array values in variables so that you can easily use them in your script. If you have several fields in your table, you can use list() like list($x, $y, $z) for 3 fields, for example.
2014-03-19 at 13:45

ReplyPositive Negative
Reply

Related Topics

PHP: Current Date and Time

Tutorial | 0 Comments

PHP: Upload of large Files

Tutorial | 0 Comments

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.

Participate

Ask your own question or write your own article on askingbox.com. That’s how it’s done.