簡體   English   中英

如何使用php將所有表從一個數據庫復制到另一個數據庫?

[英]How to copy all the tables from one database to another database using php?

我需要以編程方式將表的所有值從一個數據庫復制到另一個數據庫。我非常喜歡使用 php。 我如何實現這一目標?

我找到了一個特定的代碼:

$sql1 = "DELETE FROM Kunthanahali.justshawarma_aauth_groups;";
$result1 = $conn->query($sql1);

$sql2 = "INSERT INTO Kunthanahali.justshawarma_aauth_groups SELECT * FROM justshawarmapos.justshawarma_aauth_groups;";
$result2 = $conn->query($sql2);

這段代碼工作正常。但問題是我的數據庫中有大約 50 個表。有沒有辦法截斷第二個數據庫並從第一個數據庫創建表和復制值?

我知道 phpmyadmin 中有一個選項。 但我想以編程方式做到這一點。 我想實現這一點,因為我正在創建一個銷售點系統,其中銷售點系統存在於本地主機中,並且在網站上在線查看分析。我需要定期將表及其數據復制到在線數據庫。

您可以使用以下代碼實現此目的 -

 <?php
$dblink1=mysql_connect('$ip1', '$user1', '$pass1'); // connect server 1

mysql_select_db('$database1',$dblink1);  // select database 1

$dblink2=mysql_connect('$ip2', '$user2', '$pass2'); // connect server 2 

mysql_select_db('$database2',$dblink2); // select database 2

$tables = mysql_fetch_array(mysql_query("SHOW TABLES  ",$dblink1));

//$table='tabletest';

foreach($tables as $table){

    $tableinfo = mysql_fetch_array(mysql_query("SHOW CREATE TABLE $table  ",$dblink1)); // get structure from table on server 1

    mysql_query(" $tableinfo[1] ",$dblink2); // use found structure to make table on server 2

    $result = mysql_query("SELECT * FROM $table  ",$dblink1); // select all content     

    while ($row = mysql_fetch_array($result, MYSQL_ASSOC) ) {       
       mysql_query("INSERT INTO $table (".implode(", ",array_keys($row)).") VALUES ('".implode("', '",array_values($row))."')",$dblink2); // insert one row into new table
    }

}

 mysql_close($dblink1); 
 mysql_close($dblink2);

以下是 mysqli 版本 -

<?php
$dblink1=mysqli_connect('127.0.0.1', 'root', ''); // connect server 1

mysqli_select_db($dblink1,'pdb1');  // select database 1

$dblink2=mysqli_connect('127.0.0.1', 'root', ''); // connect server 2   

mysqli_select_db($dblink2,'pdb4'); // select database 2

$tables = mysqli_fetch_array(mysqli_query($dblink1,"SHOW TABLES  "));

//$table='tabletest';

foreach($tables as $table){

    $tableinfo = mysqli_fetch_array(mysqli_query($dblink1,"SHOW CREATE TABLE $table  ")); // get structure from table on server 1

    mysqli_query($dblink2," $tableinfo[1] "); // use found structure to make table on server 2

    $result = mysqli_query($dblink1,"SELECT * FROM $table  "); // select all content        

    while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC) ) {     
       mysqli_query($dblink2,"INSERT INTO $table (".implode(", ",array_keys($row)).") VALUES ('".implode("', '",array_values($row))."')"); // insert one row into new table
    }

}

 mysqli_close($dblink1); 
 mysqli_close($dblink2);

在我看來,這不是實現這一目標的方法。 完成整個數據庫的方法是使用 mysqldump 命令編寫腳本。 要備份整個數據庫,您將執行以下操作:

mysqldump --databases yourdb --password=pw | mysql -u user --password=pw otherdb

有您可能需要或想要的各種選項和設置,在這篇博文中有詳細介紹。 例如,如果您將遠程主機的 -h 參數和主機詳細信息添加到命令的命令行 mysql 部分,則這同樣適用於在 mysql 服務器之間復制數據庫。

編寫腳本后,使用 system 或exec從 PHP 運行此類腳本就很簡單了。

下面是在兩個數據庫之間遷移數據的代碼,它檢查表或列是否存在,否則創建它並插入或更新數據注意它不是大型數據庫的合適解決方案,並確保您為目標數據庫備份。

mysqli_select_db($dblink1,'db1');  // select database 1

$dblink2=mysqli_connect('127.0.0.1', 'root', ''); // connect server 2   

mysqli_select_db($dblink2,'db2'); // select database 2

$result = (mysqli_query($dblink1,"SHOW TABLES  "));
while ($row = mysqli_fetch_row($result)) {
    $tables[] = $row[0];
}
echo "Searching Table: ".$tables[0] ."<br>";
foreach ($tables as $i => $table){

    $val = mysqli_query($dblink2,"select 1 from $table  ");

    if($val !== FALSE) /***** table exists */
    {
        $structure1= get_colums($dblink1, $table);
        $structure2= get_colums($dblink2, $table);
        compare_colums($dblink1,$dblink2, $structure1, $structure2, $table );


        $result = mysqli_query($dblink1,"SELECT * FROM $table  "); // select all content        
        echo $table." Updating table.... "."<br>";
        $rowcount=mysqli_num_rows($result); 
        while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC) ) {     
            $update_string = update_query_format($row );

           mysqli_query($dblink2,"INSERT INTO $table (".implode(", ",array_keys($row)).") VALUES ('".implode("', '",array_values($row))."') 
           ON DUPLICATE KEY UPDATE $update_string "); // insert one row into new table
        }
        echo $table." Updating table Completed.... total updated: $rowcount"."<br><br><br>"; 
    }
    else
    {
        /**** table not exists */
       echo $table." Table not found "."<br>";
       echo $table." Creating table... "."<br>";
       $tableinfo = mysqli_fetch_array(mysqli_query($dblink1,"SHOW CREATE TABLE $table  ")); // get structure from table on server 1
       mysqli_query($dblink2," $tableinfo[1] "); // use found structure to make table on server 2

       $result = mysqli_query($dblink1,"SELECT * FROM $table  "); // select all content        
       echo $table." Copying table.... "."<br><br><br>"; 
       while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC) ) {     
          mysqli_query($dblink2,"INSERT INTO $table (".implode(", ",array_keys($row)).") VALUES ('".implode("', '",array_values($row))."')"); // insert one row into new table
       }
    }    


}
 mysqli_close($dblink1); 
 mysqli_close($dblink2);


 function compare_structure($table, $dblink1 , $dblink2){
            /***  Check if table exists */
            $val = mysqli_query($dblink2,"select 1 from $table  ");

            if($val !== FALSE) /***** table exists */
            {
                $structure1= get_colums($dblink1, $table);
                $structure2= get_colums($dblink2, $table);
                compare_colums($dblink1,$dblink2, $structure1, $structure2, $table );


                $result = mysqli_query($dblink1,"SELECT * FROM $table  "); // select all content        
                echo $table." Updating table.... "."<br>";
                $rowcount=mysqli_num_rows($result); 
                while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC) ) {     
                    $update_string = update_query_format($row );

                   mysqli_query($dblink2,"INSERT INTO $table (".implode(", ",array_keys($row)).") VALUES ('".implode("', '",array_values($row))."') 
                   ON DUPLICATE KEY UPDATE $update_string "); // insert one row into new table
                }
                echo $table." Updating table Completed.... total updated: $rowcount"."<br><br><br>"; 
            }
            else
            {
                /**** table not exists */
               echo $table." Table not found "."<br>";
               echo $table." Creating table... "."<br>";
               $tableinfo = mysqli_fetch_array(mysqli_query($dblink1,"SHOW CREATE TABLE $table  ")); // get structure from table on server 1
               mysqli_query($dblink2," $tableinfo[1] "); // use found structure to make table on server 2

               $result = mysqli_query($dblink1,"SELECT * FROM $table  "); // select all content        
               echo $table." Copying table.... "."<br><br><br>"; 
               while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC) ) {     
                  mysqli_query($dblink2,"INSERT INTO $table (".implode(", ",array_keys($row)).") VALUES ('".implode("', '",array_values($row))."')"); // insert one row into new table
               }
            }

}

function get_colums($dblink, $table){
    $result = mysqli_query($dblink,"SHOW COLUMNS FROM $table ");
    $columns = [];           
    if (!$result) {
        echo 'Could not run query: ' . mysql_error();
        return [];
    }
    if (mysqli_num_rows($result) > 0) {
        while ($row = mysqli_fetch_assoc($result)) {
            $columns[$row['Field']] = $row['Type'];
        }
    }

    return $columns;

}

function compare_colums( $dblink1, $dblink2,  $structure1, $structure2, $table ){

    foreach ($structure2 as $field => $type){
        if (!array_key_exists($field,$structure2)){

            $result = mysqli_query($dblink2,"ALTER TABLE cus_tbl  ADD $field $type NOT NULL ");  
            if ($result){
                echo "Table: ". $table." New Field created ".$field. " ". $type. " .... "."<br>"; 
            }
        }

    }

}

function update_query_format($row){

    $query_format = "";
    foreach ($row as $k => $v){
        $query_format .= " ".$k. " = '". $v ."',"; 
    }
   // echo strlen($query_format);exit;
   // echo substr($query_format, 0,strlen($query_format)-1); exit;
    return substr($query_format, 0, strlen($query_format)-1);

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM