code to copy all tables of one mysql db to other with structure, keys and data

In my two old posts I had posted about firstly how to copy all data of one database tables to the same structured tables of second database. Then my second post had the method to copy all tables data and structure to a second database. That script was copying the data and the structure of all pages but that was not copying the keys (indexes) of first table to the second table. Here comes the modified code which now copy all tables structure, Keys and data from one table to another mysql table.




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


$result = mysql_list_tables ("database1name");
$i = 0;
while ($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());

$query0= "create table database2name.".$table[$i]." LIKE database1name.".$table[$i];

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


So in this modified PHP script we are actually using two statements to copy a table. After deleteing the table if exists we create a table using the "LIKE" statement in the create query which actually copies the table to second database with the same structure of first table. Then after that we are coping the data from the table in first db to the table in second db.

Just pick the code and play it and if you discover or implement something new feel free to post here in comments.

Posted in |