I am still on the process of learning php/mysql. just trying a piece of code to see how it works. the save function that will check if the record exist, if it does not exist, it will do INSERT, but if it do exist, it will do UPDATE. But, when I run the code, it only do INSERT when the record does not exist, but does no do UPDATE when the record do exist. I want someone to examine my code and tell me what is wrong in the code.
function save_inventory(){
extract($_POST);
$data = "";
foreach($_POST as $k =>$v){
if(!in_array($k,array('id'))){
if(!empty($data)) $data .=",";
$v = htmlspecialchars($this->conn->real_escape_string($v));
$data .= " `{$k}`='{$v}' ";
}
}
$check = $this->conn->query("SELECT * FROM `product_list` where `code` = '{$code}' and delete_flag = 0 ".(!empty($id) ? " and id != {$id} " : "")." ")->num_rows;
if($this->capture_err())
return $this->capture_err();
if($check > 0){
$resp['status'] = 'failed';
$resp['msg'] = "Product Code already exists. Code must be unique";
return json_encode($resp);
exit;
}
if(empty($id)){
$sql = "INSERT INTO `product_list` set {$data} ";
}else if(!empty($id)){
$sql = "UPDATE `product_list` set {$data} where id = '{$id}' ";
}
$save = $this->conn->query($sql);
if($save){
$cid = !empty($id) ? $id : $this->conn->insert_id;
$resp['cid'] = $cid;
$resp['status'] = 'success';
if(empty($id))
$resp['msg'] = "New Inventory successfully saved.";
else
$resp['msg'] = " Inventory successfully updated.";
}else{
$resp['status'] = 'failed';
$resp['err'] = $this->conn->error."[{$sql}]";
}
// if($resp['status'] == 'success')
// $this->settings->set_flashdata('success',$resp['msg']);
return json_encode($resp);
}
Code in the mysql query stand for product Id.