dongming6201 2019-05-03 08:09
浏览 160
已采纳

如何在PHP中添加多个项目在购物车中

i have created a cart in php, which will add item to the cart when the user clicks the add to cart button redirecting the user to the carts page. the cart is adding 1 product multiple times, but when i add another product, its increasing the quantity of the old product in cart instead of diplaying 2 products. below is my cart.php page

<?php

// Start Session
session_start();

// Application library ( with ShopingCart class )
require __DIR__ . '/library.php';

$app = new ShopingCart();

if(isset($_POST['add_to_cart']))
{
    $app->addToCart($_POST['id']);
}

if (isset($_GET['id_to_remove']) && isset($_GET['id_to_remove']) != '') {
    $app->removeProductFromCart($_GET['id_to_remove']);
}

?>


                <?php
                    if(isset($_SESSION['shopping_cart']) && count($_SESSION['shopping_cart']) > 0)
                    {
                        $entertainment = $_SESSION['shopping_cart'];

                        echo '
                                <table class="table table-hover table-bordered">
                                <thead>
                                    <tr>
                                    <th scope="col">#</th>
                                    <th scope="col">Title</th>
                                    <th scope="col">Quantity</th>
                                    <th scope="col">Price</th>
                                    <th scope="col" width="100">Action</th>
                                    </tr>
                                </thead>';

                        $item_number = 1;
                        $total = 0;
                        foreach ($entertainment as $product) {
                        echo '
                                <tbody>
                                    <tr>
                                    <th scope="row">'. $item_number .'</th>
                                    <td>' . $product['title'] . '</td>
                                    <td>'.$product['quantity'].'</td>
                                    <td>₹ '. $product['price']. '</td>
                                    <td>
                                        <a href="cart.php?id_to_remove=' . $item_number . '" class="btn btn-danger btn-sm">X</a>
                                    </td>
                                    </tr>
                                </tbody>
                           ';
                           $total += ((int)$product['price'] * $product['quantity']);
                            $item_number++;
                        }

                        echo '
                                <tr>
                                    <th colspan="4" align="right">
                                        Total:
                                    </th>
                                    <td>
                                        ₹ '. $total .'
                                    </td>
                                </tr>
                                </table>';

                    }
                    else {
                        echo '<div class="alert alert-primary" role="alert">
                              Shopping cart is empty, visit <a href="index.php" class="alert-link">products</a> page to add product into shopping cart.
                            </div>';
                    }
                ?>

below is my library.php

<?php

// load database connection script

include("database_connection.php");

/*
 * Tutorial: PHP MySQL Shopping cart
 *
 * Page: Application library
 * */

class ShopingCart
{



    protected $db;

    function __construct()
    {
        $this->db = DB();
    }

    /**
     * get products list
     *
     * @return array
     */
    public function getProducts()
    {
        $query = "SELECT *  FROM `entertainment`";
        if (!$result = mysqli_query($this->db, $query)) {
            exit(mysqli_error($this->db));
        }
        $data = [];
        if (mysqli_num_rows($result) > 0) {
            while ($row = mysqli_fetch_assoc($result)) {
                $data[] = $row;
            }
        }

        return $data;
    }

    /**
        * get given product details
        *
        * @param [integer] $id
        * @return array
        */
       public function getProductDetails($id)
       {
           $id = mysqli_real_escape_string($this->db, $id);
           $query = "SELECT *  FROM `entertainment` WHERE `id` = '$id'";
           if (!$result = mysqli_query($this->db, $query)) {
               exit(mysqli_error($this->db));
           }
           $data = [];
           if (mysqli_num_rows($result) > 0) {
               while ($row = mysqli_fetch_assoc($result)) {
                   $data['id'] = $row['id'];
                   $data['title'] = $row['title'];
                   $data['price'] = $row['vendor_price'];
                   $data['quantity'] = 1;
               }
           }

           return $data;
       }

       /**
        * Add new product into the cart
        *
        * @param [integer] $id
        * @return void
        */
       public function addToCart($id)
       {
           $product = $this->getProductDetails($id);

           $isFound = false;
           $i = 0;

           if (!isset($_SESSION['shopping_cart']) || count($_SESSION['shopping_cart']) < 1)
           {
               $_SESSION['shopping_cart'] = array(0 => $product);
           } else {

               foreach ($_SESSION['shopping_cart'] as $item) {
                   $i++;
                   foreach ($item as $key => $value) {
                       if ($key == "id" && $value == $id) {
                           array_splice($_SESSION['shopping_cart'], $i - 1, 1, array([
                               'id' => $item['id'],
                               'title' => $item['title'],
                               'price' => $item['vendor_price'],
                               'quantity' => $item['quantity'] + 1,
                           ]));
                           $isFound = true;
                       }
                   }

               }
               if ($isFound == false) {
                   array_push($_SESSION['shopping_cart'], $product);
               }
           }

       }

       /**
        * remove existing product from the cart
        *
        * @param [integer] $id
        * @return void
        */
       public function removeProductFromCart($id)
       {
           unset($_SESSION['shopping_cart'][$id - 1]);
       }


}

?>

one item is being added to the cart, and the 1 item can be added multiple times, but when i am trying to add different items, its not being added, instead the quantity of the previous item is being updated like below image

enter image description here

i need to list the items user clicks one below the other in cart. can anyone tell me how to do this? will be a great help

</div>
  • 写回答

1条回答 默认 最新

  • dongxi5423 2019-05-03 12:49
    关注

    Perhaps $_POST['id'] is everytime the same.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化