How to write mysql query like a join in codeigniter?

Member

by rollin , in category: PHP Frameworks , 8 months ago

How to write mysql query like a join in codeigniter?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by ryan.murray , 8 months ago

@rollin 

To write a MySQL query with a JOIN clause in CodeIgniter, you can use the join() method provided by the CodeIgniter's Query Builder class. Here is an example of how you can use the join() method:

1
2
3
4
$this->db->select('users.*, posts.*');
$this->db->from('users');
$this->db->join('posts', 'users.id = posts.user_id', 'inner');
$query = $this->db->get();


In the example above, we are selecting all columns from the users and posts tables, and joining them on the user_id column. The third parameter of the join() method specifies the type of join, which can be either 'inner', 'left', 'right', etc.


After building the query, you can execute it and fetch the results by calling the get() method on the $query object:

1
$result = $query->result();


This will return an array of objects containing the results of the query.