Jump to content

Recommended Posts

If I have a simple query:

$query = "select count(*) from table";

$mysql_query($query) or die (mysql_error());

 

What is the simplest way to display the actual number of rows returned?

 

since I'm not actually grabbing a row, I'm not sure how to display the count.

Can be done this way as well mate.

<?php 
//database connection.


/// select with count.
$query = "select count(*) as num from table";
//query select.
$mysql_query($query) or die (mysql_error());
//loop query.
while($row=mysql_fetch_array($mysql_query)){
//echo result.
echo $row['num'];
}
?>

and this way.

 

<?php 
//database connection.


/// select with count.
$query = "select count(*) as num from table";
//query select.
$mysql_query($query) or die (mysql_error());

//echo result.
echo $mysql_query['num'];

?>

 

If you want just the count, this is the better/preferred method:

 

<?php
$sql = "SELECT count(id) as cnt FROM `table`";
$query = mysql_query($sql) or die(mysql_error());
$cnt = mysql_result($query, 0);
echo $cnt;
?>

 

Do not use count(*) as it is slower and less efficient. Defining a column is much faster and you should generally use the index/primary key column.

 

EDIT:

Sort of beaten to it by Thorpe, but yea, since I do not use count(*) I figured this was ok to post :)

If you want just the count, this is the better/preferred method:

 

<?php
$sql = "SELECT count(id) as cnt FROM `table`";
$query = mysql_query($sql) or die(mysql_error());
$cnt = mysql_result($query, 0);
echo $cnt;
?>

 

Do not use count(*) as it is slower and less efficient. Defining a column is much faster and you should generally use the index/primary key column.

 

EDIT:

Sort of beaten to it by Thorpe, but yea, since I do not use count(*) I figured this was ok to post :)

 

Oh, ok.....thank you.

yeah, that was exactly what I wanted...just the count....

thanks guys.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.