Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get LAST_INSERT_ID via stored procedure in php

Tags:

mysql

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

like image 864
MD TAHMID HOSSAIN Avatar asked Dec 27 '22 00:12

MD TAHMID HOSSAIN


1 Answers

You can get last insert id like this in SP:

DECLARE LID int;

SET LID = LAST_INSERT_ID();
like image 88
Nono Avatar answered Feb 23 '23 18:02

Nono