Insert into more than 1 database:PHP

I have a table called vendor_keys.
It has 2 fields:
1. vendor_name
2. key_provided.

The Same table is inside 3 databases.And I want to insert the details into all 3 databases at once.
Following is the code to insert details into 3 databases.

<?php
header("Access-Control-Allow-Origin: *");
$vendor_name=$_POST['vendor_name'];
$key_provided=$_POST['key_provided'];
$password=$_POST['password'];

$servername = "localhost";
$username = "root"; //replace with your username
$password = ""; //replace with your password

$database1 = "db1"; //replace with your first database name
$database2 = "db2"; //replace with your second  database name
$database3 = "db3"; //replace with your third database name
$dbh1 = new mysqli($servername, $username, $password, $database1);

if($dbh1->connect_errno > 0){
die('Unable to connect to database' . $dbh1->connect_error);
}

$dbh2 = new mysqli($servername, $username, $password, $database2);
if($dbh2->connect_errno > 0){
die('Unable to connect to database' . $dbh2->connect_error);
}

$dbh3 = new mysqli($servername, $username, $password, $database3);
if($dbh3->connect_errno > 0){
die('Unable to connect to database' . $dbh3->connect_error);
}

$add_vendor="INSERT INTO `vendor_keys`(`vendor_name`, `key_provided`) VALUES ('$vendor_name','$key_provided')";

$sql1 = mysqli_query($dbh1,$add_vendor);
$sql2 = mysqli_query($dbh2,$add_vendor);
$sql3 = mysqli_query($dbh3,$add_vendor);

echo "<br>";
echo 'VENDOR ADDED SUCCESSFULLY.<br>';

?>

Leave a Reply