user1015214
user1015214

Reputation: 3091

getting number of rows in sql result in php

Is there a way to write php code to give you the amount of rows in a sql query (and print the number on the screen) without having to make an actual loop through each row and adding up the numbers?

Upvotes: 0

Views: 130

Answers (3)

Fabrizio
Fabrizio

Reputation: 3776

multiple ways:

SELECT COUNT(*) `tot` FROM table

(attention, not COUNT(field), as if field is NULL the row won't be counted)

of, if you have already queried the database and you want to know all the rows that you have pulled, let's say inside an array, you could do a

count($array)

if you haven't looped the values but planning on it, you could execute a mysql_num_rows

and finally, if you executed a SELECT with LIMIT in it, you could run add SQL_CALC_FOUND_ROWS to the select and then use the FOUND_ROWS()

SELECT SQL_CALC_FOUND_ROWS * FROM table WHERE field="value" LIMIT 0,100; /* grab first 100 rows WHERE field="value" */
SELECT FOUND_ROWS();  /* return the total number of rows WHERE field="value" */

Upvotes: 0

Corbin
Corbin

Reputation: 33467

It sounds like you're looking for COUNT?

SELECT COUNT(id) as number_users FROM users

Then it's treated like a normal resource where you can pull out the row and number_users column.

Edit: Your question a is a bit oddly worded. It also sounds like you might be looking for SUM() and GROUP BY. Or maybe COUNT() and GROUP BY.

Upvotes: 1

NCode
NCode

Reputation: 2808

For MySQL its mysql_num_rows:

http://www.php.net/manual/en/function.mysql-num-rows.php

Upvotes: 0

Related Questions