获取上次插入行的唯一ID

时间:2012-04-25 06:29:55

标签: mysql stored-procedures insert

我想获取存储过程中最后插入行的唯一ID,我这样做

DELIMITER //
 CREATE PROCEDURE addNewUsers(IN userName varchar(128),IN password varchar(128), IN addedBy INT)

BEGIN

 DECLARE id int default 0;

  id = mysqli_insert_id (insert into  `system_users`( `username`,`password`) values (userName ,md5(password)) );
  IF id <> 0 THEN     
        insert into  `user_profile`( `full_name`,`Date_time_ added`,`added_by`) values (userName ,CURRENT_TIMESTAMP(),addedBy ) where `user_id`=id ;
  END IF


END //

DELIMITER ;

发生此错误

  #1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '= mysqli_insert_id (insert into `system_users`( `username`,`password`) values (' at line 7

我怀疑它来自mysqli_insert_id ,我该怎么办?

1 个答案:

答案 0 :(得分:7)

您的mysqli_insert_id是问题,您正在编写MySQL存储过程,而不是PHP。您想使用last_insert_id()函数:

  

LAST_INSERT_ID()(不带参数)返回一个BIGINT(64位)值,表示由于最近执行AUTO_INCREMENT而成功插入INSERT列的第一个自动生成的值声明。

您还需要修复分配语法。更像是这样:

DELIMITER //
CREATE PROCEDURE addNewUsers(IN userName varchar(128),IN password varchar(128), IN addedBy INT)
BEGIN
  DECLARE id int default 0;

  insert into  `system_users`( `username`,`password`) values (userName ,md5(password));
  set id = last_insert_id();
  if id <> 0 then
    -- ...