获取的唯一ID上次插入行(Get the Unique ID for the Last Insert

2019-09-16 17:30发布

我想获得的唯一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 ,我该怎么办?

Answer 1:

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
    -- ...


文章来源: Get the Unique ID for the Last Inserted Row