I want to get patient data by user_id and also by added_by=user & self
but it shows data from other user_id bassis of "added_by"=>"self"
I know the SQL query that is:
SELECT * FROM `patients` WHERE ( `added_by` = 'user' OR `added_by` = 'self' ) AND `user_id` = '1'
but I need to know how to make query in codeigniter3
Here is my code:
public function get_all_patients_by_user($user_id)
{
$this->db->where(["added_by"=>"user","user_id"=>$user_id]);
$this->db->or_where(["added_by"=>"self","user_id"=>$user_id]);
$data = $this->db->get("patients")->result_array();
return $data;
}
Please help me to get exact code.
2
Answers
You must use group_start and group_end.
So, your method should be:
You can learn more here:
https://codeigniter.com/userguide3/database/query_builder.html?highlight=group_start#query-grouping
Your original query is generating the wrong SQL structure due to the way CodeIgniter handles
or_where
andand_where
conditions by default.To achieve the desired query structure where "added_by" is either "user" or "self" AND "user_id" is ‘1’, you should use CodeIgniter’s group_start and group_end methods to explicitly group the "added_by" conditions and then combine them with the "user_id".
This code generate the SQL query which you want.