我試圖將insert
多個rows
插入到我的數據庫中,依賴於數組返回的迭代次數。SQL插入多行,foreach
插入正在工作,但是插入多於一行,無論數組中有什麼。
function createOrder(){
$CustomerID = $_SESSION['CustomerID'];
$BasketID = $_SESSION['BasketID'];
// create a new entry with an OrderID
$orders = new Basket;
$orders->storeFormValues($_POST);
// Collect the OrderID returned from insertOrder(); and insert into 'Orders'
$OrderID = $orders->insertOrder($CustomerID);
// Populate OrderDetails with items in users Basket.
$data = Basket::getBasket($BasketID);
$results['basket'] = $data['results'];
// Insert the order details into the orderDetails DB.
$orders->insertOrderDetails($OrderID, $BasketID, $CustomerID, $results);
};
和環路:
public static function insertOrderDetails($OrderID, $BasketID, $CustomerID, $results){
$conn = new PDO(DB_DSN, DB_USERNAME, DB_PASSWORD);
// for each row insert into the DB
foreach ($results['basket'] as $row) {
$sql = "INSERT INTO OrderProducts (OrderID, ProductName, Price, Quantity)
VALUES (:OrderID, :ProductName, :Price, :Quantity)";
$st = $conn->prepare($sql);
$st->bindValue(":OrderID", $OrderID, PDO::PARAM_INT);
$st->bindValue(":ProductName", $row->ProductName, PDO::PARAM_STR);
$st->bindValue(":Price", $row->Price, PDO::PARAM_INT);
$st->bindValue(":Quantity", $row->Quantity, PDO::PARAM_STR);
$st->execute();
}
$conn = null;
}
和陣列,$results
看起來像;
array(1) {
["basket"]=>
array(2) {
[0]=>
object(Basket)#3 (10) {
["OrderID"]=>
NULL
["CustomerID"]=>
NULL
["OrderItemID"]=>
NULL
["ProductID"]=>
string(1) "9"
["Quantity"]=>
string(1) "4"
["ProductName"]=>
string(12) "Cheese Bagel"
["Price"]=>
string(1) "1"
["NameType"]=>
string(5) "Bagel"
["BasketProductID"]=>
string(2) "25"
["BasketID"]=>
string(1) "3"
}
[1]=>
object(Basket)#5 (10) {
["OrderID"]=>
NULL
["CustomerID"]=>
NULL
["OrderItemID"]=>
NULL
["ProductID"]=>
string(1) "2"
["Quantity"]=>
string(1) "1"
["ProductName"]=>
string(15) "The British BLT"
["Price"]=>
string(1) "3"
["NameType"]=>
string(5) "Bagel"
["BasketProductID"]=>
string(2) "26"
["BasketID"]=>
string(1) "3"
}
}
}
任何建議大大apprecaited!
什麼是你的主要和唯一的密鑰? – Legionar 2015-02-09 14:42:59
PDO默認使用「返回布爾值false」來表示失敗。你不檢查任何DB代碼中的失敗,這意味着你只是假設什麼都不會失敗。 – 2015-02-09 14:45:53
@Legionar,在'OrderProducts'中,OrderProductID是主要的,唯一的,'Orders',OrderID是主要的。 @MarcB謝謝,我計劃創建一些conidtions來檢查腳本的主要部分是否正常工作。 – atoms 2015-02-09 14:47:56