PDO get the last ID inserted

前端 未结 3 2129
一整个雨季
一整个雨季 2020-11-22 13:59

I have a query, and I want to get the last ID inserted. The field ID is the primary key and auto incrementing.

I know that I have to use this statement:



        
3条回答
  •  傲寒
    傲寒 (楼主)
    2020-11-22 15:03

    That's because that's an SQL function, not PHP. You can use PDO::lastInsertId().

    Like:

    $stmt = $db->prepare("...");
    $stmt->execute();
    $id = $db->lastInsertId();
    

    If you want to do it with SQL instead of the PDO API, you would do it like a normal select query:

    $stmt = $db->query("SELECT LAST_INSERT_ID()");
    $lastId = $stmt->fetchColumn();
    

提交回复
热议问题