0

I have a problem here I input the number of items purchased more than the stock I have, so the output is data minus example "-1" . I have the source json php below can you help me to improve my program so that I will be notified "items purchased are out of stock"

<?php
     if($_SERVER['REQUEST_METHOD']=='POST') {
        date_default_timezone_set("Asia/Jakarta");
        $timestamp = date('H:i:s');
        $tanggal = date('Y-m-d');
          $response = array();
          //mendapatkan data
        
        $id_barang = $_POST['id_barang'];
        $nm_barang = $_POST['nm_barang'];
        $stokk = $_POST['stokk'];
          $nm_pegawai = $_POST['nm_pegawai'];
         
          
        
        require_once('dbConnect.php');  
           $sql2 ="SELECT * FROM stok where id_barang='$id_barang'";
         
         $res = mysqli_query($con,$sql2);
         
         while($row = mysqli_fetch_array($res)){
         $tokavailable = $row['stokk'];
        }
        
        if( $stokavailable >=$stokk ){
             $response["value"] = 0;
               $response["message"] = "oops! Item purchased is out of stock!";
               echo json_encode($response);
            
            
        }else{
            $sql = "INSERT INTO keluar (id_barang,nm_barang,nm_pegawai,stokk,waktu,tanggal) VALUES('$id_barang','$nm_barang','$stokk','$nm_pegawai','$timestamp','$tanggal')";
              
             if(mysqli_query($con,$sql)) {
               $response["value"] = 1;
               $response["message"] = "successful buying";
               echo json_encode($response);
             } else {
               $response["value"] = 0;
               $response["message"] = "oops! try Again";
               echo json_encode($response);
             } 
        }
            
        }
           // tutup database
           mysqli_close($con);

1 Answers1

0

The problem come from your IF statement.

  1. Variable $stokavailable doesn't exist (you have a typo, you declared it as $tokavailable) so it is not possible to compare.

  2. To be out of stock, you must change your condition to

    $stokk >= $stokavailable

so you do not have enough items in your inventory...

This way, it should work ;)

Alexandre Martin
  • 1,472
  • 5
  • 14
  • 27