dsbruqxgt820011351
2013-08-29 02:58
浏览 142
已采纳

PHP MySQL INSERT值返回插入的主键

I'm trying to use the following statement to insert photograph information into photograph table:

$stmt = $mysqli->prepare("INSERT INTO Photographs(Genre, Name, Photographer, Camera, location) VALUES(?,?,?,?,?)");
$stmt->bind_param('isiis', $genre, $name, $photographer, $camera, $location);
$stmt->execute();

After successful insert I would like to get the auto incremented primary key value of the photograph table and insert into a junction table (for my many to many relationship) as such:

$stmtPhotoGenre = $mysqli->prepare("INSERT INTO PhotoGenre(idPhotograph, Genre) VALUES(?,?)");
$stmtPhotoGenre->bind_param('ii', $idPhotograph);

Is there a way to get the id of the last insert using MySQL or PHP? I thought of using timestamp but there is always a chance that two people can be inserting at the same time and some sort cross mapping could happen. Any solution or suggestions?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • dongzhi9906 2013-08-29 03:00
    已采纳

    mysqli_insert_id — Returns the auto generated id used in the last query

    点赞 打赏 评论
  • douzheng0702 2013-08-29 03:01

    You can get it back using this class variable named mysqli_insert_id.

    It looks like all you have to do is access $stmtPhotoGenre->insert_id;, or run mysqli_insert_id($link); if you're not going the OOP route.

    点赞 打赏 评论
  • dourangdz750379 2013-08-29 03:01

    I think the MySQL LAST_INSERT_ID function will meet your needs.

    http://dev.mysql.com/doc/refman/5.5/en/information-functions.html#function_last-insert-id

    点赞 打赏 评论

相关推荐 更多相似问题