-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.

0

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

5 Comments

the question was asking how to do it without a different query. I need a php answer
Why not just build this into your original query? You don't need to run 2 queries.
@CheeseFlavored Added a php answer for you as well
I am looking for a php answer, I tried $lastElement = array_values(array_slice(mysql_fetch_array($result), -1))[0]; but it didn't give me the last element
Then your select query is sorting it wrong and you will have to modify it. Otherwise there's no easy answer.
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.

2 Comments

the question was asking how to do it without a different query. I need a php answer based on the query that was already done.
@CheeseFlavored I have updated my answer

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.