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 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化