downloads | documentation | faq | getting help | mailing lists | reporting bugs | sites | links | conferences | my

search for in the

mysql_pconnect> <mysql_num_fields
Last updated: Wed, 28 Mar 2007

view this page in


(PHP 4, PHP 5, PECL mysql:1.0)

mysql_num_rows — Get number of rows in result


int mysql_num_rows ( resource $result )

Retrieves the number of rows from a result set. This command is only valid for statements like SELECT or SHOW that return an actual result set. To retrieve the number of rows affected by a INSERT, UPDATE, REPLACE or DELETE query, use mysql_affected_rows().



The result resource that is being evaluated. This result comes from a call to mysql_query().

Return Values

The number of rows in a result set on success, or FALSE on failure.


Example 1373. mysql_num_rows() example


= mysql_connect("localhost", "mysql_user", "mysql_password");
mysql_select_db("database", $link);

$result = mysql_query("SELECT * FROM table1", $link);
$num_rows = mysql_num_rows($result);

"$num_rows Rows\n";



Note: If you use mysql_unbuffered_query(), mysql_num_rows() will not return the correct value until all the rows in the result set have been retrieved.

Note: For downward compatibility, the following deprecated alias may be used: mysql_numrows()

See Also


add a note add a note User Contributed Notes
eriline dot mees at mail dot ee
27-Dec-2005 08:28
If you have a problem using:
    $res1=mysql_query("select SQL_CALC_FOUND_ROWS * from minutabel LIMIT 20");
    $res2=mysql_query("select FOUND_ROWS()");
($res2 got always "0")
then be sure the php.ini config option "mysql.trace_mode" is "Off".

You can use
    // do your $res1 and $res2 queries.
for temporary disabling.
08-Dec-2005 01:55
A small tip concerning SQL_CALC_FOUND_ROWS and FOUND_ROWS()

Remember that you can us "AS" when working with mysql_fetch_assoc.

        FOUND_ROWS() AS `found_rows`;
$result = mysql_query($sql);
$myrow = mysql_fetch_assoc($result);
$row_count = $myrow['found_rows'];

echo $row_count;
mancini at nextcode dot org
14-Nov-2005 01:24
here is a really fast mysql_num_rows alternative that makes use of the SELECT FOUND_ROWS() MySQL function , it only reads a single row and it is really helpfull if you are counting multiple tables with thousands of rows

function get_rows ($table) {
$temp = mysql_query("SELECT SQL_CALC_FOUND_ROWS * FROM $table LIMIT 1");
$result = mysql_query("SELECT FOUND_ROWS()");
$total = mysql_fetch_row($result);
simon_nuttall at hotmail dot com
12-Nov-2005 07:36
Object oriented version of wil1488 at gmail dot com's comment for counting table rows:
= $mysqli->query("SELECT COUNT(*) as TOTALFOUND from table");
jonbendi @t stud o ntnu o no
07-Nov-2005 06:16
I find that mysql_num_rows() overlook LIMIT clauses.
For instance:

//table has 700 rows
$command = "SELECT * FROM table LIMIT 500";
$q = mysql_query($command);
$rows = mysql_num_rows($q);

//$rows is 700
thismelancholy at ilovebubbles dot net
29-Sep-2005 03:27
I�ve noticed that on some servers one need to put "or die(mysql_error())" when you use mysql_num_rows(), or else it will throw an error. :S
Rancid m+m
30-Jun-2005 07:58
In PHP 5, mysql_affected_rows looks for the link as the first parameter, not a MySQL result.
wil1488 at gmail dot com
31-May-2005 07:53
To use SQL COUNT function, without select the source...

see an example:


$my_table = mysql_query("SELECT COUNT(*) as TOTALFOUND from table", $link); //EXECUTE SQL CODE
Note: will return the total on TOTALFOUND

print (mysql_result($my_table,0,"TOTALFOUND")); //use the field camp to get the total from your SQL query!

Thanks, good luck.
jsirovic AT g male dot com
19-May-2005 08:34
The reason it's just as slow is that to count that way as it is to fetch, minus the data transfer.

Even when executing a limit query, when you ask it to fetch the number of total rows, it must scan the whole table every time to calculate the count.
alex dot feinberg 4t gm41l
28-Apr-2005 03:56
Re dzver at abv dot bg's note...

I just ran some tests using MySQL Super Smack. Surprisingly, a SELECT * followed by a SELECT COUNT(*) actually was close in speed to a SELECT SQL_CALC_FOUND_ROWS * followed by a SELECT FOUND_ROWS(), but the SQL_CALC_FOUND_ROWS solution was still a bit faster.

Perhaps it varies by table structure? Either way, it might be worth checking which is faster for your application.
liamvictor at gmail dot com
13-Apr-2005 05:22
// this works properly
$query = "SELECT first_name FROM users_tbl WHERE user_id='$user_id' AND password = '$p0' ";
$result = mysql_query($query, $connection) or die ("<p class=err>Error - Query failed: ".mysql_error()."</p>");
$num_rows = mysql_num_rows($result);
if ($num_rows){
    while ($myrow = mysql_fetch_row($result)){
        $first_name = $myrow[0];
        print ("<p>Line:".__LINE__." num_rows:$num_rows first_name:$first_name <br> $query</p>");
    print ("<p>Password error.</p>");

// Here 1 row is returned with a value of 0 when the password is wrong rather than reporting the password error.
$query = "SELECT COUNT(first_name) FROM users_tbl WHERE user_id='$user_id' AND password = '$p0' ";
$result = mysql_query($query, $connection) or die ("<p class=err>Error - Query failed: ".mysql_error()."</p>");
$num_rows = mysql_num_rows($result);
if ($num_rows){
    while ($myrow = mysql_fetch_row($result)){
        $count_first_name = $myrow[0];
        print ("<p>Line:".__LINE__." num_rows:$num_rows count:$count_first_name <br> $query</p>");
    print ("<p>Password error.</p>");
dzver at abv dot bg
20-Feb-2005 05:00
It is faster to run second query "select count(...) from ... ", than adding SQL_CALC_FOUND_ROWS to your first query, and then using select FOUND_ROWS() + mysql_num_rows().
29-Jan-2005 05:18
In response to oran at trifeed dot com:

You are only experiencing this behaviour because you have not given your FOUND_ROWS() result an alias:

$qry = mysql_query ( 'SELECT FOUND_ROWS() AS total' );
$rst = mysql_fetch_array ( $qry, MYSQL_ASSOC );
echo $rst['total'];

Sean :)
oran at trifeed dot com
15-Dec-2004 09:06
For me


Only worked with the following syntax:
$result = @mysql_query($query);
$resultTotal = @mysql_query("SELECT FOUND_ROWS()");
$res=    mysql_fetch_array($resultTotal);
echo $res['FOUND_ROWS()'];

hope it helped

pjoe444 at yahoo dot com
18-Nov-2004 03:38
Re my last entry:

This seems the best workaround to get an 'ordinary' loop going, with possibility of altering output according to row number
(eg laying out a schedule)


for ($i=0; $i<mysql_num_rows($result); $i++) {
$row = mysql_fetch_assoc($result);

print "<div class=\"showing\">";
print "<b>".$row['timeon']."-".$row['timeoff']."</b> ".$row['event']."<br />;
if ($i!=$rowno-1) {
    print "other-html-within-sched-here</div>";
else print "end-last-entry-html-here</div>";
}  //close loop
pjoe444 at yahoo dot com
18-Nov-2004 02:24
A pity there seems no way of getting the CURRENT  row number that's under iteration in a typical loop,
such as:
while ($row = mysql_fetch_assoc($result)) { }

After all there is an array of row arrays, as signified by

Say this gives "40 rows" : it would be useful to know when the iteration is on row 39.

The nearest seems to be "data seek":but it connects directly to a
row number eg (from mysql_data_seek page)

for ($i = mysql_num_rows($result) - 1; $i >= 0; $i--) {
   if (!mysql_data_seek($result, $i)) {
       echo "Cannot seek to row $i: " . mysql_error() . "\n";

= it still wouldn't solve knowing what row number you're on in an ordinary loop.

One reason for this situation is the php fetch (fetch-a-single-row) construction, without any reasonable FOR loop possibility with row numbers.

$Rows[$i] possibility where
$i would be the row number

$Rows[$row[], $row[], $row[].....]
             0            1            2     etc

-- the excellent retrieval WITHIN a row ( $row[$i] ),
while certainly more important,  is not matched by
similar possibilities for rows themselves.

and Count($result) doesnt work of course, $result being a
mere ticket-identifier...

Peter T
They call me .. "Blaqy"
08-Nov-2004 07:30
Just wanted to add my 2 cents in regards to the mysql functions:

It was difficult finding any information on PHP usage.
What wasn't (or currently isn't) mentioned is that:

$query = "SELECT FOUND_ROWS()";

Will return a 'recordset' .. that holds the 'number of rows', not the actual value.  So the correct usage is:

$result = mysql_query($query);
$total_records = mysql_result($result, 0);

$total_records = mysql_query($query);

As some of the literature .. may suggest to you.
sam at liddicott dot com
04-Nov-2004 05:40
Some user comments on this page, and some resources including the FAQ at : suggest using count(*) to count the number of rows

This is not a particularly universal solution, and those who read these comments on this page should also be aware that

select count(*) may not give correct results if you are using "group by" or "having" in your query, as count(*) is an agregate function and resets eachtime a group-by column changes.

select sum(..) ... left join .. group by ... having ...

can be an alternative to sub-selects in mysql 3, and such queries cannot have the select fields replaced by count(*) to give good results, it just doesn't work.

aaronp123 att yahoo dott comm
21-Feb-2003 05:40
I may indeed be the only one ever to encounter this - however if you have a myisam table with one row, and you search with valid table and column name for a result where you might expect 0 rows, you will not get 0, you will get 1, which is the myisam optimised response when a table has 0 or one rows.  Under "5.2.4 How MySQL Optimises WHERE Clauses" it reads:

*Early detection of invalid constant expressions. MySQL quickly detects that some SELECT statements are impossible and returns no rows.


*All constant tables are read first, before any other tables in the query. A constant table is:
1) An empty table or a table with 1 row.
2) A table that is used with a WHERE clause on a UNIQUE index, or a PRIMARY KEY, where all index parts are used with constant expressions and the index parts are defined as NOT NULL.

Hopefully this will keep someone from staying up all night with 1146 errors, unless I am completely mistaken in thinking I have this figured out.
webmaster at _NOSPAM_elite-gaming dot com
10-Oct-2002 07:48
The fastest way to get the number of rows in a table is doing this:

$total = mysql_result(mysql_query("SELECT COUNT(id) FROM yourtable"),0);

As long as there are no NULL ids (shouldnt be), it will return the correct rows extremely fast.  If you already used yourtable though, it is faster to use mysql_num_rows() on the result of it.
tac at smokescreen dot org
13-Jan-2002 11:58
MySQL 4.0 supports a fabulous new feature that allows you to get the number of rows that would have been returned if the query did not have a LIMIT clause.  To use it, you need to add SQL_CALC_FOUND_ROWS to the query, e.g.

$sql = "Select SQL_CALC_FOUND_ROWS * from table where state='CA' limit 50";
$result = mysql_query($sql);

$sql = "Select FOUND_ROWS()";
$count_result = mysql_query($sql);

You now have the total number of rows in table that match the criteria.  This is great for knowing the total number of records when browsing through a list.
philip at cornado dot c()m
06-May-2001 11:37
Regarding SQL count(), see this faq :
Note: If you already have a $result, use mysql_num_rows() on it otherwise use SQL count().  Don't SELECT data just for a count.

mysql_pconnect> <mysql_num_fields
Last updated: Wed, 28 Mar 2007
show source | credits | sitemap | contact | advertising | mirror sites