YMSmash
YMSmash

Reputation: 65

How do I transfer newly added rows in an SQL Server table to an identical MySQL table using PHP?

Basically, I have two identical tables in SQL Server and MySQL. I want to use PHP in such a way that I'll only have to manually insert new values in one of them. I want to make a PHP code where the newly inserted values in the SQL Server table will also be inserted in its identical counterpart in MySQL with the press of a button.

For example, I have a table named "Customers" in both SQL Server and MySQL with the rows "ID (auto incremented)", Name, and Address. I insert new values into those columns in SQL Server. How do I make it so that I'll only have to press a button made in PHP so that I won't have to do the whole "insert into" process again in MySQL?

Any ideas are much appreciated!

Upvotes: 0

Views: 64

Answers (1)

Budimir Skrtic
Budimir Skrtic

Reputation: 419

According to new information given in the comments, I'm changing my answer and adjusting the code.

Code example:

<?php
 $serverName = "server"; //serverName\instanceName
 $connectionInfo_mssql = array("Database"=>"DB", "UID"=>"username", "PWD"=>"password","CharacterSet"=>"UTF-8");
 $conn_mssql = sqlsrv_connect($serverName, $connectionInfo_bi);
 $conn_mysql = new mysqli("server", "username", "password", "db");

//SELECT FROM MS SQL DB
$mssql_array = array();
$ms_sql = "SELECT column_names FROM db_table";
$mssql_query = sqlsrv_query($conn_mssql , $ms_sql);
while($row = sqlsrv_fetch_array($mssql_query) {
  $mssql_array[] = array('name' => $row['name'],
                         'adress' => $row['adress']);
}

foreach($mssql_array as $key => $value) {

   //SELECT FROM MySQL DB
   $my_sql = "SELECT column_names FROM db_table WHERE name = '".$value['name']."' AND adress = '".$value['adress']."'";
   $mysql_query = mysqli_query($conn_mysql , $my_sql);
   $num_rows = mysqli_num_rows($mysql_query);

   if ($num_rows == 0) {
     //Insert in MySQL DB
     $sql = "INSERT INTO db_table (db_columns) VALUES (variables_from_array)";
     $sql_query = mysqli_query($conn_mysql, $sql);
   } else {
     //There is a record in DB, and maybe you want to update it. If not, then lose this else part.
   }

}

echo 'Table Customers from MS SQL DB and table Customers from MySQL DB are now synced!';

?>

Upvotes: 1

Related Questions