简体   繁体   English

如何通过 php 中的存储过程获取 LAST_INSERT_ID

[英]how to get LAST_INSERT_ID via stored procedure in php

say i have a stored procedure in mysql like below说我在mysql中有一个存储过程,如下所示

-- ----------------------------
-- 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我可以毫无问题地从 php 调用它

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

but it only returns 1 for each successful insert.但它只为每个成功的插入返回 1。 i guess it is saying 1 row affected!我想这是说 1 行受影响!

i want it to return LAST_INSERT_ID我希望它返回LAST_INSERT_ID

how to do it?怎么做? by the way i don't want to add any OUT parameter.顺便说一句,我不想​​添加任何 OUT 参数。 mysql_insert_id returns 0 mysql_insert_id 返回 0

You can get last insert id like this in SP: 你可以在SP中获得这样的最后一个插入ID:

DECLARE LID int;

SET LID = LAST_INSERT_ID();

10.4.22-MariaDB 10.4.22-MariaDB

LAST_INSERT_ID() did not work for me, for some reason via phpMyAdmin. LAST_INSERT_ID() 对我不起作用,出于某种原因,通过 phpMyAdmin。 last_insert_id() did work via phphMyAdmin. last_insert_id() 确实通过 phphMyAdmin 工作。

Define and out parameter when creating the procedure:创建过程时定义和输出参数:

OUT o_ProductId BIGINT UNSIGNED OUT o_ProductId BIGINT UNSIGNED

Then set the out parameter using all lower case.然后使用全部小写设置 out 参数。

SET o_ProductId = last_insert_id(); SET o_ProductId = last_insert_id(); SELECT @o_ProductId;选择@o_ProductId;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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