使用带LAST_INSERT_ID()的PHP插入多个表

时间:2012-04-10 15:04:48

标签: php mysql sql

下面是我尝试过的代码,但我似乎无法做出正确的调整以使脚本正常运行。

$sql = 'INSERT INTO clients (first_name, last_name, email) VALUES('.$_POST['first_name'].', '.$_POST['last_name'].', '.$_POST['email'].')
INSERT INTO client_data (client_id, phone, zip, note) VALUES(LAST_INSERT_ID(), '.$_POST['phone'].', '.$_POST['zip'].', '.$_POST['message'].')';

mysql_query($sql) or die (mysql_error());

非常感谢任何帮助。

4 个答案:

答案 0 :(得分:3)

您无法使用mysql_query();

执行两个sql语句

使用类似的东西:

$sql = 'INSERT INTO clients (first_name, last_name, email) VALUES('.$_POST['first_name'].', '.$_POST['last_name'].', '.$_POST['email'].')';
mysql_query($sql);

$clientId = mysql_insert_id();

$sql = 'INSERT INTO client_data (client_id, phone, zip, note) VALUES('.$clientId.', '.$_POST['phone'].', '.$_POST['zip'].', '.$_POST['message'].')';

mysql_query($sql) or die (mysql_error());

阅读SQL注入以及如何预防它们。

答案 1 :(得分:0)

您应该将其分成两个单独的mysql_query来电并使用mysql_insert_id功能:

$firstName = mysql_real_escape_string($_POST["first_name"]);
$lastName = mysql_real_escape_string($_POST["last_name"]);
$email = mysql_real_escape_string($_POST["email"]);
$phone = mysql_real_escape_string($_POST["phone"]);
$zip = mysql_real_escape_string($_POST["zip"]);
$message = mysql_real_escape_string($_POST["message"]);

mysql_query("INSERT INTO clients (first_name, last_name, email) VALUES ('{$firstName}', '{$lastName}', '{$email}')") or die(mysql_error());
mysql_query("INSERT INTO client_data (client_id, phone, zip, note) VALUES ('". mysql_insert_id() ."', '{$phone}', '{$zip}', '{$message}')") or die(mysql_error());

答案 2 :(得分:0)

只需进行2次查询:

$sql_insert_clients = "INSERT INTO clients (first_name, last_name, email) VALUES(".$_POST['first_name'].", ".$_POST['last_name'].", ".$_POST['email'].")";
mysql_query($sql_insert_clients) or die (mysql_error());

$sql_insert_client_data = "INSERT INTO client_data (client_id, phone, zip, note) VALUES(".mysql_insert_id().", ".$_POST['phone'].", ".$_POST['zip'].", ".$_POST['message'].")";
mysql_query($sql_insert_client_data) or die (mysql_error());

答案 3 :(得分:-1)

你刚刚错过了分号以分割插入的

$sql = 'INSERT INTO clients (first_name, last_name, email) 
        VALUES('.$_POST['first_name'].', '.$_POST['last_name'].', '.$_POST['email'].')'."; ".' INSERT INTO client_data (client_id, phone, zip, note) VALUES(LAST_INSERT_ID(), '.$_POST['phone'].', '.$_POST['zip'].', '.$_POST['message'].')';

mysqli_multi_query($sql) or die (mysql_error());

它应该运行的SQL查询(带有虚拟内容)是

INSERT INTO clients (first_name, last_name, email) VALUES('test', 'surname', email); INSERT INTO client_data (client_id, phone, zip, note) VALUES(LAST_INSERT_ID(), 'phone', 'zip', 'message');