如何在同一个 php 文件中使用两个查询

How to use two queries in the same php file

是否可以从同一个 php 文件中查询两个不同的表。 如果我 运行 只有一个 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);

?>

您需要将第一个插入查询更正为

$sql = "INSERT INTO table1 (name, mail, number, device, price, paymenttype,status,date) VALUES ('$name', '$email', '$number', '$device', '$price', '$payment','$status',NOW())";

第二次在第二次插入查询之前关闭连接。只是评论密切联系。并尝试在第二个 insert

中给出不同的变量名
  //  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);

您在执行第一个插入时关闭了连接,而当您使用第二个插入的连接时连接已经关闭

1) 检查您的第一个查询语法。它应该是这样的:

$sql = "INSERT INTO table1(mail, number, device, price, paymenttype,status,date) VALUES ('$name', '$email', '$number', '$device', '$price', '$payment','$status',NOW())";

2) 您在第二次插入查询之前关闭了连接。