简体   繁体   中英

how to get LAST_INSERT_ID via stored procedure in php

say i have a stored procedure in mysql like below

-- ----------------------------
-- Procedure structure for usp_insert_user_basic_info
-- ----------------------------
DROP PROCEDURE IF EXISTS `usp_insert_user_basic_info`;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `usp_insert_user_basic_info`(IN `user_first_name` varchar(200),IN `user_last_name` varchar(200),IN `user_password` text,IN `user_dob` date,IN `user_email` varchar(250))
BEGIN
    #Routine body goes here...
  INSERT INTO  `nuclear`.`user_basic_info` (
    `user_email` ,
    `user_password` ,
    `user_first_name` ,
    `user_last_name` ,
    `user_dob`,
    `user_creation_time`
    )
    VALUES (
      user_email,  user_password,  user_first_name,  user_last_name,  user_dob,NOW()
    );
 SELECT LAST_INSERT_ID() ;

END
;;
DELIMITER ;

Table

    -- ----------------------------
-- Table structure for user_basic_info
-- ----------------------------
DROP TABLE IF EXISTS `user_basic_info`;
CREATE TABLE `user_basic_info` (
  `user_id` int(11) NOT NULL AUTO_INCREMENT,
  `user_email` varchar(250) DEFAULT NULL,
  `user_password` text,
  `user_first_name` varchar(200) DEFAULT NULL,
  `user_last_name` varchar(200) DEFAULT NULL,
  `user_dob` date DEFAULT NULL,
  `user_creation_time` datetime DEFAULT NULL,
  PRIMARY KEY (`user_id`),
  UNIQUE KEY `user_email` (`user_email`)
) ENGINE=InnoDB AUTO_INCREMENT=36 DEFAULT CHARSET=latin1;

i can call this from php without any problem

 $resultUsp = mysql_query($query) or die("Error: " . mysql_error());

but it only returns 1 for each successful insert. i guess it is saying 1 row affected!

i want it to return LAST_INSERT_ID

how to do it? by the way i don't want to add any OUT parameter. mysql_insert_id returns 0

You can get last insert id like this in SP:

DECLARE LID int;

SET LID = LAST_INSERT_ID();

10.4.22-MariaDB

LAST_INSERT_ID() did not work for me, for some reason via phpMyAdmin. last_insert_id() did work via phphMyAdmin.

Define and out parameter when creating the procedure:

OUT o_ProductId BIGINT UNSIGNED

Then set the out parameter using all lower case.

SET o_ProductId = last_insert_id(); SELECT @o_ProductId;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM