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

前端 未结 12 1479
一个人的身影
一个人的身影 2020-12-07 21:03

I need to copy a table from one database to another. This will be a cronjob. Which one is the best way to do it? PHP script or Shell Script. The problem with PHP, both datab

12条回答
  •  無奈伤痛
    2020-12-07 21:33

    $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

提交回复
热议问题