phpmysqlcodeigniteractiverecordwhere-clause

PHP retrieve distinct data from database based on two rows


I have table named messages with some rows:

+---------+
| columns |
+---------+
| id      |
| from    |
| to      |
| body    |
| date    |
+---------+

What I want is to retrieve a list of users I message or users who messaged me.

public function get_users_m($where)
{
    $this->db->select('*');
    $this->db->from('messages');
    $this->db->where($where); // to = my_id or from = my_id 
    $this->db->group_by('from, to');

    return $this->db->get()->result_array();
}

I made that using Codeigniter but the problem is when I reply, for example to C, I get A (me) send message to C and C send message to A and I don't want that I want just C one time because it doesn't matter if i'm the one who sent him message or he is the one who send me the message it still the same user.


Solution

  • What about this

    public function get_users_m()
    {
        $my_id = 5; # some id
        $this->db->select('*');
        $this->db->from('messages');
        $this->db->where('from == $my_id');
        $this->db->or_where('to == $my_id'); # add this or_where Clause
        $this->db->group_by('user_id');
        $query = $this->db->get();
        $result = $query->result_array();
        return $result;
    }
    

    Check comment of Tpojka