簡體   English   中英

從數據庫中獲取特定產品的數量而不是 session - 購物車(PHP 和 MySQL)

[英]Get quantity of certain product from database instead of session - Shopping Cart (PHP & MySQL)

我一直在嘗試創建一個持久的基於 MySQL 的購物車應用程序,從一個基於會話的 php 購物車開始。 cart表具有結構userid | productid | quantity | postingdate userid | productid | quantity | postingdate userid | productid | quantity | postingdate 在基於會話的實現中,特定產品的數量信息存儲在$_SESSION['cart'][$row['id']]['quantity']; ; 我在從數據庫的cart表中檢索特定產品的數量信息時遇到了麻煩,因為我似乎無法找到如何提取$getquantity查詢所需的productId

$sql1 = "SELECT * FROM cart WHERE userid='$userId'"; //selects the user's cart
$query1=mysqli_query($con,$sql1);
if (!empty($query1)) {    //if the user's cart isn't empty
    while($row = mysqli_fetch_array($query1)){
        $query = mysqli_query($con,"SELECT * FROM products JOIN cart ON cart.productid=products.id 
ORDER BY cart.postingDate DESC"); //selects all the products in the current user's cart
    } 
    $totalprice=0;
    $totalqunty=0;
    if (!empty($query)) {
        while ($row = mysqli_fetch_array($query)) { //for each product
            //$quantity=$_SESSION['cart'][$row['id']]['quantity']; //SESSION IMPLEMENTATION
            $id = $row['id'];
            $quantity = mysqli_query($con,"SELECT quantity FROM cart WHERE userid='$userId' AND productid='$id'"); //MY IMPLEMENTATION, THE WRONG PART IS WITH $id
            $subtotal= $quantity*$row['productPrice']+$row['shippingCharge'];
            $totalprice += $subtotal;  
            $_SESSION['qnty']=$totalqunty+=$quantity; //SESSION IMPLEMENTATION
        }
    }
}

我試過$row['id']但它從$query返回的記錄中返回所有productid的數組,而 MySQl 似乎不接受它,而我需要$getquantity在每個productid上運行。 請不要介意它如何容易受到 SQL 注入的攻擊,因為我將在后面的階段進行介紹。

這是一個有效的解決方案:我可以選擇cart.quantity屬性(考慮productscart表的連接方式):

$sql1 = "SELECT * FROM cart WHERE userid='$userId'"; //selects the user's cart
$query1=mysqli_query($con,$sql1);
if (!empty($query1)) {    //if the user's cart isn't empty
    while($row = mysqli_fetch_array($query1)){
        $query = mysqli_query($con,"SELECT products.productImage1 , products.productName ,
                                                    products.id, cart.productId, cart.quantity as qty, products.productPrice,
                                                    products.shippingCharge  FROM products JOIN cart ON cart.productid=products.id 
ORDER BY cart.postingDate DESC"); //selects all the products in the current user's cart
    } 
    $totalprice=0;
    $totalqunty=0;
    if (!empty($query)) {
        while ($row = mysqli_fetch_array($query)) { //for each product
            $quantity=$row['qty'];
            $subtotal= $quantity*$row['productPrice']+$row['shippingCharge'];
            $totalprice += $subtotal;   
        }
    }
}

暫無
暫無

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

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