简体   繁体   中英

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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM