繁体   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