Count in sql and php

mysql_num_rows

This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide. Alternatives to this function include:

Description

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() .

Parameters

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.

Examples

Example #1 mysql_num_rows() example

$link = 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 );

Notes

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 backward compatibility, the following deprecated alias may be used: mysql_numrows()

See Also

  • mysql_affected_rows() — Get number of affected rows in previous MySQL operation
  • mysql_connect() — Open a connection to a MySQL Server
  • mysql_data_seek() — Move internal result pointer
  • mysql_select_db() — Select a MySQL database
  • mysql_query() — Send a MySQL query

User Contributed Notes 22 notes

Some user comments on this page, and some resources including the FAQ at :

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.

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)

print «

print ««.$row[‘timeon’].»-«.$row[‘timeoff’].» «.$row[‘event’].»
;
if ($i!=$rowno-1) print «other-html-within-sched-here

«;
>
else print «end-last-entry-html-here

«;
> //close loop

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.

In Reply to the last post: This may not always work correctly, as $object->doesExist would contain a result, not a boolean value. A better way (using the same method) would be using a cast:

class Object var $doesExist = false ;

[. ]
function load () $result = mysql_query ( ‘. ‘ );
$this -> doesExist = (bool) ( $res = mysql_fetch_array ( $result ))
[. ]
>
>
?>

Regarding SQL count(), see this faq :
* http://www.faqts.com/knowledge_base/view.phtml/aid/114/fid/12
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.

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’];

A note on the following usage; that suggest to use several MySQL Functions to get the number of Table Records.

You may be familiar with following:

$sqlQuery = ‘Select SQL_CALC_FOUND_ROWS `MyField` From `MyTable` Limit 1;’ ;

$sqlQuery_1 = ‘Select FOUND_ROWS( );’ ;

?>

I omitted the actual connection to MySQL and the execution of the query, but you get the idea.

I did some tests and on a fairly high traffic web site, one that executes several queries quite often and found that using this combination of MySQL Functions can actually result in wrong results.

For example, assume I have two queries to get the number of Table Records in two different Tables. So in essence, we are executing 4 queries ( 2 queries for each Table ).

If two different requests come in through PHP, your going to run into problems. Note than when I mean request, I mean two different clients requesting your PHP page.

Execute: SQL_CALC_FOUND_ROWS On Table 1

Execute: SQL_CALC_FOUND_ROWS On Table 2

Execute: Select FOUND_ROWS( )

At this point, you see the race condition that occurred. While Request 1 was being executed, Request 2 came in.

At this point Request 1 will return the number of Table Records in Table 2 and not Table 1 as expected!

Why? Because MySQL does not differ between requests. Each query is in a queue waiting its turn. As soon as its turn comes in it will be executed my MySQL.

The MySQL Function Select FOUND_ROWS( ) will return the result of the last SQL_CALC_FOUND_ROWS!

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().

SELECT SQL_CALC_FOUND_ROWS together with
SELECT FOUND_ROWS()

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()’];

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.

To use SQL COUNT function, without select the source.

//MAKE THE CONNECTION WITH DATABASE

$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!
?>

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
mysql_num_rows($result):

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»;
continue;
>

= 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.

Suggestion:
$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.

In preventing the race condition for the SQL_CALC_FOUND_ROWS and FOUND_ROWS() operations, it can become complicated and somewhat kludgy to include the FOUND_ROWS() result in the actual result set, especially for complex queries and/or result ordering. The query gets more complex, you may have trouble isolating/excluding the FOUND_ROWS() result, and mysql_num_rows() will return the number of actual results + 1, all of which makes your code messier and harder to read. However, the race condition is real and must be dealt with.

A alternative and cleaner method is to explicitly lock the table using a WRITE lock (preventing other processes from reading/writing to the table). The downsides I can see are a performance hit, and your mysql user must have lock permissions.

// excuse the use of mysqli instead of mysql

$mysqli -> query ( «LOCK TABLE t WRITE» );
$results = $mysqli -> query ( «SELECT id FROM t LIMIT 0,10» );
$totalNumResults = array_pop ( $mysqli -> query ( «SELECT FOUND_ROWS()» )-> fetch_row ());
$mysqli -> query ( «UNLOCK TABLES» );
?>

Now you may iterate through the results just like any other result set.

Actually I am a little ashamed to be saying this, but I stand corrected about a rather old note I posted on 17-Jul-2007 06:44.

Using SQL_CALC_FOUND_ROWS and FOUND_ROWS( ) will NOT trigger a race condition on MySQL, as that would pretty much defy their entire purpose.

The results for their usage is actually unique per connection session as it is impossible for processes to share anything in PHP. As far as PHP is concerned, each request represents a new connection to MySQL as each request is isolated to its own process.

To simulate this, create the following script:

$Handle = mysql_connect ( «localhost» , «root» , «» );
mysql_select_db ( «lls» );

if( isset( $_GET [ ‘Sleep’ ] ) ) mysql_query ( «SELECT SQL_CALC_FOUND_ROWS `bid` From `blocks` Limit 1» );
> else mysql_query ( «SELECT SQL_CALC_FOUND_ROWS `aid` From `access` Limit 1» );
>

if( isset( $_GET [ ‘Sleep’ ] ) ) sleep ( 10 ); // Simulate another HTTP request coming in.
$Result = mysql_query ( «SELECT FOUND_ROWS( )» );
print_r ( mysql_fetch_array ( $Result ) );
>

?>

Set the connection and query information for something that matches your environment.

Run the script once with the Sleep query string and once again without it. Its important to run them both at the same time. Use Apache ab or something similar, or even easier, just open two browser tabs. For example:

If a race condition existed, the results of the first instance of the script would equal the results of the second instance of the script.

For example, the second instance of the script will execute the following SQL query:

mysql_query ( «SELECT SQL_CALC_FOUND_ROWS `aid` From `access` Limit 1» );

?>

This happens while the first instance of the script is sleeping. If a race condition existed, when the first instance of the script wakes up, the result of the FOUND_ROWS( ) it executes should be the number of rows in the SQL query the second instance of the script executed.

But when you run them, this is not the case. The first instance of the script returns the number of rows of its OWN query, which is:

mysql_query ( «SELECT SQL_CALC_FOUND_ROWS `bid` From `blocks` Limit 1» );

?>

So it turns out NO race condition exists, and every solution presented to combat this «issue» are pretty much not needed.

Источник

Читайте также:  Javascript work with file
Оцените статью