-1

Is it possible to fetch only the last row returned from a mysql query. For example. Let's say I have

$result=mysql_query("SELECT * from mytable)

It returns many rows. the only way I know to get the data is to use a while loop like this

while ($row=mysql_fetch_array($result)) { ... }

I know what you're thinking... Why not just do a query to SELECT only the last row? But lets say that's out of my control. The query is already done and it's got lots of rows and I don't want to do another query. Is the only way to get the last row, to go through the entire while loop and then look at the last data returned? Or is there a way to maybe fetch the rows backwards and stop at the first one. Actually, if it makes it any easier, I don't really even need the entire last row. I want to know what's in the last column of the last row.

Dharman
  • 30,962
  • 25
  • 85
  • 135
CheeseFlavored
  • 1,922
  • 1
  • 21
  • 28

3 Answers3

3

Although you use obsolete mysql api, you can use mysql_data_seek.

Link provides you an example, you can do something like:

mysql_data_seek($result, mysql_num_rows($result) - 1);
$row = mysql_fetch_array($result);

More up-to-date mysqli also has this feature.

u_mulder
  • 54,101
  • 5
  • 48
  • 64
2

Use

SELECT * FROM Table ORDER BY ID DESC LIMIT 1

Alternatively PHP Answer:

$lastElement = array_values(array_slice($array, -1))[0];

If you run that on your query results you can just get the value this way.

Lulceltech
  • 1,662
  • 11
  • 22
0

PHP

You can have a variable outside of the loop that saves the last row like so:

$lastRow = null;
while ($row=mysql_fetch_array($result)) 
{  
    $lastRow = $row;
}

$value = lastRow['ColumnName'];

You can now use lastRow anywhere outside of the query.

SQL

You can order by descending to flip the table.

SELECT ColumnName FROM table ORDER BY id DESC LIMIT 1;

LIMIT 1 would only return 1 row.

Haley Mueller
  • 487
  • 4
  • 16