How to copy a table from one mysql database to another mysql database

mysqldump -u user1 -ppassword1 databasename TblName | mysql -u user2 -ppassword2 anotherDatabase

It all can be done in a single command.


$L1 = mysql_connect('localhost', 'user1', 'pass1');
$DB1 = mysql_select_db('database1', $L1);   

$L2 = mysql_connect('localhost', 'user2', 'pass2');
$DB2 = mysql_select_db('database2', $L2);   

$re=mysql_query("SELECT * FROM table1",$L1);
while($i=mysql_fetch_assoc($re))
{
    $u=array();
    foreach($i as $k=>$v) if($k!=$keyfield) $u[]="$k='$v'";
    mysql_query("INSERT INTO table2 (".implode(',',array_keys($i)).") VALUES ('".implode("','",$i)."') ON DUPLICATE KEY UPDATE ".implode(',',$u),$L2) or die(mysql_error());
}

user1, pass1, database1, table1 reffers to initial table user2, pass2, database2, table2 reffers to copied table $keyfield is the primary key of table


I'd dump it. Much less complicated than anything PHP based.

mysqldump -u user1 -ppassword1 databasename > dump.sql
mysql -u user2 -ppassword2 databasename < dump.sql

MySQL reference: 4.5.4. mysqldump — A Database Backup Program


If you need to copy the table on the same server you can use this code:

USE db2;

CREATE TABLE table2 LIKE db1.table1;

INSERT INTO table2  
    SELECT * FROM db1.table1;

It's copy+pasted from here: codingforums.com

It's not my solution, but I find it useful.