简体   繁体   English

MYSQL和PHP将LAST_INSERT_ID()保存为本地变量

[英]MYSQL & PHP Saving LAST_INSERT_ID() as a local variable

I am having some issues with storing data in database from a PHP form. 我在从PHP表单将数据存储到数据库中遇到一些问题。 The form calls a file called insert which I have copied below. 该表格调用了一个名为insert的文件,我在下面复制了该文件。 Basically, I need to store details into the table scout and save the last_insert_id() as a local variable to be used when I insert items into the table emergencyContact. 基本上,我需要将详细信息存储到表侦查中,并将last_insert_id()保存为在将项目插入表EmergencyContact中时要使用的局部变量。 Then the emergencycontacts last_insert_id() needs to be saved and then stored in the scout table. 然后,需要保存紧急联系人last_insert_id(),然后将其存储在侦查表中。 However at the moment it is not working. 但是此刻它不起作用。 I don't think I have storing/using the variable correct yet. 我认为我尚未正确存储/使用变量。

<?php
$con = mysql_connect("localhost","user","password");
if (!$con) {
    die('Could not connect: ' . mysql_error());
}
mysql_select_db("lex", $con);

mysql_query("INSERT INTO Scout (Unit_id, FirstName, SurName, DOB, Address, Telephone, School, Religion, Ethenic, Child_Doc, Doc_Phone, Allergies, Active)
VALUES ('$_POST[unitid]','$_POST[firstname]','$_POST[lastname]','$_POST[dob]','$_POST[address]','$_POST[phone]','$_POST[school]','$_POST[religion]','$_POST[ethnicidentity]','$_POST[doctorsname]','$_POST[doctorsnumber]','$_POST[health]','$_POST[radio]')");

mysql_query("SET @scout_id = LAST_INSERT_ID()");

mysql_query("INSERT INTO EmergencyContact (Scout_id, Name, Tel, Address) 
VALUES(@scout_id,'$_POST[emergencycontact]','$_POST[emergencyphone]',$_POST[emergencyaddress]')");

mysql_query("SET @emergency_id = LAST_INSERT_ID()");

mysql_close($con);
?>

use mysql_insert_id() 使用mysql_insert_id()

$idInsertLast = mysql_insert_id();

the result is the last AUTOINCREMENT id inserted from this connection/user. 结果是从此连接/用户插入的最后一个AUTOINCREMENT ID。 if you have 200 different users doing insert transactions around the same time, each will receive his/her last id, not anyone else's, even if between the time userA inserts a record and the time he/she calls mysql_insert_id(), userB and userC have inserted records of their own. 如果您有200个不同的用户同时进行插入事务,则即使在userA插入记录的时间与他/她调用mysql_insert_id(),userB和userC的时间之间,每个用户都将收到其上一个ID,而不是其他任何人的上一个ID。插入了自己的记录。

be careful not to share connections between users, as long as each user opens his/her own connection to DB, everything will be fine. 注意不要在用户之间共享连接,只要每个用户打开自己的数据库连接,一切都会好起来的。

NOTE: mysql_query and the rest of the library have been deprecated and will eventually be removed from future php versions. 注意:mysql_query和库的其余部分已被弃用,并将最终从将来的php版本中删除。

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

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