【问题标题】:MySQL PDO last inserted IDMySQL PDO 最后插入的 ID
【发布时间】:2012-05-31 22:57:24
【问题描述】:

我在 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 的情况下填满所有表格 :)

【问题讨论】:

    标签: mysql database pdo


    【解决方案1】:

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

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

    要保存您的 ID,最好将其保存在变量中

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

    记住你必须在$sth->execute()之后使用它

    【讨论】:

      【解决方案2】:

      每次您将记录插入到具有作为自动增量的主键的表中时,“LAST_INSERT_ID()”都会更新为最新值。它不会是持久的,但是如果您的表没有,它应该仍然保留用于具有自动增量主键的表的最后一个值。

      【讨论】:

      • 谢谢你的帮助,我已经放了自动增量,我得到了答案,谢谢
      猜你喜欢
      • 2011-05-15
      • 1970-01-01
      • 2013-05-26
      • 2012-05-27
      • 1970-01-01
      • 2016-07-10
      相关资源
      最近更新 更多