views:

391

answers:

3

How can I select rows from two or more tables?

I'm setting default fields for a form, and I need values from two tables...

My current code reads:

    $this->CI->db->select('*');
    $this->CI->db->from('user_profiles');
    $this->CI->db->where('user_id' , $id);
    $user = $this->CI->db->get();
    $user = $user->row_array();
    $this->CI->validation->set_default_value($user);
A: 
$SqlInfo="select a.name, b.data fromtable1 a, table2 b where a.id=b.a_id;
$query = $this->db->query($SqlInfo);

try this way, you can add a third table named as c and add an 'and' command to the sql command.

aleo
I'm a major noob. Can you explain this a bit more?
Kevin Brown
A: 

Just add the other table to the "->from()" method. Something like:

 $this->db->select('t1.field, t2.field2')
          ->from('table1 AS t1, table2 AS t2')
          ->where('t1.id = t2.table1_id')
          ->where('t1.user_id', $user_id);
Favio
That will produce broken syntax.
Phil Sturgeon
Not on my end. Can you elaborate?
Favio
+1  A: 

The example in the User Guide should explain this:

$this->db->select('*'); // <-- There is never any reason to write this line!
$this->db->from('blogs');
$this->db->join('comments', 'comments.id = blogs.id');

$query = $this->db->get();

// Produces:
// SELECT * FROM blogs
// JOIN comments ON comments.id = blogs.id

See the whole thing under Active Record page in the User Guide.

Phil Sturgeon