2011-08-09 85 views
0

我正在创建一个订单购物车。PHP - 如何做到这一点,如果?

在显示购物车的页面上,它检查存储在会话$order中的值是否与mysql表中的某一行的id相对应。如果该匹配存在,则返回相应的行。

在此过程中,我试图检索会话$quantity中存储的与表中行的id对应的数量值。

$order$quantity中的每个值都分配了一个名称,它是从中添加的项目的ID。

这是增加了为了将购物车的代码:

if (isset($_POST['action']) and $_POST['action'] == 'Order') 
{ 
// Add item to the end of the $_SESSION['order'] array 
$_SESSION['order'][$_POST['id']] = $_POST['id']; 
$_SESSION['quantity'][$_POST['id']] = $_POST['quantity']; 
header('Location: .'); 
exit(); 
} 

这是购物车页上的代码:

foreach ($order as $item) 
foreach ($quantity as $amount) 
{ 

mysql_data_seek($productsSql, 0); //<- this line, to reset the pointer for every EACH. 
while($row = mysql_fetch_assoc($productsSql)) 
{ 
    $itId = $row['id']; 
    $itDesc = $row['desc']; 
    $itPrice1 = $row['price1']; 
    if ($item == $itId) 
    { 
    $pageContent .= ' 
      <tr> 
       <td>'.$itDesc.'</td> 
       <td>'.if ($item[''.$itId.''] == $amount[''.$itId.'']) {echo $amount}.'</td> 
       <td>R'.number_format($itPrice1*$amount, 2).'</td>    
      </tr> 
';  
    } 
} 
} 

此行产生语法错误:

<td>'.if ($item[''.$itId.''] == $amount[''.$itId.'']) {echo $amount}.'</td> 

这里的初学者有什么问题?其次,我需要怎样做才能完成我面临的任务?

对此的任何输入将不胜感激!

回答

2

你可以试试吗?

<td>'.($item[$itId] == $amount[$itId] ? $amount : '').'</td> 

这是一个三元运算符,看看http://en.wikipedia.org/wiki/Ternary_operation

+0

虽然这工作被添加到购物车中的第一项。当第二件物品被添加到购物车中时,这些物品会被重复,例如,应该有两个物品,其中有四个物品,这些物品的价值混合了吗? –

+0

添加var转储时,$ $ itId的值为:string(1)“3”string(1)“3”string(1)“6”string(1)“6” –

+0

您可以尝试使用$ item [intval($ itId)]? – Lordalcol

1

你不能简单地添加这样的条件语句,而你正在构建一个字符串。

你可以这样做,但是

<td>' . ($item[$itId] == $amount[$itId]) ? $amount : null . '</td> 

,但你应该使用更清晰的方法。

您可能会遇到的另一个问题是,如果$amount是一个数组,您将无法将其打印为字符串。但是,如果$amount是ArrayAccess接口的对象,则可以使用__toString()方法打印它;但那是另一回事。

0

创建购物车页面的代码有几个问题。

  1. 您可以遍历项目和数量,这可能会给您重复的输出。
  2. $ item是一个纯字符串,所以我想知道$ item [$ itId]应该做什么?
  3. 您遍历完整的结果集几次,实际上并非必要。我真的希望“$ productSql”不是“从产品中选择*”,否则这可能会在生产模式下变得很慢。

我建议建立一个良好的SQL用于获取数据,并以此作为填充页面的基础:

// note this has SQL-injection issues, so you really need to make sure that $order contains no crap 
$productsSql = mysql_query("select * from product where id in (".join($order, ',').")"); 

// you now have a result set with all products from your order. 
while($row = mysql_fetch_assoc($productsSql)) 
{ 
$itId = $row['id']; 
$itDesc = $row['desc']; 
$itPrice1 = $row['price1']; 
// session contains the quantity array mapping ID -> Quantity, so grab it from there 
$itQuantity = $quantity[$itId]; 
// finally calculate the price 
$itPrice = number_format($itPrice1*$itQuantity, 2); 

// now you have all data for your template and can just insert it. 
// if you use double quotes you can put the $xyz into the string directly 
$pageContent .= " 
     <tr> 
      <td>$itDesc</td> 
      <td>$itQuanty</td> 
      <td>R $itPrice</td>    
     </tr> 
     ";  
}