<?php
 
include 'dbconfig.php';
 
$nama = $_POST['nama'];
 
$kode = $_POST['kode'];
 
$harga= $_POST['harga'];

$harga_beli= $_POST['harga_beli'];

$kodecab= $_POST['kodecab'];
 
$id = $_POST['id'];
 
// Create connection
 
$conn = mysqli_connect($servername, $username, $password, $dbname);
 
// Check connection
 
if (!$conn) {
 
    die("Connection failed: " . mysqli_connect_error());
 
}
 
/* grab the posts from the db */

$sqlcheck="select kode from tbl_barang where kode='".$kode."' ";
$res2 = mysqli_query($conn, $sqlcheck);
$sqlcheck2=mysqli_num_rows($res2);
 
if($sqlcheck2==0)
{
$query = "insert into tbl_barang (kode, nama, harga,harga_beli) values('".$kode."','".$nama."','".$harga."','".$harga_beli."')";
$response = mysqli_query($conn, $query) or die('Error query:  '.$query);
} 

if ($sqlcheck2>0){
 
$query = "update tbl_barang set nama='".$nama."',kode='".$kode."',harga='".$harga."',harga_beli='".$harga_beli."' where id=".$id;
$response = mysqli_query($conn, $query) or die('Error query:  '.$query);
 
}
 

 
$lid = mysqli_insert_id($conn);
 
$result["errormsg"]="Success";
 
$result["lid"]="$lid";
 
if ($sqlcheck2==0 and $id==0){
 
    echo json_encode($result);
 
}

if ($sqlcheck2>0 and $id>0){
    
     //edit data

    echo json_encode($result);
 
}
 
else{
 
    $result["errormsg"]="failed";
 
    echo json_encode($result);
 
}
 
?>
