簡體   English   中英

MySQL PDO最后插入了ID

[英]MySQL PDO last inserted ID

我有一個帶有主鍵的MySQL表,我插入到該表中,我想恢復已插入的最后一行的id,我知道我必須使用LAST_INSERT_ID但我的問題是在使用該語句將值插入另一個之后沒有主鍵的表,我可以再次使用它來獲取第一個插入的確切ID嗎?

$ 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
            ));
        }

現在,如果about==place可以寫這個嗎?

$query = "INSERT INTO `question-io` (questionID, io) VALUES
                (LAST_INSERT_ID() ,:io )";
$sth = $this->db->prepare($query);
$sth->execute(array(
                ':io' => $io
            ));

我沒有嘗試過,因為我無法嘗試,直到我填寫所有表格而且我無法填寫所有表格而不知道ID :)

如果您的對象$this->db引用PDO對象,那么您可以使用它

$ID=$this->db->lastInsertId();

要保存您的ID,最好將其保存在變量中

所以在每次插入后,您可以保存該插入行的ID

並記住你必須在$sth->execute()之后使用它

每次將記錄插入到具有主鍵作為自動增量的表中時,“LAST_INSERT_ID()”將使用最新的值進行更新。 它不是持久性的,但是如果你的表沒有一個,它仍然應該保留用於具有自動增量主鍵的表的最后一個值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM