Forum Moderators: coopster

Message Too Old, No Replies

Dumb php MySql question

printing results of a COUNT

         

ukgimp

3:52 pm on Nov 21, 2002 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Sorry to ask this but it is causing me greif. I cannot get the results of a simple COUNT working

$sqly = "SELECT COUNT(*) FROM blah WHERE blah = $blah";
$yResult=mysql_query( $sqly , $db_connection );

Now when I try to echo the yResult I get the followign type of error:

Resource id #3

and not the count. I know this is simple but it is baffling me. I can get the number if I do a select and then count rows but that seems a bad way of doint it.

Regards

andreasfriedrich

4:22 pm on Nov 21, 2002 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



As always with a select query mysql_query [php.net] returns a resource identifier or FALSE if the query was not executed correctly.

To retrieve the count just retrieve the first and only row returned by the query with any of the mysql_fetch_* methods.

Andreas

ukgimp

4:59 pm on Nov 21, 2002 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Thanks for that Andreas (not 100% with the concept yet but getting there)

I have further query related to efficiency of code. Say I wish to print a list of subjects and I want to print a count for each record that has the related subject. The way I do it now is to loop the sql that is required to count and echo the number. This works but I need to know if this is the best way. It seems wasteful in that I make and break multiple db connections and run the SQL multiple times.

Could I do this with a group by.

Regards

aaronc

6:25 pm on Nov 21, 2002 (gmt 0)

10+ Year Member



I think maybe this is what you're looking for.

SELECT subject, count(*) AS total FROM tablename WHERE match = 'value' GROUP BY subject

This will return.

subject - total
subject1 - 20
subject2 - 35
subject3 - 4
etc..