codeBarer
codeBarer

Reputation: 2378

PHP MySQL INSERT Value return Primary Key of inserted

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?

Upvotes: 1

Views: 4768

Answers (3)

spencer7593
spencer7593

Reputation: 108370

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

Upvotes: 0

user1846065
user1846065

Reputation:

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.

Upvotes: 2

roninblade
roninblade

Reputation: 1892

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

Upvotes: 5

Related Questions