簡體   English   中英

顯示會話數組中的所有項目。 只顯示第一項

[英]displaying all items in session array. only the top item is showing

$_SESSION['cart']存儲在數組中,我使用foreach來獲取$_SESSION['cart']所有產品ID,以便在查詢中使用。 但是,僅顯示$_SESSION['cart']數組的頂部,我找不到顯示會話中存儲的所有產品的方法。 每次我從數組中刪除最上面的項目時,都會顯示下一個項目。

這是代碼:

<?php
$action = isset($_GET['action']) ? $_GET['action'] : "";

if ($action == 'removed') {
    echo "<div>" . $_GET['name'] . " was removed from cart.</div>";
}

if (isset($_SESSION['cart'])) {
    $ids = "";
    foreach ($_SESSION['cart'] as $id) {
        $ids = $ids . $id . ",";
    }

    //remove the last comma
    $ids = rtrim($ids, ',');

    $query = "SELECT productID, productName, productPrice FROM tblproducts WHERE productID='$ids' ";
    $result = mysql_query($query);
    $num_rows = mysql_num_rows($result);

    if ($num_rows > 0) {
        echo "<table border='0'>"; //start table

        // our table heading
        echo "<tr>";
        echo "<th class='textAlignLeft'>Product Name</th>";
        echo "<th>Price (PHP)</th>";
        echo "<th>Action</th>";
        echo "</tr>";

        //also compute for total price
        $totalPrice = 0;

        while ($row = mysql_fetch_array($result)) {

            $totalPrice += $row['productPrice'];

            //creating new table row per record
            echo "<tr>";
            echo "<td>" . $row['productName'] . "</td>";
            echo "<td class='textAlignRight'>" . $row['productPrice'] . "</td>";
            echo "<td class='textAlignCenter'>";
            echo "<a href='remove-from-cart.php?id=" . $row['productID'] . "&name=" . $row['productName']
                . "'\" class='custom-button'>";
            echo "<img src='../../images/front/removefromcart.png' title='Remove from cart' width='80' height='50' />";
            echo "</a>";
            echo "</td>";
            echo "</tr>";
        }

        echo "<tr>";
        echo "<th class='textAlignCenter'>Total Price</th>";
        echo "<th class='textAlignRight'>{$totalPrice}</th>";
        echo "<th></th>";
        echo "</tr>";

        echo "</table>";
        echo "<br /><div><a href='#' class='customButton'>Checkout</a></div>";
    } else {
        echo "<div>No products found in your cart. :(</div>";
    }
} else {
    echo "<div>No products in cart yet.</div>";
}

?>

您可能應該更改這部分代碼:

$ids = "";
foreach($_SESSION['cart'] as $id){
    $ids = $ids . $id . ",";
}

//remove the last comma
$ids = rtrim($ids, ',');

$query = "SELECT productID, productName, productPrice FROM tblproducts WHERE productID='$ids' ";

$query = "SELECT productID, productName, productPrice FROM tblproducts WHERE productID IN (".implode(',', $_SESSION['cart'])." )";

如果要選擇多個記錄,則不能使用=運算符,應使用IN (...)

您還應該使用mysqli函數而不是mysql因為它已被棄用。

暫無
暫無

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

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