[英]Can I add different data to two different tables using separate INSERT statements within nested IF statements?
我有一個系統,有人可以放置和訂購多個相同或不同的產品。 我將一些購物車數據(訂單概述)存儲到orders
表中,我想將特定商品數據存儲到另一個表order_item
(例如quantity
, product_id
等)。 INSERT INTO orders
的第一個查詢正在運行,但不知何故,第二個查詢將不會INSERT INTO
第二個表。 為了插入第二個表,我還需要從orders
表中找到最高的id
號,這樣就可以將它添加到order_item
表中。
以下是SQL語句:
if(empty($hNum) || empty($street) || empty($city) || empty($county) || empty($postcode) || empty($country)){
header("Location: ../shop/checkout.php?error=emptyaddressfields");
exit();
}
else {
$sqlO = "INSERT INTO orders (customer_id, order_date, order_status, num_items, total_cost)
VALUES ('$customer_id', CURRENT_TIMESTAMP, 'Order Placed', '$num_items', '$total_cost')";
$stmt = mysqli_stmt_init($conn);
if(!mysqli_stmt_prepare($stmt, $sqlO)) {
header("Location: ../shop/checkout.php?error=sqlerror");
exit();
}
else { //if statement here for second sql insert
$sqlMaxId = "SELECT order_id FROM orders ORDER BY order_id DESC LIMIT 1";
$sqlOI = "INSERT INTO order_item (order_id, product_id, quantity)
VALUES ('$sqlMaxId', '$productID', '$productQty')";
$result = mysqli_stmt_init($conn);
if(!mysqli_stmt_prepare($result, $sqlOI)) {
header("Location: ../shop/checkout.php?error=sqlerror3");
}
else {
mysqli_stmt_execute($stmt);
unset($_SESSION['shopping_cart']);
header("Location: ../shop/account.php");
exit();
}
}
}
所有變量都被正確命名,但沒有必要把它們放在這里。 也許值得一提的是,所有變量都是通過$ _POST從另一個提交表單的頁面中獲取的。
為了找到最大id
號,我嘗試使用MAX(id)
但似乎沒有用,也許是因為整個語句不能正常工作,但這肯定會起作用。
我認為這可能是語句如何嵌套的問題?
任何幫助,將不勝感激!
$sqlMaxId = "SELECT order_id FROM orders ORDER BY order_id DESC LIMIT 1";
$sqlOI = "INSERT INTO order_item (order_id, product_id, quantity)
VALUES ('$sqlMaxId', '$productID', '$productQty')";
在這里插入實際的字符串$sqlMaxID
即使你喜歡下面的內容,所以包含變量內容,$ sqlMaxId表示字符串"select ..."
而不是該查詢的結果。
$sqlOI = "INSERT INTO order_item (order_id, product_id, quantity)
VALUES (" $sqlMaxId "," $productID "," $productQty ")";
嵌套的Ifs ==魔鬼。 這也需要在一次交易中完成。 如果兩個客戶同時提交並且第二個sql語句運行時,最大ID已更改為下一個客戶,會發生什么? 您應該做的是創建一個存儲過程來處理所有插入邏輯。 您的應用程序不應該知道或關心數據庫中數據的組織方式。 因此,在新的存儲過程中,您可以使用輸出子句將剛插入表1中的數據(包括標識列)輸出到一個表變量中,該表變量僅包含成功插入的內容。 然后,您可以加入該表變量以獲取第二個插入所需的ID。 輸出子句如下所示:
DECLARE @NewItem Table(ItemID int)
insert into Table1(Some stuff)
OUTPUT Inserted.ID
INTO @NewIssue
Values(1,2,3, etc)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.