PHP code to copy data and structure of one mysql database to other

If you are looking for to develop PHP script which can copy all data and structure of all tables of first database to other database you are on right place. Previously I had posted a script with ability to copy all data of first mysql db to other mysql db with same table structure. But now this script update both data and structure of tables in destination database. Script do not remove or change any additional tables in destination db it just pick all tables of source db to destination db or if they exist in destination db script update their data and structure.

$dbc=@mysql_connect("localhost","dbUser","dbPass") OR die('Couldn\'t connect to MySql:'.mysql_error());


$result = mysql_list_tables ("database1name");
$i = 0;
while ($i < mysql_num_rows ($result))
{
$table[$i] = mysql_tablename ($result,$i);
$i++;
}


$j=count($table);
for($i=0;$i<$j;$i++)
{

$qry="drop table if exists database2name.".$table[$i];
mysql_query($qry)or die("Failed to delete:".mysql_error());

$query="CREATE TABLE database2name.".$table[$i]." SELECT * FROM database1name.".$table[$i];
mysql_query($query)or die("Table copy failed:".mysql_error());
echo "$table[$i] copy done...";
}
?>


So script actually works in a way that it picks list of tables in first db the delete those tables from second db then recreate them in second db. Thats it.

If you change or optimize the code to use I will be happy to see an update from you through comment.

Posted in |