PHP SQL:如何将数据从一个html表单保存到多个数据库,或者如何自动将数据从一个数据库复制到另一个数据库

我有一个HTML表单,例如form action=form.php method=postFirst name:brinput type=text id=fname name=fnamebrLast name:brinput type=text id=lname name=lnamebrbrinput ...

我有一个HTML表单,例如

<form action="form.php" method="post">
First name:<br>
<input type="text" id="fname" name="fname">
<br>
Last name:<br>
<input type="text" id="lname" name="lname">
<br><br>
<input type="submit" value="Submit">
</form>

和form.php

<?php
$servername = "localhost";
$username = "database1";
$password = "xxxxxxxx";
$dbname = "database1";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

//escape variables for security
$fname = mysqli_real_escape_string($conn, $_POST['fname']);
$lname = mysqli_real_escape_string($conn, $_POST['lname']);

$sql = "INSERT INTO mytable (fname,lname)
VALUES ('$fname','$lname')";

if ($conn->query($sql) === TRUE) {
   echo "Successfully Saved";

    } else {
    echo "Error: Go back and Try Again ! " . $sql . "<br>" . $conn->error;
}

$conn->close();

?>

form.php将该数据保存到database1.

我希望将这些数据与database1一起保存到另一个数据库database2中.

可能吗 ??如果是,那么应该对代码进行哪些更改?

如果不可能,是否可以将数据从数据库1自动复制到数据库2?每当在database1中添加新行时,它都应自动复制到database2.

我希望相同的数据位于两个不同的数据库中.我如何实现上述任何一项?

解决方法:

从php中,您只需要创建与数据库的新连接即可.

<?php
   $servername = "localhost";
   $username = "database1";
   $password = "xxxxxxxx";
   $dbname = "database1";


   $servernameS = "localhost";
   $usernameS = "database2";
   $passwordS = "xxxxxxxx";
   $dbnameS = "database2";

   // Create connection
   $conn = new mysqli($servername, $username, $password, $dbname);
   $connS = new mysqli($servernameS, $usernameS, $passwordS, $dbnameS);

   // Check connection
  if ($conn->connect_error) {
       die("Connection failed: " . $conn->connect_error);
   }
   if ($connS->connect_error) {
       die("Connection failed: " . $connS->connect_error);
   }

   //escape variables for security
   $fname = mysqli_real_escape_string($conn, $_POST['fname']);
   $lname = mysqli_real_escape_string($conn, $_POST['lname']);

   $sql = "INSERT INTO mytable (fname,lname) 
   VALUES ('$fname','$lname')";

    if ($conn->query($sql) === TRUE) {
     echo "Successfully Saved";

    } else {
      echo "Error: Go back and Try Again ! " . $sql . "<br>" . $conn->error;
    }

    if ($connS->query($sql) === TRUE) {
     echo "Successfully Saved";

    } else {
      echo "Error: Go back and Try Again ! " . $sql . "<br>" . $connS->error;
    }
    $conn->close();
    $connS->close();

   ?>

本文标题为:PHP SQL:如何将数据从一个html表单保存到多个数据库,或者如何自动将数据从一个数据库复制到另一个数据库

基础教程推荐