I want to count all the rows and at the same time list them as I usually do, using mysql_fetch_object. I thought I’d do something like this;
$total = mysql_query("SELECT *, COUNT(*) AS totalfound FROM img WHERE state='0'");
But I can’t seem to wrap my head around how to get the values out – I just get the first item in the table when I run this;
while ($record = mysql_fetch_object($total)) { echo $record->id; }
If I want to get the totalfound I could do this;
$result = mysql_fetch_assoc($total);
$count = $result['totalfound'];
…but then I can’t get the rest. I know I’m thinking wrong but can’t seem to get it to work. Can you guys please help me out? Thanks!
Once thing I forgot to mention: mysql_num_rows is too slow, I was thinking of using count(*) instead. As an example, mysql_num_rows on the entire table takes everything from 3 to 9 seconds, and a count(*) always takes 0.6 seconds, getting the same results.
A
countis an aggregate function, you cannot select both rows and aggregates without usinggroup by. MySQL will let you do it without thegroup by, and will produce unpredictable results.Just use the query without
countto get the rows, and usemysql_num_rows()on the result.Edit: If
mysql_num_rows()is slow, you must be returning a lot of rows. You’d then better execute two queries, one simplyselect count(*) as numrows ..., and one to retreive your data.Try to add proper indexes and the
count(*)will execute within a few miliseconds.You really don’t want this in one query. Every row will then have a column that states how many rows there are, which is unrelated to that row.