简体   繁体   中英

How do I loop through an INSERT INTO statement

The problem I am having is getting the INSERT INTO Mysql statement to fire during each loop of the while statement.

It is correctly looping according to the echo coming back the correct amount of times, however the INSERT INTO is only working the 1 time.

Basically the question is: "How do I loop through this SQL INSERT statement using a PHP or SQL statement"

Thanks in advance

EDIT : Being an absolute doughnut I didn't realize I had set a primary key for the orderID, which was working all along. It was just not allowing duplication of the orderID .

Thanks for the help

<?php
if(isset($_GET['checkout']))
{
$sql="SELECT * FROM cart WHERE userID =".$_SESSION['user'];
$query= mysqli_query($conn,$sql);
while ($row = mysqli_fetch_array($query)) {
            $querys= "INSERT INTO `orderdetail`(`orderID`, `selectionID`) VALUES (LAST_INSERT_ID(),{$row['cardchoiceID']})";
              $performit = $conn->query($querys);
                echo("testing");
            }
}
?>

You could optimize the approach by inserting from a select statement (call it a "migration" from one table to another):

"INSERT INTO orderdetail(selectionID, orderID)
  SELECT selectionID,orderID FROM cart WHERE userID =".$_SESSION['user'];

Reference: Mysql Doc

Ka_lin's answer is a fine one but your order didn't store the user/cart detail? I see no relation between them

Normally the flow of cart is

  1. User add some items to the cart (cart has id)
  2. User checkout and cart become an order (generate an order id with items from the cart) with

    insert into orders(cart_id,item_id,item_qty,item_price,create_datetime) select cart_id,item_id,item_qty,item_price,now() from carts;

  3. then update cart_status to marked this cart as 'finished' to make sure we create a new cart when this user returned

    update carts set cart_status = 'ordered' where user_id = {$user_id};

  4. Go on and process the order!

===============

Edited after saw an OP comments

Maybe this way will work for you

  1. Have a order_header (store generic info - like order_type,addresses,timestamp and users) and order_detail (store items/products related info) tables
  2. Insert a carts info into order_header to generate an order_id
  3. Obtain order_id from order_header with select order_id from order_header where user = {$user_id} and status = 'new'
  4. insert item/product detail into order_detail with insert into order_detail (order_id,some columns here...) select ('{$order_id}',some columns here...) from carts where user = {$user_id};
  5. then update the cart_status to 'ordered' - that's it!

Had set orderID to primary key. cant have duplicates

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