简体   繁体   中英

PHP/MySQL - Mysqli - Prepared Statements - Run multiple insert statements within another select statement while loop?

I am having a problem with what I would assume is my logic behind how to deal with stored data relating to lines ordered within an e-commerce system.

I have two arrays. One array ( orderedItems ) keeps track of the various product id's relating to ordered products. The other array ( orderedItemQuantity ) keeps track of various product id's and also a quantity value of the product ordered.

So now I would like to begin inserting data into a table called order_items . This table has four columns, id (the orders id number), itemId , quantity and totalValue . So each item that has been ordered, there is a row added to this table with the information corresponding to it inserted.

Here is the code i had in mind:

// Loop through ordered items
if ($stmt = $link->prepare("
    SELECT name, price
    FROM items i
    IN (".join($_SESSION['orderedItems'], ',').")
"))
{   
    $stmt->execute();
    $stmt->bind_result($itemName, $itemPrice);
    while ($stmt->fetch())
    {
        $itemQuantity = sanitize($_SESSION['orderedItemQuantity']["$itemId"]);
        $lineTotal = number_format($itemPrice * $itemQuantity, 2);
        // Insert each item line to database \\
        $stmt2 = $link->prepare("
            INSERT INTO order_items SET
            id = ?,
            itemId = ?,
            itemQuantity = ?,
            lineValue = ?
        ");

        if (!$stmt2)
        {
            $error = "Error {$link->errno}  :  {$link->error}";
            include "$docRoot/html/main/error.html.php";
            exit();
        }
        if (!$stmt2->bind_param("iiis", $orderId, $itemId, $itemQuantity, $lineTotal))
        {
            $error = "Error {$link->errno}  :  {$link->error}";
            include "$docRoot/html/main/error.html.php";
            exit();
        }
        if (!$stmt2->execute())
        {
            $error = "Error {$link->errno}  :  {$link->error}";
            include "$docRoot/html/main/error.html.php";
            exit();
        }
        $stmt2->close();
    }
    $stmt->close();
}

However, when I try to run this I get the mysql error code 2014 : Commands out of sync; you can't run this command now. This is triggered by the if (!stmt2) clause.

Could someone possibly tell me if I am way off here and this is simply just not the way that things work. And if this is the case, could you suggest a solution for what I am trying to do.

If on the other hand this is possible, could you please explain to me why it is not working for me. Because for love nor money... It just wont, and I assume that this idea is fundamentally flawed.

Thank you for your time in reading through this and any suggestions, input, advice or knowledge that you may be willing to share!!

Sorry, but the error message you are seeing is the last of your problems here.

I have two arrays

This is plain wrong - it should be a single array.

The other array (orderedItemQuantity) keeps track of various product id's and also a quantity value of the product ordered

erm, looking at the code this seems to be a nested array.

if ($stmt = $link->prepare("
  SELECT name, price
  FROM items i
  IN (".join($_SESSION['orderedItems'], ',').")
"))

Why are you bothering with prepared statements when your splicing in literal values with no escaping?

while ($stmt->fetch()) ... $stmt2 = $link->prepare("

You should never execute SQL statements inside loops.

Working around the error message is trivial - just use a seperate database connection - but it's not going to fix the deeper issues with your code - OTOH tidying up the rest of your code should also solve the error properly.

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