簡體   English   中英

使用PHP在購物車中顯示商品清單

[英]Display item list in shopping cart using PHP

通過foreach循環,我試圖連接到數據庫並在列表中顯示已添加到購物車的產品。 每個產品都有一個產品ID,該ID可以正常工作並通過cart.php存儲在會話變量中。 我無法弄清楚如何連接到數據庫以顯示有關所添加產品的信息-我也嘗試做var_dump $ SESSION ['cart'],即使在cart.php使用“添加”按鈕后,其打印結果null cart.php

<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");


    ?>

對於產品視圖(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>';

    }

    ?>

需要從購物車中移除產品

在更新購物車(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();
?>

根據您的解釋,您試圖從會話值中檢索數據以填充數據庫查詢。

但是,當您的for循環執行時,您尚未將會話數據反序列化到內存中(因此無法對其進行訪問,並且會獲得null值)。

您需要在for循環之前啟動會話:

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

請在php手冊中查看更多信息

另外,您可以將PHP配置為在需要時自動啟動會話(請參見上面鏈接的手冊中的更多詳細信息),但是請記住,即使在不依賴會話數據的頁面上,這也會對性能產生影響。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM