How to get last inserted inserted row id from PDO

前端 未结 2 910
盖世英雄少女心
盖世英雄少女心 2020-12-19 10:43

I am following mvc structure in PHP and I want to retrieve last inserted row ID.

I have created following sql code:

$sql = \"INSERT          


        
相关标签:
2条回答
  • 2020-12-19 10:57

    you can try the following -

    $query = "INSERT INTO song (artist, track, link) VALUES (:artist, :track, :link)";
    $stmt = $pdo->prepare($query);
    
    $params = array(
        "artist" => $artist,
        "track" => $track,
        "link" => $link,
    );
    
    $data = $stmt->execute($params);
    
    $insert_id = $pdo->lastInsertId();
    
    0 讨论(0)
  • 2020-12-19 11:05

    You're almost there.

    If you look at the manual page for lastInsertId, it's called on the database handle - you're currently calling it on the statement.

    You just need to call:

    $this->db->lastInsertId();
    
    0 讨论(0)
提交回复
热议问题