Code/Script to Copy MySql Database

Downloads:3748 Bookmark this code Bookmark and Share
Rank : 3.13/5
Rated by : 8 user(s)
Developer:Junaid Shabbir  |   35 submission(s)
Date Uploaded:April 30,2008
Level:Intermediate
Size: 0 Bytes
Category:PHP -> Database
Developer Says:

This is a very smart script to copy a mysql database (with contents) to another database or it simply duplicates/backups a mysql database

<?
	// Change the source & destination database
	// You don't need to create the destination database, only change the name below
 
	$source_db="db1";
	$new_db="db2";
 
	mysql_connect("localhost","root","");
	mysql_select_db($source_db);	
 
	$result=mysql_query("show tables");
 
	$table_names=array();
	while($row=mysql_fetch_array($result)){
		$table_names[]=$row[0];
	}
 
	mysql_query("create database $new_db");
	mysql_select_db($new_db);
 
 
	for($i=0;$i<count($table_names);$i++){
		mysql_query("create table ".$table_names[$i]." select * from $source_db.".$table_names[$i]);
	}
 
	echo count($table_names)." tables successfully copied!";
 ?>

The above code was highlighted with Neat Highlighter


User Reviews
Adeel Fakhar
[14-Jan-2009]
#1

Nice Sharing!

Rob
[25-Dec-2008]
#2

This is only good to copy names of tables. Not the columns as well.

Mathew
[17-Jul-2008]
#3

Very nice script this! I wanted to make a copy of my database, works great

Alex
[13-Jul-2009]
#4

Very nice script this! I wanted to make a copy of my database, works great

Thomas
[26-Mar-2010]
#5

CAUTION! Does not preserve AUTO_INCREMENT attribute

Leave a Comment
Age (Required, will not be shown)
Name
Email (Required, will not be shown)
Website (Optional, starting with http://)
 
Rate this code
Poor   1 2 3 4 5   Outstanding
Are you human ?

Enter the code shown above