我正在开发一个购物车的结帐系统,我想使用预准备语句将购物车的详细信息插入到数据库的order_details表中,但是只插入了最后一行,而不是将所有行插入到数据库中。
//I used the block of code below to extract the cart contents, I left the curly brackets open so that I can accommodate the next block of code
```php
<?php
//initialize total
$total = 0;
if(!empty($_SESSION['cart_contents'])){
//create array of initail qty which is 1
$index = 0;
if(!isset($_SESSION['qty_array'])){
$_SESSION['qty_array'] = array_fill(0, count($_SESSION['cart_contents']), 1);
}
$sql = "SELECT * FROM products WHERE id IN (".implode(',',$_SESSION['cart_contents']).")";
$query = $conn->query($sql);
while($row = $query->fetch_assoc()){
$product_id = $row['Product_id'];
$product_name = $row['product_name'];
$product_price = $row['discount_price'];
$qty = $_SESSION['qty_array'][$index];
?>
/*this is the code that is inserting only the last data into database and I am seeking assistance on how to make it insert all the contents of the cart*
<?php
if(!empty($_SESSION['cart_contents']) &&
count($_SESSION['cart_contents']) > 0){
$subtotal = $product_price * $qty;
$order_id = $_SESSION['orderID'];
for($i=0;$i<count($row['id']);$i++){
foreach ($_SESSION["cart_contents"] as $i){
$order_id = $order_id[$i];
$product_id = $product_id[$i];
$product_name = $product_name[$i];
$product_price = $product_price[$i];
$qty = $qty[$i];
$subtotal = $subtotal[$i];}}}
if($order_id!=='' && $product_id!=='' && $product_name!=='' && $product_price!=='' && $qty!=='' && $subtotal!=='' ){
$stmt = $conn -> prepare('INSERT INTO order_details(order_id,product_id,product_name,product_price,qty,subtotal) VALUES (?,?,?,?,?,?)');
$stmt -> bind_param('issiii', $order_id, $product_id, $product_name, $product_price, $qty, $subtotal);
$stmt -> execute();
$stmt->close();
//echo '<div class="alert alert-success" role="alert">Submitted Successfully</div>';
}
?>
// this closes the opened curly bracket
<?php }?>
任何关于插入超过购物车内容最后一行的帮助将非常感谢。
1条答案
按热度按时间w80xi6nr1#
您在while循环中使用的是变量:
在每次迭代中,变量都会被更新,最后它们只包含最后一行的值。
试试这个:
然后在即将到来的foreach循环中使用**$result**。