【发布时间】:2014-08-09 18:12:23
【问题描述】:
$_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 必须首先被分解(在“,”上),然后需要在查询中选择逗号分隔字符串 $ids 中的每个单独的 $id
-
你可能想用调用
join()来替换这个丑陋的构造$ids = ""; foreach($_SESSION['cart'] as $id){ $ids = $ids . $id . ","; } //remove the last comma $ids = rtrim($ids, ','); -
看看this question 和答案。
标签: php mysql arrays session session-variables