Bickey Posted January 28, 2011 Share Posted January 28, 2011 How to write the code to get the count of the word "CHECKED" from a row? I tried this and it's not working. Please help. $query = mysql_query("SELECT field1, field2, field3, COUNT(CHECKED) as counter FROM db1 WHERE row_name = 'science'"); while($line = mysql_fetch_array($query)) { echo $query['counter']; } Quote Link to comment Share on other sites More sharing options...
Psycho Posted January 28, 2011 Share Posted January 28, 2011 COUNT() only works if you use GROUP BY. Can't tell from your current query what the GROUP BY clause should be. Quote Link to comment Share on other sites More sharing options...
Bickey Posted January 28, 2011 Author Share Posted January 28, 2011 ok, looking at the table below, can someone tell me how to get the count of "MAX" in row 1? id field1 field2 field3 field4 1 MAX MIN MAX MAX 2 MIN MIN MIN MAX Quote Link to comment Share on other sites More sharing options...
Psycho Posted January 28, 2011 Share Posted January 28, 2011 SELECT COUNT(field1) as field1MaxCount FROM table WHERE field1 = 'MAX' GROUP BY field1 Quote Link to comment Share on other sites More sharing options...
codefossa Posted January 28, 2011 Share Posted January 28, 2011 <?php $result = mysql_query("SELECT * FROM `table` WHERE `field1` = 'MAX';"); $count = mysql_num_rows($result); mysql_free_result($result); ?> Quote Link to comment Share on other sites More sharing options...
Psycho Posted January 28, 2011 Share Posted January 28, 2011 <?php $result = mysql_query("SELECT * FROM `table` WHERE `field1` = 'MAX';"); $count = mysql_num_rows($result); mysql_free_result($result); ?> There's no need to run a query to return back a large result set just to count the records. That is a waste of server resources. That is what COUNT() in queries is for. Quote Link to comment Share on other sites More sharing options...
Pikachu2000 Posted January 28, 2011 Share Posted January 28, 2011 I think what the OP wants is to count the number of times 'MAX' occurs in a particular record. Quote Link to comment Share on other sites More sharing options...
Psycho Posted January 28, 2011 Share Posted January 28, 2011 I think what the OP wants is to count the number of times 'MAX' occurs in a particular record. You're right. He did say How to write the code to get the count of the word "CHECKED" from a row? I totally missed that. That is actually very simple: SELECT ( IF(field1='CHECKED', 1, 0) + IF(field2='CHECKED', 1, 0) + IF(field3='CHECKED', 1, 0)) as counter FROM db1 WHERE row_name = 'science' Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.