MySQL PDO最后插入ID [英] MySQL PDO last inserted ID

查看:186
本文介绍了MySQL PDO最后插入ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表有MySQL的主键,我插入到那个表,我想恢复最后一行的插入的id,我知道我必须使用 LAST_INSERT_ID
但我的问题是,使用该语句后,将值插入到没有主键的另一个表,我可以再次使用它来获取第一个插入的确切ID吗?

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#

$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 可以写这个吗?

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

我没有尝试,因为我不能尝试,直到我填满了所有的表,我不能填充所有的表,不知道ID:)

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 :)

推荐答案

如果你的对象 $ this - > db 对PDO对象的引用,以便您可以使用此

if your object $this->db reference to a PDO object so you can use this

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

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

to save your ID, it is better to save it in a variable

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

so after each insert you can save the ID of that inserted row

并记住您必须在 $ sth-> execute()

这篇关于MySQL PDO最后插入ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆