如何获取最后插入的ID?
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_insertzonemsg`
(IN User_Id INT(10),
IN zid INT(10),
IN update_titles VARCHAR(50),
IN textarea1s TEXT,
IN filupload1s TEXT,
IN audio1s VARCHAR(100),
OUT out_id INT(10))
BEGIN
INSERT INTO zone_message_master
**(user_id,ZoneID,update_title,textarea1,filupload1,
audio1,LastUpdate)**
VALUE
**(User_Id,zid,update_titles,textarea1s,
filupload1s,audio1s,NOW());**
SELECT **id** as **out_id**
FROM **zone_message_master** LAST_INSERT_ID();
END$$
我需要从表格out_id
zone_message_master
答案 0 :(得分:37)
您需要使用SET语句。例如 -
表:
CREATE TABLE table1(
id INT(11) PRIMARY KEY AUTO_INCREMENT,
column1 VARCHAR(10),
column2 VARCHAR(10)
);
程序的正文:
BEGIN
INSERT INTO table1(column1, column2) VALUES ('value1', 'value2');
SET out_param = LAST_INSERT_ID();
END
注意,INSERT语句中未指定ID字段。该值将自动插入;当然,此ID字段必须具有AUTO_INCREMENT选项。
答案 1 :(得分:10)
您可以借助以下代码获取上次插入ID: -
*******只需创建一个存储过程:*******
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;
此致 阿德南