1

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?

2
  • Out of curiousity, why is this a wiki? Commented Feb 28, 2009 at 0:47
  • I asked this back before I knew what a community wiki was. Commented Aug 21, 2012 at 2:10

4 Answers 4

14

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(*)'];
Sign up to request clarification or add additional context in comments.

4 Comments

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?
Nevermind, found this on the doc page: "// Note: If you're expecting just one row, no need to use a loop".
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.
mysql_query("SELECT COUNT(*) AS count FROM News"); would be a lot cleaner also.
1

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

Comments

0

try the following:

$size = @mysql_query("SELECT COUNT(*) AS `total` FROM News");
$query = mysql_fetch_array($size);
echo $query['total'];

Comments

-1

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);
?>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.