2016-07-22 50 views
0

我試圖使用mysqli_multi_query函數將多行插入到同一個表中,但它只執行第一個查詢。我已經嘗試將值添加到由逗號分隔的第一個查詢的末尾,但似乎沒有任何效果。有什麼建議麼?php mysqli_multi_query()在第一個查詢後停止插入

我已經切換到準備好的語句,但仍然只插入第一個結果。我錯過了什麼嗎?

$DBConnect = mysqli_connect("localhost", "root", "", "getpressed"); 

if ($DBConnect->connect_error) { 
die("Connection failed: " . $DBConnect->connect_error); 

}

$stmt = $DBConnect->prepare("INSERT INTO orderdetails (orderID, productID, quantity) VALUES (?, ?, ?)"); 
$stmt->bind_param("iii", $orderID, $productID, $quantity); 

$orderID = $orderID; 
$productID = 1; 
$quantity = $sportShirtQuantity; 
$stmt->execute(); 

$orderID = $orderID; 
$productID = 2; 
$quantity = $sportCoatQuantity; 
$stmt->execute(); 

echo "New records created successfully"; 

$stmt->close(); 
$DBConnect->close(); 
+3

請**,請勿**使用此功能。這本質上是危險的。使用帶有佔位符值和['bind_param']的[prepared statements](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php)(http://php.net/manual/en/ mysqli-stmt.bind-param.php)將用戶數據添加到您的查詢中。你可以將它作爲一個帶有兩組值的單獨的'INSERT',或者一個準備好的'INSERT',用不同的綁定執行兩次。無論哪種方式都比你在這裏顯着更好。 – tadman

+2

在迄今爲止提供的所有愚蠢的答案中,只有正確的方式是@tadman寫的。它速度更快,很簡單,它抵抗'max_allowed_pa​​cket',它很安全。無論有人會告訴你,任何其他解決辦法都是馬糞與預先準備的陳述相比較。 –

回答

1

我在orderID上有一個主鍵索引,它不允許我使用相同的orderID插入多行。我是個白癡。感謝大家的幫助。通過tadman的建議,它可以更好地工作。

-3

刪除分號了最後陳述。該文檔指出,該方法的分號用於連接語句,而不是結束語句。

在這裏閱讀文檔:Link

$sql = "INSERT INTO orderdetails (orderID, productID, quantity) VALUES ('".$orderID."', 1, '".$sportShirtQuantity."');"; 
$sql .= "INSERT INTO orderdetails (orderID, productID, quantity) VALUES ('".$orderID."', 2, '".$sportCoatQuantity."')"; 
+0

試過,仍然沒有骰子。只插入第一行。 – kurt

+0

另外,看看你的代碼,你正在用O-O PHP混合過程PHP,試圖堅持一個約定,因爲它們不兼容。 – Groovey

-2

我改變你的代碼有點

$mysqli = new mysqli("localhost", "root", "", "getpressed"); 

if ($mysqli->connect_errno) { 
    die("Connection failed: " . $mysqli->connect_error); 
} 

$sql = "INSERT INTO orderdetails (orderID, productID, quantity) VALUES ('".$orderID."', 1, '".$sportShirtQuantity."');"; 
$sql .= "INSERT INTO orderdetails (orderID, productID, quantity) VALUES ('".$orderID."', 2, '".$sportCoatQuantity."');"; 

if ($mysqli->multi_query($sql))) { 
    echo "New records created successfully"; 
} else { 
    echo "Error: " . $sql . "<br>" . mysqli_error($mysqli); 
} 
do { 
    if ($res = $mysqli->store_result()) { 
     var_dump($res->fetch_all(MYSQLI_ASSOC)); 
     $res->free(); 
    } 
} while ($mysqli->more_results() && $mysqli->next_result()); 

我也強烈建議您使用PDO準備在未來的聲明。

+1

OP爲什麼要「嘗試這個」?一個好的答案***將總是解釋所做的事情以及爲什麼這樣做,不僅是爲了OP,還是爲了將來訪問SO。 –

相關問題