Reputation: 401
I have a table on MySQL with a primary key, I inserted to that table and I want to resume the id of the last row has inserted, I know I have to use LAST_INSERT_ID
but my question is after using that statement to insert values to another table that doesn't have primary key , can I use it again to get the exact ID of the first inserted ?
$php pdo #
include_once 'type_model.php';
$t = new Type_Model();
$typeID = $t->getTypeID($type);
include_once 'informationObject_model.php';
$i = new InformationObject_Model();
$answerIoID = $i->getIOID($ioAnswer);
$query = "INSERT INTO question (info, text, answer, answerIoID, firstChoice, secondChoice, thirdChoice,
firstHint, secondHint, typeID) VALUES (:info, :text, :answer, :answerIoID,
:firstChoice, :secondChoice, :thirdChoice, :firstHint, :secondHint, :typeID)";
$sth = $this->db->prepare($query);
$sth->execute(array(
':info' => $info,
':text' => $text,
':answer' => $answer,
':answerIoID' => $answerIoID,
':firstChoice' => $choices[0],
':secondChoice' => $choices[1],
':thirdChoice' => $choices[2],
':firstHint' => $hints[0],
':secondHint' => $hints[1],
':typeID' => $typeID
));
if ($about == "Place") {
include_once 'place_model.php';
$p = new Place_Model();
$placeID = $p->getPlaceID($place);
$query = "INSERT INTO `question-place` (questionID, placeID) VALUES
(LAST_INSERT_ID() ,:placeID )";
$sth = $this->db->prepare($query);
$sth->execute(array(
':placeID' => $placeID
));
}
and now if the about==place
can i write this ?
$query = "INSERT INTO `question-io` (questionID, io) VALUES
(LAST_INSERT_ID() ,:io )";
$sth = $this->db->prepare($query);
$sth->execute(array(
':io' => $io
));
I didn't try it , because I can't try it untill I fill all my tables and I can't fill all my tables without know the ID :)
Upvotes: 2
Views: 15455
Reputation: 2564
Every time you insert record into a table which has primary key as auto-increment "LAST_INSERT_ID()" will be updated with most latest value. It will not be persistent, but yes if your table does not have one it should still hold the last value used for table which had auto-increment primary key.
Upvotes: 1
Reputation: 28819
if your object $this->db
reference to a PDO object so you can use this
$ID=$this->db->lastInsertId();
to save your ID, it is better to save it in a variable
so after each insert you can save the ID of that inserted row
and remember you have to used it exactly after $sth->execute()
Upvotes: 12