Search code examples
phpmysqlpdo

Each "Item_ID" is inserted 4 times into database


Each "Item_ID" with its data is inserted 4 times into database, here's my code:

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

I think the problem is with this line of code:

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

because quantity is changing for each one of the duplicated items but the item is the same.


Solution

  • Thanks for help everyone, Looking at my cart.php turned out I should set $_SESSION['qty_array'] with index like this:

                try {
                    $index = 0;
                    $user_id = $_SESSION['uid'];
                    $sql = "SELECT * FROM items WHERE Item_ID IN (" . implode(',', $_SESSION['cart']) . ")";
                    $query = $pdo->query($sql);
                    while($order = $query->fetch(PDO::FETCH_ASSOC)){
                            $item_id = $order['Item_ID'];
                            $price = $order['Price'];
                            $qty = $_SESSION['qty_array'][$index];
                            $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]);
                        $index ++;
                    }
                    
                } catch (PDOException $e) {
                    echo "Error: " . $e->getMessage();
                }