Jump to content

[SOLVED] mysql_num_rows using limit in sql command


ahs10

Recommended Posts

i have a query that uses LIMIT, but i'd like to get the mysql_num_rows() of that query if the limit wasn't there.  what's the most efficient way to do that?

 

my only solution is...

 

$query = "SELECT * FROM table";

$rcResult = mysql_query($query);

$realCount = mysql_num_rows($rcResult);

$query .= " LIMIT 5";

$result = mysql_query($query);

 

.... i didn't know if there was something more clever than that.

 

any help, guidance, advice, or simple hellos are much appreciated.  thanks!

 

 

Link to comment
Share on other sites

I think that's a good idea since it does require two queries to do what you want in SQL.  You could also just pull all records and do your limit with PHP if you just want to do a single query.

Link to comment
Share on other sites

Well, if you are already going to execute the query to get the number of rows, why wouldn't you just use that resource and LIMIT with PHP?

 

<?php
  $limit = 5;
  $query = "SELECT * FROM table";
  $result = mysql_query($query);
  $count = mysql_num_rows($result);
  for($i =0;$i < $limit && $row = mysql_fetch_array($result);$i++){
    print_r($row);
  }
?>

Link to comment
Share on other sites

Why don't you just ALWAYS use the LIMIT. If there are less records than the limit then it will only pull those. Then just use a mysql_num_rows() after the query to determine how many were actually returned. I don't understand why you need to know the number of records to determine what limit to use.

 

$limit = 5;
$query = "SELECT * FROM table LIMIT $limit";
$rcResult = mysql_query($query);
$realCount = mysql_num_rows($rcResult);
echo "Query limit: $limit<br>Returned count: $realCount";

Link to comment
Share on other sites

that's what i get for trying to simplify my problem... i apologize.

 

i'm doing a paging feature, but executed via ajax.  i need to use the offset and maximum parameters that come with sql's limit, but also know how many rows are in the query without the limit.

 

Link to comment
Share on other sites

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.