Fetch last inserted ID form stored procedure in MySQL

后端 未结 2 382
暗喜
暗喜 2020-12-29 21:56

How to fetch last inserted id?

CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_insertzonemsg`

   (IN User_Id INT(10),
    IN zid INT(10),
          


        
相关标签:
2条回答
  • 2020-12-29 22:31

    You need to use SET statement. For example -

    Table:

    CREATE TABLE table1(
      id INT(11) PRIMARY KEY AUTO_INCREMENT,
      column1 VARCHAR(10),
      column2 VARCHAR(10)
    );
    

    Procedure's body:

    BEGIN
      INSERT INTO table1(column1, column2) VALUES ('value1', 'value2');
      SET out_param = LAST_INSERT_ID();
    END
    

    Note, that ID field is not specified in INSERT statement. This value will be inserted automatically; and of course, this ID field must have AUTO_INCREMENT option.

    0 讨论(0)
  • 2020-12-29 22:41

    You can Get Last Insert ID with the help of following code:-

    Just create a stored Procedure:

    CREATE DEFINER=`root`@`localhost` PROCEDURE `add_enquiry`(
    IN EnquiryNo varchar(40),
    IN OpeningDate date,
    IN ClosingDate date,
    IN  CreatedOn date,
    OUT LID int(11)
    )
    
    BEGIN
    
    INSERT into `enquiries` SET `enquiry_no`=EnquiryNo ,`opening_date`=OpeningDate ,`closing_date`=ClosingDate,`created_on` =CreatedOn;
    
    SET LID = LAST_INSERT_ID();
    END    
    

    Call on PHP:

    $rs = $dbh->query('CALL add_enquiry("ENQ" ,"2016-08-19","2016-08-18", "2016-11-23",@LID)'); 
    
    $rs2 = $dbh->query("SELECT @LID as id");
    $row = $rs2->fetchObject();
    echo $row->id;
    
    0 讨论(0)
提交回复
热议问题