PHP - How to accomplish this if?


PHP - How to accomplish this if?

我正在创建一个订单购物车。

在显示购物车的页面上,它检查会话$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>

首先,这里的问题是什么?

其次,我需要做些什么来完成我面临的任务?

对此的任何意见都将非常感谢!

你能试试吗?

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

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

在构建字符串时不能简单地添加这样的条件语句。

你可以这样做,但是

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

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

你可能得到的另一个问题是,如果$amount是一个数组,你将无法打印它作为一个字符串。但是,如果$amount是一个具有ArrayAccess接口的对象,则可以使用__toString()方法打印它;但那是另一个故事了

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

  1. 您遍历项目和数量,这可能会产生重复的输出。
  2. $item是一个普通的字符串,所以我想知道$item[$ iid]应该做什么?
  3. 您遍历完整的结果集几次,这实际上是不必要的。我真的希望"$productSql"不是一个"select * from product",否则这可能会在生产模式下变得非常慢。

我建议创建一个好的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>
        ";      
}