我有order_detail這樣結構的表:

order_id是order表中的外鍵。在更新級聯和洗掉級聯上。這不是自動增量。所以基本上,對于一個訂單,它可能有多個產品將插入到order_detail.
例如:
orderid = 4 有 3 個產品order_detail,product_id = 1, 2, 3。但它們有相同的 order_id (order_id = 4)。如果我只有一個產品要插入 order_detail,則可以使用 LAST_INSERT_ID() 填充 order_id。但是如果我有不止一個呢?我已經嘗試過自己的,但仍然無法正常作業。這是我的代碼
for ($i = 0; $i < count($product_id); $i ) {
$productId = $product_id[$i];
$totalProduct = $total_product[$i];
$order_detail = mysqli_query($con, "INSERT INTO order_detail (order_id, product_id,
total_product, total_price) VALUES ('LAST_INSERT_ID([$i])', '$productId', '$totalProduct',
null)")or die ("Gagal update".mysqli_error($con));
}
它回傳的訊息錯誤是這樣的:
Cannot add or update a child row: a foreign key constraint fails (`rz_shop`.`order_detail`, CONSTRAINT `order_detail_order_id_foreign_key` FOREIGN KEY (`order_id`) REFERENCES `orders` (`id`) ON DELETE CASCADE ON UPDATE CASCADE)
那么如何從 id 的order表中插入相同的 order_id ,不止一個但一次插入?我真的希望你能幫助我解決這個問題。提前致謝。
uj5u.com熱心網友回復:
order表和order_detail表是使用order_id作為外鍵的“一對多”關系,那么程序應該是:
order_detail需要自動遞增作為 ID(必需)將插入程序分為2個步驟
// Insert `order` table
mysqli_query($connection, "INSERT INTO order VALUES (....................)");
// Get Last Insert ID (order_id)
$insert_id = mysqli_insert_id($connection);
// Count your product list
$total = count($product_list);
// Loop product list
for ( $i = 0; $i < $total ; $i ) {
// Insert `order_detail` table
$sql = "INSERT INTO order (id, order_id, product_id, total_product, total_price)
VALUES (NULL, $insert_id, $product_id, $total_product, $total_price)";
mysqli_query($connection, $sql);
}
uj5u.com熱心網友回復:
根據我的代碼,我已經從這里的答案中實作了解決方案,這是解決該問題的最終代碼:
$insert_id = mysqli_insert_id($con);
for ($i = 0; $i < count($product_id); $i ) {
$productId = $product_id[$i];
$totalProduct = $total_product[$i];
$order_detail = mysqli_query($con, "INSERT INTO order_detail (order_id, product_id, total_product, total_price) VALUES ('$insert_id', '$productId', '$totalProduct', null)")or die ("Gagal update".mysqli_error($con));
}
非常感謝大家。
uj5u.com熱心網友回復:
在上面你回圈 $i 值所以每次 $i 值改變。您需要將插入 ID 存盤在單獨的變數中。像這樣
$InsId=mysqli_insert_id($conn); //assign the insert Id in variable
//$conn 你的資料庫連接變數
然后在回圈中使用 $InsId 而不是 LAST_INSERT_ID([$i])
for ($i = 0; $i < count($product_id); $i ) {
$productId = $product_id[$i];
$totalProduct = $total_product[$i];
$order_detail = mysqli_query($conn, "INSERT INTO order_detail (order_id, product_id,
total_product, total_price) VALUES ('$InsId', '$productId', '$totalProduct',
null)")or die ("Gagal update".mysqli_error($con));
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/369144.html
