在PHP Session Shopping Cart上运行查询返回相同的行

时间:2013-07-28 07:40:44

标签: php cart shopping

我正在使用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);
?>

1 个答案:

答案 0 :(得分:0)

从你的代码中,我假设$ _SESSION ['cart'] ='1,2,3'(其中1,2,3是ship_id的)。

<?php
$query_ships = sprintf("SELECT ship_id, ship_name, image FROM ship_infomation WHERE ship_id IN (%s)", $_SESSION['cart']);
$ships = mysql_query($query_ships, $ships) or die(mysql_error());
$totalRows_ships = mysql_num_rows($ships);

echo "<table border = '1'>";
while($ship = mysql_fetch_array($ships)) {
  echo "<tr>";
  echo "<td><img src='images/ships/".$ship['image']."' width='83' height='53' /> </td>";
  echo "<td>".$ship['ship_name']."</td>";
  echo "<td><a href='cart.php?action=delete&ship_id=".$ship['ship_id']."'><img src='images/trash.png' width='31' height='42' /></a></td>";
  echo "<td>".$ship['ship_id']."</td>";
  echo "</tr>";
} 
echo "</table>";
?>