tags:

views:

133

answers:

4

I want to get a result from sql with unlimited rows, I don't want to use limit in my sql statement because I need to know the total number of rows. But I just want to echo, for example row 30-60.

I use php.

+4  A: 

First, run this statement:

SELECT  SQL_CALC_FOUND_ROWS
        *
FROM    mytable
ORDER BY
        mycol
LIMIT 30, 30

, fetch the rows and save them into an array.

Right after that, run this statement:

SELECT  FOUND_ROWS()

, which will show you total count of rows that would be returned by the previous statement be there no LIMIT clause.

Quassnoi
And how can I echo total rows with php?
Johan
These are two statements. With the first one you get the rows (save them in an array or somewhere else), with the second one you get the total number of rows.
Quassnoi
A: 
$query=mysql_query("SELECT....");
$array=array();
while($row=mysql_fetch_row($query)){
$array[]=$row;
}

Now you have the $array array that contains all the rows. If you want to print only row between 30 and 60 use this:

for($i=30;$i<60;$i++) echo $array[$i][0];
mck89
A: 

I believe Quassnoi means this:

SELECT SQL_CALC_FOUND_ROWS * FROM  accounts ORDER BY accountID LIMIT 30

and then run this select statement to find the number of rows:

select found_rows();

You're not supposed to do any queries using the * of course because it impairs performance. Use the names of the columns you need. I think this would be the best way because it's the most efficient. There's no need to return your entire table if you only need a count and 30 rows.

shady
+1  A: 

http://php.net/manual/en/function.mysql-data-seek.php

mysql_data_seek() moves the internal row pointer of the MySQL result associated with the specified result identifier to point to the specified row number. The next call to a MySQL fetch function, such as mysql_fetch_assoc(), would return that row.

mysql_data_seek($res, 30);
for ($i = 0; $i < 30; ++$i) {
  $row = mysql_fetch_assoc($res);
  var_dump($row);      
}
pingw33n
mysql_data_seek did the work. Thanks a lot! :) Happy again.
Johan
this isn't necessarily a good idea. it means you could be fetching a lot more data than you need, which could end up being less efficient than running two queries (one for limited data, one for count)
Tom Haigh
also if there less than 30 rows available beyond the offset, your for-loop would continue beyond the available data.
Tom Haigh