Mysql
 sql >> Database >  >> RDS >> Mysql

Come posso recuperare l'ultimo record in una tabella di database MySQL utilizzando PHP?

Usa 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);

?>

La query SQL:

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

...usa ORDER BY per impostare i valori in modo che il valore più alto sia la prima riga nel set di risultati. Il LIMIT dice che di tutte quelle righe, solo la prima viene effettivamente restituita nel set di risultati. Perché messageid è auto-incremento, il valore più alto è quello più recente...