MelusDecus
MelusDecus

Reputation: 81

codeigniter, select twice or not

I'm wondering if i would need to select (where statement) twice, if i wanted tp update a spesific user in the database.

Example,

// Add new income for the day
function add_new_income($user_id, $budget_group_id, $day, $month, $year, $income)
{

    // Check if there has been posted anything at the same day
    $this->db->where('day',$this->current_date);
    $this->db->where('month',$this->current_month);
    $this->db->where('user_id',$user_id);
    $this->db->where('budget_group_id',$budget_group_id);

    $query = $this->db->get('budget_day',1);

    // Check if something was found
    if($query->num_rows() > 0)
    {
        // If something was found, update the value
        $data = array('income_total' => $income);
        $this->db->update('budget_day',$data);
    }

}

Would this work? Or do i have to run a new "db->where" statement?

Upvotes: 0

Views: 154

Answers (2)

Naveed
Naveed

Reputation: 1221

You will have to write new where conditions for update. Better would be to store all the where conditions in array and use that array for select and update if you must.

$where = array(
    'day' => $this->current_date,
    'month' => $this->current_month,
    'user_id' => $user_id,
    'budget_group_id' => $budget_group_id
);
...
$this->db->where($where);

In your case it seems no need of two quires, you just need to run update query. You can use $this->db->affected_rows() to check if something was updated.

Upvotes: 0

Vamsi
Vamsi

Reputation: 873

You need to write where condition twice, but you can try it in single line as follows:

$this->db->where(array('day'=>$this->current_date, 'month'=>$this->current_month, 'user_id'=>$user_id, 'budget_group_id'=>$budget_group_id));

Upvotes: 1

Related Questions