php只为单行计算价格

时间:2018-03-09 07:30:01

标签: php

我正在尝试创建购物车,可以根据商品价格和用户想要出售的价格来计算其利润。不幸的是,我不能只计算某一行。它保持计算整个项目。这是我的代码:

<?php
echo '<p><h3>Shopping Cart</h3></p>';

          if(isset($_SESSION['cart'])) {

            $total = 0;
            echo '<table>';
            echo '<tr>';
            echo '<th>Code</th>';
            echo '<th>Name</th>';
            echo '<th>Quantity</th>';
            echo '<th>Cost</th>';
            echo '<th>Sale</th>';
            echo '<th>Profit</th>';
            echo '</tr>';
            foreach($_SESSION['cart'] as $product_id => $quantity) {

            $result = $mysqli->query("SELECT product_code, product_name, product_desc, qty, price FROM products WHERE id = ".$product_id);

            if($result){
              while($obj = $result->fetch_object()) {
                $cost = $obj->price * $quantity; //work out the line cost
                $total = $total + $cost; //add to the total cost
                $sell = $_POST['sell'];
                $profit = $sell - $obj->price;
                echo '<tr>';
                echo '<td>'.$obj->product_code.'</td>';
                echo '<td>'.$obj->product_name.'</td>';
                echo '<td>'.$quantity.'&nbsp;<a class="button [secondary success alert]" style="padding:5px;" href="update-cart.php?action=add&id='.$product_id.'"> + </a>&nbsp;<a class="button alert" style="padding:5px;" href="update-cart.php?action=remove&id='.$product_id.'"> - </a></td>';
                echo '<td>'.$currency.$cost.'</td>';
                echo '<td><form action="" method="post"><input type="text" name="sell" />
       </form></td>';
                echo '<td>'.$currency.$profit.'</td>';
                echo '</tr>';
              }
            }
          }
          echo '<tr>';
          echo '<td colspan="3" align="right">Total</td>';
          echo '<td>'.$currency.$total.'</td>';
          echo '</tr>';

此外,我不确定如何定义&#34; sell&#34;表格/职位功能。 谢谢

1 个答案:

答案 0 :(得分:0)

使用您的代码,您的每个项目都会有一个sell变量:

Product1 sell
Product2 sell
Product3 sell

您应该附加产品的ID以区分它们

Product1 sell1
Product2 sell2
Product3 sell3

示例:

// assuming $_obj->product_code is a technical identifier (no spaces or special characters)
$sell = isset($_POST['sell'.$obj->product_code]) ? $_POST['sell'.$obj->product_code] : 0;
....
echo '<td><form action="" method="post"><input type="text" name="sell'.$obj->product_code.'" value="'.$sell.'" />
   </form></td>';