doushen4719 2018-02-17 13:52
浏览 158
已采纳

如何告诉php计算数据,+ / - 从数据库中获取新数字

I've been working on stock management project, everything was okay until I get in this situation where I need to tell PHP to Subtract the amount number which has been given in the row from the amount number which exists in the database. but something went wrong always and stopping the script from working .

Like if I have 20 T-shirt and I ordered 2, so php well went update the database and set the amount to 18.

Here is my code:

<?php   
    require_once 'connections/dbc.php';
    $user_name= mysqli_real_escape_string($conn, $_POST['user_name']);
    $brand_name= mysqli_real_escape_string($conn, $_POST['brand_name']);
    $product_name= mysqli_real_escape_string($conn, $_POST['product_name']);
    $amount = mysqli_real_escape_string($conn, $_POST['amount']);
    $discount= mysqli_real_escape_string($conn, $_POST['discount']);
    $total_preis= mysqli_real_escape_string($conn, $_POST['total_preis']);
    $payment_type= mysqli_real_escape_string($conn, $_POST['payment_type']);

    if(isset($_POST['orderbutton'])):
      $sql = "INSERT INTO `orders` (`order_id`, `order_date`, `user_name`, `brand_name`, `product_name`, `amount`, `discount`, `total_preis`, `payment_type`) VALUES ('', 'NOW()','$user_name','$brand_name','$product_name','$amount','$discount', '$total_preis', '$payment_type')";

    for($x = 0; $x < count($_POST['product_name']); $x++) {     
        $updateProductAmountSql = "SELECT product.amount FROM product WHERE product.product_name = ".$_POST['product_name'][$x]."";
        $updateProductAmountData = $connect->query($updateProductAmountSql);

        while ($updateProductAmountResult = $updateProductAmountData->fetch_row()) {
          $updateAmount[$x] = $updateProductAmountResult[0] - $_POST['amount'][$x];             
            // update product table
            $updateProductTable = "UPDATE product SET amount = '".$updateAmount[$x]."' WHERE product_name = ".$_POST['product_name'][$x]."";
            $connect = query($updateProductTable);
        } // while  
    }// /for amount
    endif;
?>
  • 写回答

1条回答 默认 最新

  • douxian4888 2018-02-17 18:09
    关注

    Your query and the code around is... well, a bit messy <_>

    Remove your For/while, you just need to subtract the ordered value to the stock:

    $sql2 = "UPDATE product 
        SET amount = amount - ".$amount." 
        WHERE product_name = '".$product_name."'";
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么