Jump to content

best way to use count(*) with sql ?


MrAdam
 Share

Recommended Posts

Basically, when you have:

SELECT COUNT(*) FROM table_name

what is the best way to return the result, using PHP... so that I am left with the variable $total containing the number of rows in the table? what is like the best way of doing it?I've been messing around for about half an hour looking on google, trying few different examples but I can't seem to find anything that does what I'm looking for, or explains how to use it properly.Thanks for the help!

Link to comment
Share on other sites

Basically, when you have:
$rowsNr = mysql_fetch_row($result);	$variableToUse = $rowsNr[0];

now you have this variable (i called it variableToUse) which you can use wherever you want..NOTE that your query resultset should be $result (as in the first line of my code).i hope this will help you!

Link to comment
Share on other sites

easier way, to keep you familiar with associated indexes, is

$sql = "SELECT COUNT(*) as total FROM table ";$ans = mysql_query($sql);$total = mysql_fetch_assoc($ans);$total = $total['total'];

mysql_fetch_row can become incredibly confusing trying to remember index numbers later on when you get into very complex statements.. Assoc works better.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...