Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I fetch the last record in a MySQL database table using PHP?

I want to fetch the last result in MySQL database table using PHP. How would I go about doing this?

I have 2 Columns in the Table, MessageID(auto) & Message.

I already know how to connect to the database.

like image 685
ritch Avatar asked Aug 05 '10 01:08

ritch


Video Answer


1 Answers

Use mysql_query:

<?php
$result = mysql_query('SELECT t.messageid, t.message 
                         FROM TABLE t 
                     ORDER BY t.messageid DESC 
                        LIMIT 1') or die('Invalid query: ' . mysql_error());

//print values to screen
while ($row = mysql_fetch_assoc($result)) {
  echo $row['messageid'];
  echo $row['message'];
}

// Free the resources associated with the result set
// This is done automatically at the end of the script
mysql_free_result($result);

?>

The SQL query:

  SELECT t.messageid, t.message 
    FROM TABLE t 
ORDER BY t.messageid DESC 
   LIMIT 1

...uses the ORDER BY to set the values so the highest value is the first row in the resultset. The LIMIT says that of all those rows, only the first is actually returned in the resultset. Because messageid is auto-increment, the highest value is the most recent one...

like image 64
OMG Ponies Avatar answered Oct 31 '22 19:10

OMG Ponies