Php 显示会话数组中的所有项目。只显示最上面的项目
Php 显示会话数组中的所有项目。只显示最上面的项目,php,mysql,arrays,session,session-variables,Php,Mysql,Arrays,Session,Session Variables,$\u会话['cart']存储在一个数组中,我使用foreach获取$\u会话['cart']中要在我的查询中使用的所有产品id。但是,仅显示$\u会话['cart']数组的顶部,我无法找到显示会话中存储的所有产品的方法。每次我从数组中删除顶部项目时,都会显示下一个项目 代码如下: <?php $action = isset($_GET['action']) ? $_GET['action'] : ""; if ($action == 'removed') { echo "<
$\u会话['cart']
存储在一个数组中,我使用foreach
获取$\u会话['cart']
中要在我的查询中使用的所有产品id。但是,仅显示$\u会话['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' ";
进入
如果要选择多个不能使用=
运算符的记录,则应在(…)中使用
您还应该使用mysqli
函数,而不要使用mysql
,因为它已被弃用。看起来必须先分解$id(在“,”),然后在查询中选择逗号分隔字符串$id中的每个单独$id。您可能需要替换这个丑陋的构造$id=”“;foreach($_SESSION['cart']as$id){$id=$id.$id.“,”;}//删除最后一个逗号$id=rtrim($id,,”)代码>有一个电话要看和回答。我明白了。谢谢marcin!这个可以。我从来没有想过要使用内爆。你的摇滚乐手!为你竖起大拇指:)
$query = "SELECT productID, productName, productPrice FROM tblproducts WHERE productID IN (".implode(',', $_SESSION['cart'])." )";