我正在使用 PHP 会话变量创建一个购物车,除了购物车的显示之外,一切都很好。
我编写了以下代码以将购物车的内容显示为带有图像、名称、删除按钮和 id 的表格,问题是对于购物车中的每个项目,只有 id 不同,带有图像、名称和删除按钮都是指购物车中的第一项。
我猜我需要在 foreach 循环中包含查询,但不确定如何实现这一点,因为可能我只运行一次查询,但对 PHP 来说相对较新 - 非常感谢任何人的反馈 - 尝试学习当我走的时候!
<?php
$array = explode(',', $_SESSION['cart']);
echo "<table border = '1'>";
foreach($array as $cartId) {
$ship_name = $row_ships['ship_name'];
$ship_image = $row_ships['image'];
echo "<tr>";
echo "<td><img src='images/ships/$ship_image'width='83' height='53' /> </td>";
echo "<td>$ship_name</td>";
echo "<td><a href='cart.php?action=delete&ship_id=$cartId'><img src='images/trash.png' width='31' height='42' /></a></td>";
echo "<td>$cartId</td>";
echo "</tr>";
}
echo "</table>";
?>
这里也是查询,目前位于页面顶部
<?php
if (!function_exists("GetSQLValueString")) {
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "")
{
if (PHP_VERSION < 6) {
$theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
}
$theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);
switch ($theType) {
case "text":
$theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
break;
case "long":
case "int":
$theValue = ($theValue != "") ? intval($theValue) : "NULL";
break;
case "double":
$theValue = ($theValue != "") ? doubleval($theValue) : "NULL";
break;
case "date":
$theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
break;
case "defined":
$theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
break;
}
return $theValue;
}
}
$colname_ships = "-1";
if (isset($_SESSION['cart'])) {
$colname_ships = $_SESSION['cart'];
}
mysql_select_db($database_ships, $ships);
$query_ships = sprintf("SELECT ship_id, ship_name, image FROM ship_infomation WHERE ship_id = %s", GetSQLValueString($colname_ships, "int"));
$ships = mysql_query($query_ships, $ships) or die(mysql_error());
$row_ships = mysql_fetch_assoc($ships);
$totalRows_ships = mysql_num_rows($ships);
?>