如何在执行之前通过PDO获取自动增量id

时间:2016-02-29 11:36:43

标签: php sql

我正在寻找“如何在执行前通过PDO获取自动增量ID”的解决方案,有没有办法在pdo中获取未来的ID。

我尝试过lastinsertID,但只能在'执行'之后。

在下面找到原文:

$last_id = $dbh->lastInsertId(); //last insert ID

我的PDO查询

$insert = $dbh->prepare('INSERT INTO _gegevensgebruiker (id, company, name, adress, zipcode, city, tel, email, employees, representative, email_re, function, date_end, user, `date_add`) VALUES (NULL, :company, :name, :adress, :zipcode, :city, :tel, :email, :employees, :representative, :email_re, :function, :date_end, :meid, NOW())');

我知道获取last_id的方法,但我需要一个解决方案来获取PDO语句中的未来ID。

在PDO声明之外的我的instert_ID解决方案下面:

$lastusers_sql = $dbh->prepare('SELECT MAX(id) FROM users');
$lastusers_sql->execute();
$last_id = $lastusers_sql->fetchColumn();

3 个答案:

答案 0 :(得分:1)

您可以使用SELECT MAX()进行INSERT:

INSERT INTO table1 
(id, column1, column2) 
(SELECT (MAX(id)+1), 'value1', 'value2' FROM table1) 

并使用您想要的值增加ID列。

答案 1 :(得分:-1)

$insert = $dbh->prepare('INSERT INTO _gegevensgebruiker ((SELECT MAX(id)+1), company, name, adress, zipcode, city, tel, email, employees, representative, email_re, function, date_end, user, `date_add`) VALUES (NULL, :company, :name, :adress, :zipcode, :city, :tel, :email, :employees, :representative, :email_re, :function, :date_end, :meid, NOW())');

答案 2 :(得分:-1)

创建UID。

$uid = '123#!';
// $dbh->execute();
$lastId = $uid;

不要在autoincr上设置你的id列。否则它不起作用。

相关问题