2013-10-15 18 views
0

編輯:下面的工作代碼!下面無法獲得multi_query()的工作

//* opens a connection to a MySQL server */ 
$mysqli = new mysqli($host, $username, $password, $database); 

/* check connection */ 
if (mysqli_connect_errno()) { 
    printf("Connect failed: %s\n", mysqli_connect_error()); 
    exit(); 
} 


$query = "INSERT INTO `test` (test1, test2) VALUES('testing','testing2222');"; 
$query .= "INSERT INTO `test` (test1, test2) VALUES('testing3333','testing44444');"; 
$query .= "INSERT INTO `test` (test1, test2) VALUES('testing5555','testing66666');"; 
$query .= "INSERT INTO `test` (test1, test2) VALUES('testing77777','testing888888');"; 
$query .= "INSERT INTO `test` (test1, test2) VALUES('testing99999','testing101010');"; 


if ($mysqli->multi_query($query)) { 
    do { 
     /* store first result set */ 
     if ($result = $mysqli->store_result()) { 
      while ($row = $result->fetch_row()) { 
       //printf("%s\n", $row[0]); 
      } 
      $result->free(); 
     } 
    /* print divider */ 
    //if ($mysqli->more_results()) { 
    // printf("-----------------\n"); 
    //} 
    } while ($mysqli->next_result()); 
} 

/* close connection */ 
$mysqli->close();   

糟糕的代碼:

我已經試過這一切可能的方式,我似乎無法得到它的工作。我注意到一個變體只有在我有一個$查詢才能輸入時纔有效。如果它有不止一個,它會失敗。

//* opens a connection to a MySQL server */ 
$mysqli = mysql_connect($host,$username,$password, $database); 



$query = "INSERT INTO `test` (test1, test2) VALUES('testing','testing2222')"; 
$query .= "INSERT INTO `test` (test1, test2) VALUES('testing3333','testing44444')"; 


if($mysqli->multi_query($query)) 
{ 
    do 
    { 

     if($result=$mysqli->store_result()) 
     { 
      while($row=$result->fetch_row()) 
      { 
       printf("%s<br/>",$row[0]); 
      } 
      $result->free(); 
     } 

     if($mysqli->more_results()) 
     { 
      print("-------------------------------<br/>"); 
     } 
     else 
     { 
      echo '<br/>'; 
     } 
    }while($mysqli->more_results() && $mysqli->next_result()); 
} 

它使連接,我只是修剪了一些代碼,以便更容易遵循。表存在,等等...也嘗試了主要的例子,逐字逐句,它似乎並沒有工作。我哪裏錯了?

+0

嘗試在您的「INSERT」語句之一中使用未存在的表來查看腳本將如何反應。我的意思是,你不應該使用沒有錯誤處理的腳本。 –

回答

1

你必須在每個陳述的末尾加上;。還總是檢查錯誤$mysqli->error。現在

查詢看起來完全一樣

INSERT INTO `test` (test1, test2) VALUES('testing','testing2222')INSERT INTO `test` (test1, test2) VALUES('testing3333','testing44444') 

這是不正確的。

+0

什麼聲明缺少一個; ?? –

+0

@BrianV。你的第一個插入。 –

+0

@BrianV。 - 這不是你的PHP代碼,它是錯誤的分號,它是SQL語句。 – andrewsi

0

您需要在每個查詢結束時使用分號。 MySQL正在等待聲明的結束。從MySQL文檔中可以看到如下內容:

一條命令不需要在一行中全部給出,所以需要多行的冗長命令不成問題。 mysql通過查找終止分號來確定語句的結束位置,而不是查找輸入行的結尾。 (換句話說,mysql的接受自由格式輸入:它收集輸入行但直到看見分號不執行它們。)

更改此:

$query = "INSERT INTO `test` (test1, test2) VALUES('testing','testing2222')"; 
$query .= "INSERT INTO `test` (test1, test2) VALUES('testing3333','testing44444')"; 

這樣:

$query = "INSERT INTO `test` (test1, test2) VALUES('testing','testing2222');"; 
$query .= "INSERT INTO `test` (test1, test2) VALUES('testing3333','testing44444');";