tags:

views:

97

answers:

1

Hi, I need to retrieve data from two tables. the first is a list of events, the second is a list of venues.

I have a fields with the same name in both tables: events.venue (which is an ID) and venues.venue is the name of the place, say "blues bar". The tables can be joined on events.venue = venues.id.

Snippet of my model:

$this->db->select('events.*, venues.*');
        $this->db->join('venues', 'events.venue = venues.id');
        if ($date != 'all')
        {
            $this->db->where('date', $date);
        }

        if ($keyword)
        {
            $this->db->like('description', $keyword);
            $this->db->or_like('band', $keyword);
            $this->db->or_like('venue', $keyword);
            $this->db->or_like('genre', $keyword);
        }

        $Q = $this->db->get('events');
        if ($Q->num_rows() > 0)
        {
            foreach ($Q->result() as $row)
            {
                $data[] = $row;
            }
        }

        $Q->free_result();
        return $data;

Snippet of the View:

foreach ($events as $row) {
            echo    "<p>{$row->band} ({$row->genre})<br />";
            echo    "Playing at: {$row->venue}<br /></p>"; // echoes "blues bar"
//more here...
}

2 Questions: 1) Why does $row->venue echo venues.venue, instead of events.venue?

B) how can I differentiate them? eg. What if I want to echo both events.venue and venues.venue? I can probably do something like "SELECT venues.venue as name_of_the_venue", but how can I do this when I've already selected *?

A: 

Quick fix:

$this->db->select('events.col1 AS ev_col1,
                   events.col2 AS ev_col2,
                   venues.col1 AS ven_col1,
                   venues.col2 AS ven_col2);

Where col1,col2 are the columns in your tables. then use

$row->ven_col1 

to access the values.

Iraklis
this could work although with a very big table I would need to list ALL the fields. can I do something like "select all but consider venues.venue as venue_name"?
Patrick
Why dont you try it out, $this->db->select('*,venues.venue AS venue_name')
Iraklis
Iraklis - you've been faster than me! :) I was just going to post a comment to say that I had tried this: $this->db->select('events.*, venues.*, events.venue AS venue_id'); and it worked!I am not entirely sure this is the best in terms of good practice, but it works!
Patrick