PHP MySQL查询插入三个不同的表

时间:2017-09-18 06:00:50

标签: php mysql

我有三个不同的表,希望一次将单个表单中的值保存到三个不同的表中。

User Table:      comment table:                user_comment     
id               id                            id    
name             comment                       u_id(fk from user table)
email            trip_id (fk from trip table)  c_id(fk from comment table)

如何一次插入所有三个表格? 迄今取得的进展

<?php

$con=mysql_connect("localhost","root","");
$db = mysql_select_db("comment", $con);


$trip = $_POST['trip'];
$name=$_POST['name'];
$email=$_POST['email'];
$title=$_POST['title'];
$comment=$_POST['comment'];

$sql="INSERT INTO comment (id, title, comment, trip_id) VALUES ('', 
'$title','$comment','$trip');
INSERT INTO user_comment (r_id) VALUES (LAST_INSERT_ID());";
$result1 = mysql_query($sql) or die(mysql_error());


 $sql2="INSERT INTO users (id, r_name, r_email) SELECT * FROM (SELECT '', 
 '$name', '$email') AS tmp WHERE NOT EXISTS (SELECT r_email FROM reviewer 
 WHERE r_email = '$email') LIMIT 1; INSERT INTO user_comment (u_id) VALUES 
 (LAST_INSERT_ID())";
 $result2 = mysql_query($sql2) or die(mysql_error());

if(mysql_affected_rows() > 0){
    echo '<div class="alert alert-success alert-dismissable">
   <a href="#" class="close" data-dismiss="alert" aria-label="close">&times 
  </a>
  Review saved
 </div>';
}
else{
    echo '<div class="alert alert-danger alert-dismissable">
  <a href="#" class="close" data-dismiss="alert" aria-label="close">&times;
  </a> You have already commented this trip!
 </div>';

2 个答案:

答案 0 :(得分:1)

MySQL不支持在单个INSERT语句中插入多表。甲骨文是我唯一知道的,奇怪的是......

INSERT INTO NAMES VALUES(...)
INSERT INTO PHONES VALUES(...)

答案 1 :(得分:0)

试试这个,只需在每个查询中添加;

$sql_query = @"
               INSERT INTO User (......) VALUES (......);
               INSERT INTO comment (......) VALUES (......);
               INSERT INTO user_comment (......) VALUES (......);
              ";