MySQL PDO 最后插入的 ID

标签 mysql database pdo

我在 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 对象那么你可以使用 this

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

要保存你的ID,最好将它保存在一个变量中

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

记住你必须恰好在 $sth->execute()

之后使用它

关于MySQL PDO 最后插入的 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10753066/

相关文章:

mysql - 当只需要一个对象时查询返回多个对象

php - 在 Ember 应用程序中连接到 MySql 数据库

Android:在后台同步远程数据库最流畅的方法是什么?

PHP - 将 PDO 与 IN 子句数组一起使用

php - 一旦引用的键插入新值,如何使外键自动更新?

mysql - 按时间排序和分组

mysql - 有没有更好的方法来获取具有相同字段的两个表之间的差异?

php - 需要使用 PHP 将 android 应用程序生成的纬度和经度值存储到 mySQL 数据库中

c++ - postgreSQL 中 lo_import 的 SQL 准备语句是什么

php - 在执行下一条语句之前等待 mysqli::multi_query 完成