In my Table i have four columns .
All i am doing is to rate the company (v_id) from user.
Suppose, if user one is rate the 1st Company (v_id),Again when same user rate the same Company Then rate column automatically updated. if user one wants to rate another company then a new row will be added in the table. But in my case when same user again rate the company then new row is inserted in the table.
Model
I don't know where i am doing wrong in this Model.
function ratings($insert,$id,$update,$v_id) {
// $this->db->where('id',$id);
// $this->db->where('v_id',$v_id);
// $run = $this->db->get('user_ratings');
// if ($run->num_rows() >= 1) {
// $this->db->where('id',$id);
// $this->db->update('user_ratings',$update);
// }else {
// // $this->db->set('user_id', $id);
// $this->db->insert('user_ratings',$insert);
// }
$query = $this->db->query('select id, v_id from user_ratings where id = "'.$id.'" and v_id = "'.$v_id.'"')->num_rows();
if ($query > 0) {
$this->db->query('update user_ratings set rate ="'.$update.'" where id = "'.$id.'"');
}else {
$this->db->insert('user_ratings',$insert);
}
}
Controller
function ratings() {
$id = $this->session->userdata('id');
$v_id = $this->uri->segment(3);
$insert= array (
'rate' => $this->input->post('click_val'),
'date' => date('Y-m-d H:i:s'),
'v_id' => $this->input->post('company_id'),
'id' => $this->input->post('id')
);
$update = array (
'rate' => $this->input->post('click_val'),
'date' => date('Y-m-d H:i:s'),
);
$this->Visa_mdl->ratings($value,$id,$update,$v_id);
}
Your on the right track. These simple changes should do the job.
Model
function ratings($data, $id, $v_id)
{
$query = $this->db->query("select r_id from user_ratings where id = $id and v_id = $v_id");
if($query->num_rows() > 0)
{
$data['r_id'] = $query->row()->r_id;
return $this->db
->where('id', $id)
->where('v_id', $v_id)
->update('user_ratings', $data);
}
else
{
return $this->db->insert('user_ratings', $data);
}
}
The method returns true or false to indicate the outcome.
Your controller modified to work with the above
function ratings()
{
$id = $this->session->userdata('id');
$v_id = $this->input->post('company_id');
$data = array(
'rate' => $this->input->post('click_val'),
'date' => date('Y-m-d H:i:s'),
'v_id' => $v_id,
'id' => $id
);
$this->Visa_mdl->ratings($data, $id, $v_id);
}
You have putted static value of v_id column try by replacing v_id ="2" with v_id = "'.$v_id.'" hope this will help you.
<?php
function ratings($insert,$id,$update,$v_id) {
$query = $this->db->query('select id, v_id from user_ratings where id = "'.$id.'" and v_id = "'.$v_id.'"')->num_rows();
if ($query > 0) {
$this->db->query('update user_ratings set rate ="'.$update.'" where id = "'.$id.'"');
}else {
$this->db->insert('user_ratings',$insert);
}
}