问题
I need to use the following insert statement, and the primary key field is auto increment. I need to return the new primary key value after the insert. Preferably using one statement to do the insert and return primary key value.
$query = $database->connection->prepare("INSERT INTO accounts (created, priviledge, password, token, idle) VALUE ('$created', '1', :password, '$token_encrypt', '$idle')");
$query->bindParam(":password", $password_hash);
$query->execute();
回答1:
As soon as you're using PDO you need to use
$database->connection->lastInsertId()
And it guarantees you to return the value from the current session. So answering to your question from comments - there is no chance you get the wrong value from a concurrent session.
回答2:
assume your primary field name is id then try this code
SELECT max(id) FROM tableName
or try this
LAST_INSERT_ID();
回答3:
Use mysql_insert_id();
to get the ID generated in the last query.
It retrieves the ID generated for an AUTO_INCREMENT column by the previous query (usually INSERT).
回答4:
DELIMITER $$
DROP TRIGGER IF EXISTS `TR_AI_mytable`;
CREATE TRIGGER `TR_AI_mytable` AFTER INSERT
ON `mytable` FOR EACH ROW
BEGIN
SET @mylastPK = new.PKField;
END;
$$
来源:https://stackoverflow.com/questions/26412658/mysql-get-primary-key-after-insert-statment