php 使用插入 PDO MySQL 获取插入 ID

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3742554/
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 10:56:58  来源:igfitidea点击:

Getting insert id with insert PDO MySQL

phpsqlpdo

提问by pondpad

Im getting to grips with the basics of PDO.

我开始掌握 PDO 的基础知识。

However Im trying to get the id of the inserted row, Im using:

但是我试图获取插入行的 id,我使用:

$query = $system->db->prepare("INSERT INTO {$this->_table} (name,description) VALUES (:name,:description)");
$query->execute(array('name'=>$name,'description'=>$description));

The tutorials I have come across are regarding transactions, however I am not using transactions!

我遇到的教程是关于交易的,但是我没有使用交易!

回答by Fanis Hatzidakis

You're probably looking for lastInsertId. "Returns the ID of the last inserted row or sequence value".

您可能正在寻找lastInsertId。“返回最后插入的行或序列值的 ID”。

$insertedId = $system->db->lastInsertId() ;

回答by Daniel Miranda

Pay attention when using transactions.

使用事务时要注意。

If you call lastInsertedIdafter you call commit, lastInsertedIdwill return 0 instead of the id. Call lastInsertedIdright after execute, but before commit.

如果在调用lastInsertedId后调用commitlastInsertedId将返回 0 而不是 id。调用lastInsertedId之后execute,但之前commit

$this->db->beginTransaction();
$this->stmt->execute();
$id = $this->db->lastInsertId();
$this->db->commit();