简体   繁体   中英

Can I add different data to two different tables using separate INSERT statements within nested IF statements?

I have a system where someone can place and order for multiple products, the same or different. I am storing some of the cart data (an overview of the order) to an orders table and I want to store specific item data to another table, order_item (eg quantity , product_id etc). The first query to INSERT INTO orders is working, but somehow, the second query won't INSERT INTO the second table. In order to insert into the second table, I need to find the highest id number from the orders table as well, so that this can be added to the order_item table.

Here are the SQL statements:

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();
    }
  }
}

All of the variables are named correctly, but there's no point putting them here. Maybe worth mentioning that all the variables are being taken via $_POST from another page where a form is submitted.

For finding the max id number, I have tried using MAX(id) but doesn't seem to work, maybe it's because the whole statement isn't working properly, but this definitely will work.

I think it could be a problem with how the statements are nested?

Any help would be appreciated!

 $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')";

Here you are inserting the actual string $sqlMaxID Even if you did like the below so the variable contents would be included, $sqlMaxId represents the String "select ..." and not the results of that query.

$sqlOI = "INSERT INTO order_item (order_id, product_id, quantity)
              VALUES ("  $sqlMaxId  ","  $productID  ","  $productQty ")";

Nested Ifs == the Devil. Also this needs to be done in one transaction. What would happen if two customers submit at the same time and by the time the second sql statement runs, the max ID has changed to the next customer? What you should do is create a stored procedure that will handle all of the insert logic. Your application should not know or care about how the data is organized in the database. So in your new stored procedure you can use the Output Clause to output the data you just inserted into table 1 (including the identity column) into a table variable that will contain only what was successfully inserted. You can then join to that table variable to get the ID you want for the second insert. The output clause looks like this:

DECLARE @NewItem Table(ItemID int)
insert into Table1(Some stuff)
OUTPUT Inserted.ID
INTO @NewIssue
Values(1,2,3, etc)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM