tags:

views:

512

answers:

3

I want to get the number of rows in my MySQL table and store that number in a php variable. This is the code I'm using:

$size = @mysql_query("SELECT COUNT(*) FROM News");

$size ends up being "Resource ID #7." How do I put the number of rows directly into $size?

+1  A: 

You need to call mysql_fetch_row or one of its sister functions.

<?php
// untested
$result = @mysql_query("SELECT COUNT(*) FROM News");
// error handling
$row = mysql_fetch_row($result);
$count = $row[0];
?>
gpojd
+9  A: 

mysql_query returns a query resource id. In order to get values from it you need to use mysql_fetch_assoc on the resource id to fetch a row into an array.

$result = mysql_query("SELECT COUNT(*) FROM News");
$row = mysql_fetch_assoc($result);
$size = $row['COUNT(*)'];
Daniel Von Fange
I haven't used php in a while, but won't it not release the $result if you don't loop through until mysql_fetch_assoc returns a null? Shouldn't it usually be used with a while loop, or is there another way to tell mysql that you don't want any more rows from $result?
gpojd
Nevermind, found this on the doc page: "// Note: If you're expecting just one row, no need to use a loop".
gpojd
You could do mysql_free_result( $result ), but you could argue that was unnecessary - the result buffer is only going to contain one row, in any case, and all the resources will be freed when the script exits.
Rob
mysql_query("SELECT COUNT(*) AS count FROM News"); would be a lot cleaner also.
Ólafur Waage
A: 

On a related note you can use the mysql_num_rows() function to obtain the number of rows from a given query. This is handy if you need to grab the data but also know the number of rows.

<?php
  $result = @mysql_query("SELECT * FROM news");
  $count = @mysql_num_rows($result);
?>
Paulo