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

时间:2019-03-05 15:07:06

标签: php mysql

当我添加我总是得到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)来检查我的输入是否正确,并且很好,所以我认为错误在这里,请帮助我

1 个答案:

答案 0 :(得分: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;