Saad Altaf Saad Altaf - 6 months ago 21
SQL Question

How to fetch record from mysql using last inserted id?

This is what i tried and it works fine..

$sql = "SELECT * FROM patient where id = (SELECT max(id) FROM patient)";
result = mysql_query($sql);
if (mysql_num_rows($result) > 0)
{
// output data of each row
while($row = mysql_fetch_assoc($result)) {
$patientid=$row["id"];
$patientname=$row["name"];
$patientrefer=$row["referto"];
$patientdisease=$row["disease"];
}
} else
{
echo "0 results";
}


but whenever i replaced the query with

$sql = "SELECT * FROM patient where id = LAST_INSERT_ID()";


It always return 0 results.

Answer

In order to get last (latest) record from your table, you can do descending ORDER BY together with LIMIT:

SELECT * FROM patient ORDER BY id DESC LIMIT 0,1

You don't need LAST_INSERT_ID in that case at all. Moreover with concurrent inserts you cannot ensure that user's last insert is really the latest one by using LAST_INSERT_ID.