为什么我在php中的添加总是在我的数据库的列中更新2

问题描述 投票:0回答:1

当我添加我总是得到2的结果我的代码有什么问题,请检查它。表结构表名= medicines_addeds

    1   idPrimary   int(11)         No  None        
    2   qty int(11)                 Yes NULL             
    3   xdate   date                Yes NULL            
    4   created_at  timestamp           Yes NULL             
    5   edited_at   timestamp           Yes NULL            
    6   deleted_at  timestamp           Yes NULL             
    7   med_id  int(11)             Yes NULL    

表名=药品

1   idPrimary   int(11)            No   None        
2   name    varchar(191)    utf8_unicode_ci     No  None             
3   description text    utf8_unicode_ci         Yes NULL             
4   form    varchar(191)    utf8_unicode_ci     Yes NULL             
5   stocks  int(11)                 Yes NULL             
6   created_at  timestamp           Yes NULL            
7   edited_at   timestamp           Yes NULL            
8   deleted_at  timestamp           Yes NULL

if (isset($_POST['submit'])) {
    include_once('CONFIG/config.php');
    include_once('CONFIG/db.php');

    $Med_id = $_POST[medicine_id];
    $Qty = $_POST[qty];
    $Xdate = date('y-m-d', strtotime($_POST['xdate']));
    $Timestamp = date("Y-m-d H:i:s");

    if (empty($Med_id) || empty($Qty) || empty($Xdate) || empty($Timestamp)) {
        header("Location: ../added_stock.php?add=empty");
        exit();
    } 
    else {
      $sql = "INSERT INTO medicines_addeds (qty, xdate, created_at, med_id) VALUES ('$Qty', '$Xdate', '$Timestamp', '$Med_id')";
      mysqli_query($conn, $sql);
      header("Location: ../added_stock.php?add=success");
      exit();

      $sql1 = "select sum(stocks) from medicines where id = $Med_id";
      $result = mysqli_query($conn, $sql1);
      $add = $result + $Qty;

      $sql2 = "update medicines set stocks = $add where id=$Med_id";
      mysqli_query($conn, $sql2);
    }

} 
else {
    header("Location: ../MIAdd_medicine.php");
    exit();
}

我通过使用var_dump($ _ POST)检查我的输入是否是正确的,所以我认为错误在这里请帮助我

php mysql
1个回答
0
投票

在您的更新查询之前,您的选择查询应该有sum()的别名,它可以是这样的。我更喜欢准备好的声明

$sql1 = "select sum(stocks) AS total_sum from medicines where id = ?";
            $result=$conn->prepare($sql1);
             $result->bind_param("s", $Med_id);
             $result->execute();
             $result_0=$result->get_result();
             while($row=$result_0->fetch_assoc(){ 
$result_1=$row['total_sum'];
}
            $add = $result_1+$Qty;
© www.soinside.com 2019 - 2024. All rights reserved.