CodeIgniter Forums
Simple sql question from two tables - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Archived Discussions (https://forum.codeigniter.com/forumdisplay.php?fid=20)
+--- Forum: Archived Development & Programming (https://forum.codeigniter.com/forumdisplay.php?fid=23)
+--- Thread: Simple sql question from two tables (/showthread.php?tid=44467)



Simple sql question from two tables - El Forum - 08-15-2011

[eluser]Unknown[/eluser]
Hello,
I'm trying to get data from a normal question with db->query. I have this question

$data['query'] = $this->db->query("SELECT table1.id, table1.name, table2.id, table2.name
FROM table1, table2
WHERE table1.table2_id = table.id");

The query gives the right results when I test them in mysql prompt but I can only get name and id from one of the tables. I cannot get for exampe table2.name only name ($row->name but not $row->table2.name).

Are there any one who can help me?

I'm using db->query because I am more used to write normal sql questions. If anyone can give me an explanation why to use codeignitors way to solve this (and how in that case).

/Pelle


Simple sql question from two tables - El Forum - 08-15-2011

[eluser]bubbafoley[/eluser]
you'll need to alias the fields

Code:
$data[‘query’] = $this->db->query(“SELECT table1.id AS id1, table1.name AS name1, table2.id AS id2, table2.name AS name2
        FROM table1, table2
        WHERE table1.table2_id = table.id”);

then you can get the data out of the result rows like
Code:
$row->id1
$row->name1
$row->id2
$row->name2



Simple sql question from two tables - El Forum - 08-15-2011

[eluser]Unknown[/eluser]
It worked exactly as I wanted - thank you very much!