To start off, this really isn’t CodeIgniter specific. I’m having trouble grasping an idea, so anyone that knows PHP/SQL (or whatever my problem is) can jump in.
I have 2 tables, ‘Photo’ and ‘Album’.
Album columns : ID TITLE USER_ID CREATED MODIFIED
Photo columns : ID ALBUM_ID TITLE LOC CREATED MODIFIED
I’m using the query
$this->db->select('*');
$this->db->from('album');
$this->db->join('photo', 'album.id = photo.album_id');
$this->db->limit(10);
return $this->db->get();
which I think translates into
SELECT * FROM album JOIN photo ON album.id = photo.album_id LIMIT 10;
Anyways, what I don’t understand is how to display each album with the related photos.
So something like…
<div class="album">
<img src="image1" />
<img src="image2" />
</div>
<div class="album">
<img src="image3" />
</div>
Basically how do I “echo” out the correct albums and their relative images? As far as I can tell, a foreach loop is just going to write out each image without discriminating between which album the image belongs to.
Should I even be using a JOIN query?
UPDATE:
Wow, ok tilman, you are pro. Thanks a lot for the help. For anyone else referencing this, make sure you change ‘id’ in $array[$row[‘id’]][] = $row; to whatever your album id is. In my case, its album_id. My final join statement was overwriting id with album_id.
Yes, JOINing the two tables is the way to go.
I hacked up this piece of code, I hope this works for you.
We pull all the data from the db, put them in a multi-nested array, grouped by albums.
Then iterate over that array and display the final html.
Probably not the prettiest solution, but should get the job done 😉
I am using Doctrine with Codeigniter, which provides this functionality out-of-the-box, it’s called the array hydrator.
Might want to have a look at it.
Let me know if you need help setting it up.