PHP script to copy all data of one mysql database to other mysql database on same server

The PHP script I am going to provide you will update all the data in second database from first database. In both databases table structure should be exactly same.
The strategy we will use is we will make an array of table names data from which have to be transfered to tables in other db. Here we are assuming database name is different but table names are same in both databases. So here we go.


$dbc=@mysql_connect("localhost","dbUser","dbPass") OR die('Couldn\'t connect to MySql:'.mysql_error());
$table=array("tableonename","tabletwoname");
$j=count($table);
for($i=0;$i<$j;$i++)
{
$query="replace INTO database2name.".$table[$i]." SELECT * FROM database1name.".$table[$i];
mysql_query($query)or die("Table copy failed:".mysql_error());
echo "

$table[$i] copy done...";

}
?>

This script will copy all the data of tables specified in array of first database to the same tables in database two provided that the db user you are connected with should have access to both the databases. This script will replace the data of db1 to db2 means will delete older data in db2 if any. If you want to just copy the data from db1 to db2 without deleting the old data in db2 use keyword "insert" instead of "replace" in the query.

If you use some changes to script and use it then It will be good for me to see those optimizations so you can post back modified code through comment feature.

Posted in |