php PDO lastInsertId() 总是返回 0
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11776818/
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
PDO lastInsertId() always return 0
提问by Revenant
I've come across with a problem. My framework was working just fine with PHP 5.3.0. I upgraded my PHP version to PHP 5.4.x and I started to have few issues with some parts of my framework.
我遇到了一个问题。我的框架在 PHP 5.3.0 上运行得很好。我将 PHP 版本升级到 PHP 5.4.x,并且我的框架的某些部分开始出现一些问题。
After PHP version upgrade, PDO lastInsterId()always returns 0.
PHP 版本升级后,PDO lastInsterId()总是返回0.
I have auto-increment field called id.
It is adding the data to database without any problems.
我有一个名为id. 它正在将数据添加到数据库中,没有任何问题。
For some reason I keep getting 0 as last insert id.
出于某种原因,我一直将 0 作为最后一个插入 ID。
Here is my code;
这是我的代码;
databaseobjects.php
数据库对象.php
public static function create () {
global $db;
$attributes = self::sanitize(static::$fields);
$sql = "INSERT INTO ".PREFIX.static::$table_name." (";
$sql .= join(", ", array_keys($attributes));
$sql .= ") VALUE (:";
$sql .= join(", :", array_keys($attributes));
$sql .= ")";
return ($db->crudQuery($sql, $attributes)) ? true : false;
}
public static function lastInsertID () {
global $db;
return $db->handler->lastInsertId();
}
database.php
数据库.php
public function crudQuery($sql, $data) {
$sth = $this->handler->prepare($sql);
return $sth->execute($data);
}
First create()method is called, then crudQuery()method is called.
As I mentioned before, I can add the data successfully to MySQL database.
Unfortunately when I call lastInsterID()method, it always returns 0.
首先create()调用方法,然后crudQuery()调用方法。正如我之前提到的,我可以成功地将数据添加到 MySQL 数据库中。不幸的是,当我调用lastInsterID()方法时,它总是返回 0。
I will be really glad if you can help me out with this problem before I will get the last ID with SQL Query (:
如果您能在我使用 SQL 查询获得最后一个 ID 之前帮助我解决这个问题,我将非常高兴(:
回答by Gary G
Other than a bug in php/PDO or your framework, there are two possibilities. Either lastInsertId()is called on a different MySQL connection than the insert, or you are generating the id in your application/framework and inserting it, rather than letting auto_increment generate it for you. Which column in the table is the primary key/auto_increment? Is that column included in $attributesin your create()function?
除了 php/PDO 或您的框架中的错误之外,还有两种可能性。要么lastInsertId()在与插入不同的 MySQL 连接上调用,要么在应用程序/框架中生成 id 并插入它,而不是让 auto_increment 为您生成它。表中哪一列是主键/auto_increment?该列是否包含$attributes在您的create()函数中?
You can test PDO to make sure that part is working correctly with this code (in a new file):
您可以测试 PDO 以确保该部分使用此代码(在新文件中)正常工作:
// Replace the database connection information, username and password with your own.
$conn = new PDO('mysql:dbname=test;host=127.0.0.1', 'user', 'password');
$conn->exec('CREATE TABLE testIncrement ' .
'(id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, name VARCHAR(50))');
$sth = $conn->prepare('INSERT INTO testIncrement (name) VALUES (:name)');
$sth->execute([':name' => 'foo']);
var_dump($conn->lastInsertId());
$conn->exec('DROP TABLE testIncrement');
When I ran this script, the output was
当我运行这个脚本时,输出是
string(1) "1"
回答by slawkens
The one other problem could be using $pdo->exec($sql) instead of $pdo->query($sql).
另一个问题可能是使用 $pdo->exec($sql) 而不是 $pdo->query($sql)。
exec($sql) will return always 0 when you use $pdo->lastInsertId(). So use query() instead.
当您使用 $pdo->lastInsertId() 时,exec($sql) 将始终返回 0。所以改用 query() 。
回答by Ivan Fretes
When no exception is thrown, lastInsertId returns 0. However, if lastInsertId is called before calling commit, the right id is returned.
当没有抛出异常时,lastInsertId 返回 0。但是,如果在调用 commit 之前调用 lastInsertId,则返回正确的 id。
回答by Harry Lewis
After you commit a transaction PDO::lastInsertID() will return 0, so best to call this method before the transaction is committed.
提交事务后 PDO::lastInsertID() 将返回 0,因此最好在提交事务之前调用此方法。
回答by Peter Ajtai
I got a 0 when the last insert statement failed due to a foreign key contraint. last_error was a string.
由于外键约束,当最后一个插入语句失败时,我得到了一个 0。last_error 是一个字符串。

