MySQL get Primary Key after Insert Statment

情到浓时终转凉″ 提交于 2019-12-25 01:36:05

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!