每个“Item_ID”被插入数据库 4 次

问题描述 投票:0回答:0

每个“Item_ID”及其数据被插入数据库 4 次,这是我的代码:

            try {
                $user_id = $_SESSION['uid'];
                $sql = "SELECT * FROM items WHERE Item_ID IN (" . implode(',', $_SESSION['cart']) . ")";
                $query = $pdo->query($sql);
                $orders = $query->fetchAll(PDO::FETCH_ASSOC);
                if ($orders > 0) {
                    foreach ($orders as $order){
                    $item_id = $order['Item_ID'];
                    $price = $order['Price'];
                    $quantity = implode(', ', $_SESSION['qty_array']);
                    $quantity_array = explode(', ', $quantity);
                    foreach ($quantity_array as $qty) {
                    $stmt = $pdo->prepare('INSERT INTO orders (user_id, item_id, name, email, phone, address, description, quantity, item_price, total_amount, payment_method) VALUES ( ? ,?, ?, ?, ?, ?, ?, ?, ?, ?, ?)');
                    $stmt->execute([$user_id, $item_id, $name, $email, $phone, $address, $description, $qty, $price , $_SESSION['total'], $payment_method]);
                    }
                } 
            }

            } catch (PDOException $e) {
                echo "Error: " . $e->getMessage();
            }

我认为问题在于这行代码:

                    $quantity = implode(', ', $_SESSION['qty_array']);
                    $quantity_array = explode(', ', $quantity);

因为每个重复项目的数量都在变化,但项目是相同的。

php mysql pdo
© www.soinside.com 2019 - 2024. All rights reserved.