tags:

views:

67

answers:

3

It is possible to select last row selected by mysql_query in php without iterating using mysql_fetch_row from first row till last?

If so, what should I use?

+4  A: 

How about ORDER-ing the results in reverse order and getting the first element? Will that work ? (If you are only interested in that row, you can also use LIMIT 1)

nc3b
In fact I need to select (e.g.) 20-th row, but if there are less than 20 rows selected I need last row from selected. Now I use LIMIT to select 20 rows and than select last row iterating via mysql_fetch_array. And I would like to avoid iterating
sergdev
So sort it in reverse order, LIMIT 20, and get the first row.
nc3b
In case of many records selected this will return 20-th record from the end, but I need 20-th from the beginning
sergdev
In that case, you are better off using `OFFSET` and `LIMIT`. Like this: http://stackoverflow.com/questions/16568/how-to-select-the-nth-row-in-a-sql-database-table
nc3b
+2  A: 

You can use mysql_data_seek function:

$result = mysql_query($query);
$row_num = mysql_num_rows($result); 
if (mysql_data_seek($result, $row_num - 1)) {
  $row = mysql_fetch_assoc($result);    
  ...
}
mysql_free_result($result);
Vitalii Fedorenko
A: 

Or, more simply this:

$count=mysql_num_rows(mysql_query("SELECT * FROM whatever"));
$query="SELECT * FROM whatever LIMIT ".($count-1).", 1";
print_r(mysql_fetch_array(mysql_query($query)));
Prab
If any rows were deleted between the first and the second request, you will get an empty result set
Vitalii Fedorenko