I am creating a messaging system. In which there are two type of user admin and user.
Admin can send message to all user and user can send message to admin.
I am trying to fetch,
$this->db->select("user_from,count(user_from)as total");
$this->db->from("messages");
$this->db->group_by("user_from");
$query = $this->db->get();
return $query->result_array();
$this->db->select("*");
$this->db->from("messages");
$this->db->where("user_to","admin");
$query = $this->db->get();
return $query->result_array();
In single both the query work correctly.
I want to include both query in one.
I want to run multiple select query using single where clause which show the last message send by user to admin.
can anyone give me any idea?
Your Controller
$this->db->where("user_to","admin");
$this->db->group_by("user_from");
$query = $this->db->get('messages');
$data['result'] = $query->result_array(); // Your Result Array
$data['total'] = $query->num_rows(); // total number of records
// You can pass $data in any view file here
Your View
print_r($result); // result array
echo $total; // total number of records
You can use below query
$this->db->select("messages.*,count(messages.user_from) as total");
$this->db->from("messages");
$this->db->group_by("messages.user_from");
$this->db->order_by("messages.user_from","DESC");
$this->db->where("messages.user_to","admin");
$query = $this->db->get();
return $query->result_array();
$this->db->select("*,user_from,count(user_from)as total");
$this->db->from("messages");
$this->db->group_by("user_from");
$this->db->where("user_to","admin");
$query = $this->db->get();
return $query->result_array();
To get the last message, use subquery like :
select message from messages where id = (select max(id) from messages where user_to = 'admin')
Test the query in MySql and if you get the result you want, you can go to codeigniter.
In Codeigniter:
$this->db->select('message')->from('messages');
$this->db->where('id = (SELECT max(id) FROM messages where user_to = 'admin')', NULL, FALSE);
Please correct the use of single quotes in above query as its demo only.
$this->db->select("*,user_from,count(user_from)as total");
$this->db->from("messages");
$this->db->group_by("user_from");
$this->db->where("user_to","admin");
$query = $this->db->get();
return $query->result_array();
I have solved my problem.
Modal
function AdminMessages($user)
{
$sql = "select * from messages where id in (select max(id) from messages GROUP BY user_from ) AND user_to='".$user."' order by id desc";
$query = $this->db->query($sql);
//echo $this->db->last_query();
return $query->result_array();
}
function UserMessages($user)
{
$sql = "select * from messages where id in (select max(id) from messages GROUP BY user_to ) AND user_to='".$user."' order by id desc";
$query = $this->db->query($sql);
//echo $this->db->last_query();
return $query->result_array();
}