使用 PHP 在购物车中显示商品列表

Display item list in shopping cart using PHP

我尝试使用 foreach 循环连接到我的数据库并在列表中显示已添加到购物车的产品。每个产品都有一个产品 ID,它可以正常工作并通过 cart.php 存储在会话变量中。我无法弄清楚如何连接到数据库以显示所收集的有关所添加产品的信息 - 我也尝试过 var_dump $SESSION['cart'] 并打印出 null 甚至在 cart.php.

中使用 "Add" 按钮后
<div class="row">
    <h4>Shopping Cart</h4>
            <?php

            foreach($_SESSION['cart'] as $proid => $proq) {

                // $proid is product id and $proq is quantity
                // use $proid to select the product detail from database

                }
            ?>
</div>
    <!--Below is my cart.php page-->
    <?php
    session_start();

    $productID = $_GET['product'];
    $action = $_GET['action'];

    switch($action) {

    case "add":
    $_SESSION['cart'][$productID]++;
    break;

    case "remove":
    $_SESSION['cart'][$productID]--;
    if($_SESSION['cart'][$productID] == 0) unset($_SESSION['cart'][$productID]);
    break;

    case "empty":
    unset($_SESSION['cart']);
    break;
    }
    header("Location: browse.php");


    ?>

根据您的解释,您正在尝试从会话值中检索数据以填充数据库查询。

但是,当您的 for 循环执行时,您还没有将会话数据反序列化到内存中(因此无法访问它并且您得到 null 值)。

您需要在 for 循环之前开始会话:

session_start();
foreach($_SESSION['cart'] as $proid => $proq) {

请在php manual

中查看更多信息

此外,如果需要,您可以配置 PHP 以自动启动会话(请参阅上面链接的手册中的更多详细信息),但是请记住,即使在没有的页面上,这也会对性能产生影响依赖会话数据。

产品视图(index.php)

<?php
    //current URL of the Page. cart_update.php redirects back to this URL
    $current_url = base64_encode($url="http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);

    $results = $mysqli->query("SELECT * FROM products");
    if ($results) { 

        //fetch results set as object and output HTML
        while($obj = $results->fetch_object())
        {
            echo '<div class="product">'; 
            echo '<form method="post" action="update_cart.php">';
            echo '<div class="product-content">';
            echo '<div class="product-info">';
            echo 'Price '.$currency.$obj->price.' | ';
            echo 'Qty <input type="text" name="product_qty" value="1" size="3" />';
            echo '<button class="add_to_cart">Add To Cart</button>';
            echo '</div></div>';
            echo '<input type="hidden" name="product_code" value="'.$obj->product_code.'" />';
            echo '<input type="hidden" name="type" value="add" />';
            echo '<input type="hidden" name="return_url" value="'.$current_url.'" />';
            echo '</form>';
            echo '</div>';
        }

    }
    ?>

更新购物车(Update_cart.php)

//add item in shopping cart
if(isset($_POST["type"]) && $_POST["type"]=='add')
{
    $product_code   = filter_var($_POST["product_code"], FILTER_SANITIZE_STRING); //product code
    $product_qty    = filter_var($_POST["product_qty"], FILTER_SANITIZE_NUMBER_INT); //product code
    $return_url     = base64_decode($_POST["return_url"]); //return url

    ySqli query - get details of item from db using product code
    $results = $mysqli->query("SELECT product_name,price FROM products WHERE product_code='$product_code' LIMIT 1");
    $obj = $results->fetch_object();

    if ($results) { //we have the product info 

        //prepare array for the session variable
        $new_product = array(array('name'=>$obj->product_name, 'code'=>$product_code, 'qty'=>$product_qty, 'price'=>$obj->price));

        if(isset($_SESSION["products"])) //if we have the session
        {
            $found = false; //set found item to false

            foreach ($_SESSION["products"] as $cart_itm) //loop through session array
            {
                if($cart_itm["code"] == $product_code){ //the item exist in array

                    $product[] = array('name'=>$cart_itm["name"], 'code'=>$cart_itm["code"], 'qty'=>$product_qty, 'price'=>$cart_itm["price"]);
                    $found = true;
                }else{
                    //item doesn't exist in the list, just retrive old info and prepare array for session var
                    $product[] = array('name'=>$cart_itm["name"], 'code'=>$cart_itm["code"], 'qty'=>$cart_itm["qty"], 'price'=>$cart_itm["price"]);
                }
            }

            if($found == false) //we didn't find item in array
            {
                //add new user item in array
                $_SESSION["products"] = array_merge($product, $new_product);
            }else{
                //found user item in array list, and increased the quantity
                $_SESSION["products"] = $product;
            }

        }else{
            //create a new session var if does not exist
            $_SESSION["products"] = $new_product;
        }

    }

    //redirect back to original page
    header('Location:'.$return_url);
}

查看购物车(View_cart.php)

 <?php
    $current_url = base64_encode($url="http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
    if(isset($_SESSION["products"]))
    {
        $total = 0;
        echo '<form method="post" action="checkout.php">';
        echo '<ul>';
        $cart_items = 0;
        foreach ($_SESSION["products"] as $cart_itm)
        {
           $product_code = $cart_itm["code"];
           $results = $mysqli->query("SELECT product_name,product_desc, price FROM products WHERE product_code='$product_code' LIMIT 1");
           $obj = $results->fetch_object();

            echo '<li class="cart-itm">';
            echo '<span class="remove-itm"><a href="cart_update.php?removep='.$cart_itm["code"].'&return_url='.$current_url.'">&times;</a></span>';
            echo '<div class="p-price">'.$currency.$obj->price.'</div>';
            echo '<div class="product-info">';
            echo '<h3>'.$obj->product_name.' (Code :'.$product_code.')</h3> ';
            echo '<div class="p-qty">Qty : '.$cart_itm["qty"].'</div>';
            echo '<div>'.$obj->product_desc.'</div>';
            echo '</div>';
            echo '</li>';
            $subtotal = ($cart_itm["price"]*$cart_itm["qty"]);
            $total = ($total + $subtotal);

            echo '<input type="hidden" name="item_name['.$cart_items.']" value="'.$obj->product_name.'" />';
            echo '<input type="hidden" name="item_code['.$cart_items.']" value="'.$product_code.'" />';
            echo '<input type="hidden" name="item_desc['.$cart_items.']" value="'.$obj->product_desc.'" />';
            echo '<input type="hidden" name="item_qty['.$cart_items.']" value="'.$cart_itm["qty"].'" />';
            $cart_items ++;

        }
        echo '</ul>';
        echo '<span class="check-out-txt">';
        echo '<strong>Total : '.$currency.$total.'</strong>  ';
        echo '</span>';
        echo '</form>';

    }

    ?>

Need remove product from cart

在更新购物车中使用它 (update_cart.php)

//remove item from shopping cart
if(isset($_GET["removep"]) && isset($_GET["return_url"]) && isset($_SESSION["products"]))
{
    $product_code   = $_GET["removep"]; //get the product code to remove
    $return_url     = base64_decode($_GET["return_url"]); //get return url


    foreach ($_SESSION["products"] as $cart_itm) //loop through session array var
    {
        if($cart_itm["code"]!=$product_code){ //item does,t exist in the list
            $product[] = array('name'=>$cart_itm["name"], 'code'=>$cart_itm["code"], 'qty'=>$cart_itm["qty"], 'price'=>$cart_itm["price"]);
        }

        //create a new product list for cart
        $_SESSION["products"] = $product;
    }

    //redirect back to original page
    header('Location:'.$return_url);
}

创建数据库连接

<?php

$db_username = 'root';//username
$db_password = '';//password
$db_name = '';//database name
$db_host = 'localhost';//your host
$mysqli = new mysqli($db_host, $db_username, $db_password,$db_name);
?>

> Important Use this in every page

<?php
    error_reporting(0);
    include("config.php");
    session_start();
?>