php 如何从 PDO 获取最后插入的插入行 ID

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24837050/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 17:29:36  来源:igfitidea点击:

How to get last inserted inserted row id from PDO

phpsqlpdo

提问by Mr.Happy

I am following mvc structure in PHP and I want to retrieve last inserted row ID.

我在 PHP 中遵循 mvc 结构,我想检索最后插入的行 ID。

I have created following sql code:

我创建了以下 sql 代码:

$sql = "INSERT INTO song (artist, track, link) VALUES (:artist, :track, :link)";
$query = $this->db->prepare($sql);
$query->execute(array(':artist' => $artist, ':track' => $track, ':link' => $link));

echo $query->lastInsertId(); // To retrieve last inserted row ID.

but unfortunately I ma getting this error: Fatal error: Call to undefined method PDOStatement::lastInsertId()

但不幸的是我收到了这个错误: Fatal error: Call to undefined method PDOStatement::lastInsertId()

I have also tried this stacklinks but not worked for me so I will happy if you help me for retrieve ID.

我也试过这个堆栈链接,但对我没有用,所以如果你能帮我检索 ID,我会很高兴。

I am also sharing my controller.php file here.

我也在这里分享我的 controller.php 文件。

/**
 * This is the "base controller class". All other "real" controllers extend this class.
 */
class Controller{
    /**
     * @var null Database Connection
     */
    public $db = null;

    /**
     * Whenever a controller is created, open a database connection too. The idea behind is to have ONE connection
     * that can be used by multiple models (there are frameworks that open one connection per model).
     */
    function __construct(){
        $this->openDatabaseConnection();
    }

    /**
     * Open the database connection with the credentials from application/config/config.php
     */
    private function openDatabaseConnection(){
        // set the (optional) options of the PDO connection. in this case, we set the fetch mode to
        // "objects", which means all results will be objects, like this: $result->user_name !
        // For example, fetch mode FETCH_ASSOC would return results like this: $result["user_name] !
        // @see http://www.php.net/manual/en/pdostatement.fetch.php
        $options = array(PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ, PDO::ATTR_ERRMODE => PDO::ERRMODE_WARNING);

        // generate a database connection, using the PDO connector
        // @see http://net.tutsplus.com/tutorials/php/why-you-should-be-using-phps-pdo-for-database-access/
        $this->db = new PDO(DB_TYPE . ':host=' . DB_HOST . ';dbname=' . DB_NAME, DB_USER, DB_PASS, $options);
    }

    /**
     * Load the model with the given name.
     * loadModel("SongModel") would include models/songmodel.php and create the object in the controller, like this:
     * $songs_model = $this->loadModel('SongsModel');
     * Note that the model class name is written in "CamelCase", the model's filename is the same in lowercase letters
     * @param string $model_name The name of the model
     * @return object model
     */
    public function loadModel($model_name){
        require 'application/models/' . strtolower($model_name) . '.php';
        // return new model (and pass the database connection to the model)
        return new $model_name($this->db);
    }
}

回答by andrewsi

You're almost there.

您快到了。

If you look at the manual page for lastInsertId, it's called on the database handle - you're currently calling it on the statement.

如果您查看lastInsertId 的手册页,它会在数据库句柄上调用 - 您当前正在语句上调用它。

You just need to call:

你只需要打电话:

$this->db->lastInsertId();

回答by Mithun Sen

you can try the following -

您可以尝试以下操作 -

$query = "INSERT INTO song (artist, track, link) VALUES (:artist, :track, :link)";
$stmt = $pdo->prepare($query);

$params = array(
    "artist" => $artist,
    "track" => $track,
    "link" => $link,
);

$data = $stmt->execute($params);

$insert_id = $pdo->lastInsertId();