0

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?

sergtk
  • 10,714
  • 15
  • 75
  • 130

3 Answers3

4

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
  • 15,562
  • 5
  • 51
  • 63
  • 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 – sergtk May 16 '10 at 11:05
  • So sort it in reverse order, LIMIT 20, and get the first row. – nc3b May 16 '10 at 11:14
  • In case of many records selected this will return 20-th record from the end, but I need 20-th from the beginning – sergtk May 16 '10 at 11:16
  • 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 May 16 '10 at 11:21
3

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
  • 110,878
  • 29
  • 149
  • 111
0

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)));
Prabhakar
  • 347
  • 1
  • 5
  • 12