Search code examples
phpmysqlinsertmysql-insert-id

Grab last ID of Insert query


I need to get the story_id from the last insert. Ive tried using mysql_insert_id() but it doesn't seem to work with my statement. Here is the code:

$stmt = $this->db->prepare("INSERT INTO active_stories (story_id, current_chapter, creator, cover_title, cover_img_name, create_date, last_update_date, story_tags, locked) VALUES (NULL, ?, ?, ?, ?, ?, ?, ?, ?)");
        $stmt->bind_param("issssssi",$zero, $creatorName,$storyTitle, $fileName, $createDate, $createDate, $themeTags, $zero);
        $stmt->execute();
        printf("Last inserted record has id %d\n", mysql_insert_id());
        $stmt->close();

Solution

  • If you are using PDO, here's how to get that:

    PDO::lastInsertId()
    

    If using mysqli, try this one:

    mysqli::$insert_id