2015-02-08 68 views
-4

我正在將一個數據庫表複製到具有相同模式的其他數據庫表中。我在一個數據庫中有三張表1)客戶2)訂購3)產品。 當我運行我的代碼時,它成功地將客戶表的數據複製到數據庫2的客戶表中,但是當它爲訂單表計時時,它會生成一個錯誤 您的SQL語法錯誤;檢查對應於你的MySQL服務器版本在線路附近使用「秩序」正確的語法手冊1個 我的代碼是在這裏:在其他文件SQL語法錯誤,PHP

$dbname = "db1"; 
$db1= new database_connection(); 
$link = $db1->get_connection($dbname); 

$dbname1="db2"; 
$db2=new database_connection(); 
$link1=$db2->get_connection($dbname1); 

$sql = "SHOW TABLES FROM $dbname"; 
$result = mysql_query($sql,$link); 

if (!$result) { 
    echo "DB Error, could not list tables\n"; 
    echo 'MySQL Error: ' . mysql_error(); 
    exit; 
} 
$tables= array(); 
while ($row = mysql_fetch_row($result)) { 
    array_push($tables,$row[0]); 
} 
//print_r($tables); 
$i=0; 
echo "tables = ". count($tables); 
while($i<count($tables)){ 
    echo "i= $i"; 

    $fields=array(); 
    $query="SHOW COLUMNS FROM $tables[$i]"; 
    $result = mysql_query($query,$link) or die(mysql_error($link)); 

    if (!$result) { 
     echo 'Could not run query1: ' . mysql_error(); 
     exit; 
    } 


    //fields of table 
    if (mysql_num_rows($result) > 0) { 
     while ($row = mysql_fetch_assoc($result)) { 
       array_push($fields, $row['Field']); 
       } 
      //print_r($fields); 

      $value=$db1->get_column($tables[$i],$fields,$link); 
      echo "extracted"; 
       $db2->insert_column($tables[$i],$fields,$value,$link1); 
       echo "insertrd"; 
      //print_r($value); 

    } 
    unset($fields); 
    $i = $i + 1; 
} 

功能

function get_column($table,$row,$link){ 

     $result=mysql_query("SELECT * FROM $table",$link) or die(); 
      $data=array(); 
      while($row = mysql_fetch_assoc($result)){ 
      //unset($row["0"]); //get rid of the "sorting col" 
      array_push($data,$row); //or whatever ;) 


      } 
      return $data; 

    } 
     //return $result; 
    } 
    function insert_column($table,$field,$value,$link1){ 
     $count_fields=count($value); 
     echo "count $count_fields"; 
      $j=0; 
      while ($j <$count_fields) { 
        $array=array(); 
        $array=$value[$j]; 

        $sqll= " ('".implode("', '", $array)."') "; 
        $sql="INSERT INTO $table VALUES " . ($sqll);; 
        //$sql=mysql_real_escape_string($sql); 
        echo "$sql"; 
        mysql_query($sql,$link1) or die(mysql_error()); 
        $j= $j +1; 
       }  


} 

請幫我謝謝

+1

注意'order'是一個保留字 – Strawberry 2015-02-08 13:29:54

回答

0

order是SQL中用於ORDER BY子句的保留字。所以你不能像那樣使用它。

您應該將表名更改爲其他名稱,或者每次在SQL查詢中使用此表名時都必須使用反引號。

例如,而不是

$sql="INSERT INTO $table VALUES " . ($sqll); 

不喜歡它:

$sql="INSERT INTO `$table` VALUES " . ($sqll); 

Here你必須在MySQL的保留字完整列表

+0

停止給我發癢 – Strawberry 2015-02-08 13:40:41

+0

@Strawberry ok ;-) – 2015-02-08 13:43:01