Jump to content

Getting num rows before filtering results


egalp

Recommended Posts

Is there a way to use one query to get the number of results that fit a certain criterion and then filter them?
Suppose that I have many rows that fit a criterion, and I want to limit the actual number of rows I fetch, dividing their display to pages that show only a certain number of results per page. I would use the LIMIT argument, with the proper offset to display them.
But I would also like to know the total number of results so I could calculate the number of pages and generate a page navigation display (i.e. page numbers).
Right now I am using two seperate queries, which seems a bit wasteful.

Something like:
[code]
//Geting total number of rows
$query = "SELECT id FROM p_poll";
$result = mysql_query($query);
$num = mysql_num_rows($result);

//Issueing filtered query
$query = "SELECT * FROM p_poll ORDER BY time DESC LIMIT $offset, $per_page";
$result = mysql_query($query,$connect);
$pages = (int) $num / $per_page + 1;

//Outputing query data
while($row = mysql_fetch_array($result))
{
        echo "Various crap";
}

//Generating page navigation
for($i=1;$i<$pages;$i++)
{
if($i != $page)
{
echo "<a href=\"".$_SERVER['PHP_SELF']."?page=".$i."\">[".$i."]</a> ";
}
else
{
echo "-".$i."- ";
}
}
[/code]
In Mysql, using the default MyISAM tables, it is very fast to count the number of rows in a table like this:

[code=php:0]$query = "SELECT count(*) FROM p_poll";
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_array($result);
if ($row) {
  $num = $row[0];
}[/code]


I am rusty with mysql, so I may have made a mistake in there somewhere.
[quote author=weknowtheworld link=topic=121650.msg501111#msg501111 date=1168409280]
Else can have :
$query = "SELECT * FROM p_poll";
$result = mysql_query($query) or die(mysql_error());
$ i =0;
$row = mysql_fetch_array($result);
if ($row) {
  $i++;
}

echo "Count : $i";
[/quote]
Please, please PLEASE NEVER do this.  Use a count() if you want to count, run a query if you want to examine each matching record in succession.
Thanks, but I wasn't asking how to count rows... (If you look at the code piece I submitted I'm counting them at the beginning)
I was asking if it's possible to combine a count on all rows and fetch a filtered result on that count in the same query.

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.