我有2页php:一个带有表单,一个用于将数据插入数据库。 我试图了解如何使用下面的代码将数据插入到2个不同的表中。如果我只运行一个INSERT但是有两个我无法使其工作,它确实有用。为什么?在同一个PHP页面中使用2 INSERT语句并在两个不同的表中添加信息的方法是什么?
<?php
include("../includes/connection.php");
// Escape user inputs for security
$name = mysqli_real_escape_string($link, $_POST['name']);
$email = mysqli_real_escape_string($link, $_POST['email']);
$number = mysqli_real_escape_string($link, $_POST['number']);
$device = mysqli_real_escape_string($link, $_POST['device']);
$price = mysqli_real_escape_string($link, $_POST['price']);
$payment = mysqli_real_escape_string($link, $_POST['payment']);
$status = mysqli_real_escape_string($link, $_POST['status']);
$model = mysqli_real_escape_string($link, $_POST['model']);
$problem = mysqli_real_escape_string($link, $_POST['problem']);
// attempt insert query execution
$sql = "INSERT INTO table1 (mail, number, device, price, paymenttype,status,date) VALUES ('$name', '$email', '$number', '$device', '$price', '$payment','$status',NOW())";
if(mysqli_query($link, $sql)){
// echo "Records added successfully.";
header("location:ciao.php?message=The customer has been added to the database");
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// close connection
mysqli_close($link);
$sql = "INSERT INTO table2(model, problem, device, status) VALUES ('$model', '$problem', '$device', '$status')";
if(mysqli_query($link, $sql)){
// echo "Records added successfully.";
header("location:ciao.php?message=The customer has been added to the database");
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
mysqli_close($link);
?>
答案 0 :(得分:3)
1)检查您的第一个查询语法。应该是这样的:
$sql = "INSERT INTO table1(mail, number, device, price, paymenttype,status,date) VALUES ('$name', '$email', '$number', '$device', '$price', '$payment','$status',NOW())";
2)您在第二次插入查询之前已关闭连接。
答案 1 :(得分:1)
您需要将第一个插入查询更正为
$sql = "INSERT INTO table1 (name, mail, number, device, price, paymenttype,status,date) VALUES ('$name', '$email', '$number', '$device', '$price', '$payment','$status',NOW())";
其次,在第二次插入查询之前关闭连接。只需评论关闭连接。并尝试在第二个插入中提供不同的变量名称
// mysqli_close($link);// comment this line
$sql1 = "INSERT INTO table2(model, problem, device, status) VALUES ('$model', '$problem', '$device', '$status')";
if(mysqli_query($link, $sql1)){
// echo "Records added successfully.";
header("location:ciao.php?message=The customer has been added to the database");
} else{
echo "ERROR: Could not able to execute $sql1. " . mysqli_error($link);
}
mysqli_close($link);
答案 2 :(得分:1)
您执行第一次插入时关闭了连接,当您使用第二次插入时的连接时,连接已经关闭