PDO get the last ID inserted

前端 未结 3 2084
一整个雨季
一整个雨季 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 14:48

    You can get the id of the last transaction by running lastInsertId() method on the connection object($conn).

    Like this $lid = $conn->lastInsertId();

    Please check out the docs https://www.php.net/manual/en/language.oop5.basic.php

    0 讨论(0)
  • 2020-11-22 14:49

    lastInsertId() only work after the INSERT query.

    Correct:

    $stmt = $this->conn->prepare("INSERT INTO users(userName,userEmail,userPass) 
                                  VALUES(?,?,?);");
    $sonuc = $stmt->execute([$username,$email,$pass]);
    $LAST_ID = $this->conn->lastInsertId();
    

    Incorrect:

    $stmt = $this->conn->prepare("SELECT * FROM users");
    $sonuc = $stmt->execute();
    $LAST_ID = $this->conn->lastInsertId(); //always return string(1)=0
    
    0 讨论(0)
  • 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();
    
    0 讨论(0)
提交回复
热议问题