PHP SQL: how to back up data on multiple databases from an html form OR how to copy data from one database to another database automatically

advertisements

I have a html form, say example

<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>

and 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();

?>

The form.php is saving that data to database1 .

I want that data to be saved to another database database2 along with database1.

Is it possible ?? If yes then what changes should be made in the code ?

If it is not possible then is it possible to copy data from database1 to database2 automatically? Whenever a new row is added in database1 then it should automatically copied to database2.

I want the same data to be in two different database. How can I achieve any of the above said ??


From php you just have to create new connection to DB.

<?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();

   ?>