2

我的PDO::lastInsertId()方法不返回最后插入行的 id(主键),而是返回另一个作为外键字段的字段。

PHP代码:

$pdo = new PDO(...);
$stmt = $pdo->prepare($sql);
$stmt->bindParam(...);
$stmt->bindParam(...);
$stmt->execute();
$id = $pdo->lastInsertId();
// or
$id = $pdo->lastInsertId('services_id_seq'); // I think 'services_id_seq' is not necessary in MySQL
// both of them don't return the primary key of last inserted row

echo 'last inserted id: ' . $id;

MySQL表结构:

...
id          int unsigned not null primary key auto_increment
customer_id int unsigned not null
user_id     int unsigned not null
....

在 MySQL 中插入行:

id    customer_id    user_id    ...
1     19             31         ...

PHP 输出:

last inserted id: 19

1它不应该返回19。我不知道我的代码有什么问题……或者这可能是正常行为:?

返回值(PHP 文档):

  • 如果没有为 name 参数指定序列名称,则 PDO::lastInsertId()返回一个字符串,该字符串表示ID插入数据库的最后一行的行。

  • 如果为 name 参数指定了序列名称,则PDO::lastInsertId()返回一个字符串,该字符串表示从指定序列对象中检索到的最后一个值。

  • 如果PDO驱动程序不支持此功能,则PDO::lastInsertId()触发IM001 SQLSTATE.

4

2 回答 2

1

运行"SELECT LAST_INSERT_ID()"查询。
如果返回的 ID 仍然是 19,而不是 2(或者在所有尝试之后应该是任何主键),则 MySQL 存在问题,与 PDO 无关。您必须将其作为一个单独的案例(并且可能是单独的问题)进行调查,提供完整的 SQL 证明代码,能够在控制台中运行,包括创建表、运行插入和选择 LAST_INSERT_ID()

如果此函数返回正确的值但 PDO 仍然是错误的值 - 您可能必须在 bugs.php.net 上报告它,再次提供完整的可复制代码和所有软件名称以及提供的确切版本号。

只有一件事要说清楚:您确定$sql问题中的变量包含正确的 INSERT 语句,而不是 INSERT ON DUPLICATE 之类的吗?还是在此 INSERT 上设置了任何触发器?

于 2013-01-14T06:57:51.180 回答
-1

I looked at PDO::lastInsertId() recently but found the description in the manual insufficiently convincing (or indeed comprehensible) and so opted for using something like this instead:

...
$stmt->execute();
$row = $stmt->fetch();
...

which seems to work for me.

I'm no PDO or MySQL expert, so this may not be quite right, but I also thought that the above approach would circumvent the possible problem of another row being inserted in the database (by a different user/thread) in between this thread's execute() and lastInsertID() calls.

If you're keen to keep lastInsertID() have you investigated whether, in your setup, the ID returned has to be an auto-increment field? The manual sort of hints that this should be so but is hopeless vague (IMHO).

Hope that's of some help.

Cheers, Ian.

于 2013-01-14T06:11:45.440 回答