[英]PHP, PDO & MYSQL : lastInsertId() returns NULL
I am rather new at PDO-based MySQL and I'm running into a problem. 我在基于PDO的MySQL上还很陌生,并且遇到了问题。
This is the method I'm executing : 这是我正在执行的方法:
public function insert( $table, $data )
{
// utility functions to auto-format the statements
$keys = $this->getKeys($data);
$placeholders = $this->getPlaceholders($data);
$q = "INSERT INTO $table ($keys) VALUES ($placeholders)";
// this simply returns a new PDO object
$dbh = $this->createSession();
$stmt = $dbh->prepare($q);
$stmt->execute( array_values($data) );
return $dbh->lastInsertId();
}
After that, I run my method and store the returned value in a variable : 之后,我运行我的方法并将返回的值存储在变量中:
$new_user_id = $U->insert( $data );
var_dump($new_user_id);
And I get 我得到
NULL
Note the query is actually executed, and my data is correctly inserted into my table; 注意 ,查询实际上已执行,并且我的数据已正确插入表中; no problem on that side. 那边没问题。 It seems it just can't grab the last insert ID as I ask for it. 似乎我无法索取最后一个插入ID。
Thanks for your time. 谢谢你的时间。
Not sure about any PDO-specific issues, but by default MySQL only returns an insert id if there's an auto_increment integer field in the database (generally but not necessarily the primary key). 不确定是否有任何特定于PDO的问题,但是默认情况下,如果数据库中有一个auto_increment整数字段(通常但不一定是主键),则MySQL仅返回插入ID。 If your table doesn't include this nothing is returned by $dbh->lastInsertId() 如果您的表不包含此内容,则$ dbh-> lastInsertId()不会返回任何内容
I've reviewed the code again and I found that my value wasn't returned because of an intermediate method that wasn't passing the value correctly to the top-layer method. 我再次检查了代码,发现由于中间方法未将值正确地传递给顶层方法而未返回我的值。
Checking the value at the source shows no problem. 从源头检查值显示没有问题。
Thanks for the replies anyway. 无论如何,感谢您的答复。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.