PDO lastInsertId()始终返回0 [英] PDO lastInsertId() always return 0
问题描述
我遇到了一个问题.我的框架在PHP 5.3.0上运行正常.我将PHP版本升级到PHP 5.4.x,并且框架的某些部分开始出现一些问题.
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版本升级后,PDO lastInsterId()
始终返回0
.
After PHP version upgrade, PDO lastInsterId()
always returns 0
.
我有一个称为id
的自动递增字段.
它将数据毫无问题地添加到数据库中.
I have auto-increment field called id
.
It is adding the data to database without any problems.
由于某种原因,我的最后一个插入ID一直为0.
For some reason I keep getting 0 as last insert id.
这是我的代码;
databaseobjects.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
public function crudQuery($sql, $data) {
$sth = $this->handler->prepare($sql);
return $sth->execute($data);
}
首先调用create()
方法,然后调用crudQuery()
方法.
如前所述,我可以将数据成功添加到MySQL数据库中.
不幸的是,当我调用lastInsterID()
方法时,它总是返回0.
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.
如果您能在通过SQL Query获得最后的ID(:
I will be really glad if you can help me out with this problem before I will get the last ID with SQL Query (:
推荐答案
除了php/PDO或您的框架中的错误外,还有两种可能.在与插入不同的MySQL连接上调用lastInsertId()
,或者在应用程序/框架中生成ID并将其插入,而不是让auto_increment为您生成它.表中的哪一列是主键/auto_increment?该列是否包含在create()
函数的$attributes
中?
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 $attributes
in your create()
function?
您可以测试PDO以确保该部分使用此代码正确工作(在新文件中):
You can test PDO to make sure that part is working correctly with this code (in a new file):
// 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"
这篇关于PDO lastInsertId()始终返回0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!