2

This is my query:

$query = $this->db->query('
    SELECT archives.id, archives.signature, type_of_source.description, media_type.description, origin.description 
    FROM archives, type_of_source, media_type, origin                                                             
    WHERE archives.type_of_source_id = type_of_source.id                                                          
    AND type_of_source.media_type_id = media_type.id                                                              
    AND archives.origin_id = origin.id                                                                            
    ORDER BY archives.id ASC
');

But how to output the result? This works, but only gets the last description (origin.description):

foreach ($query->result_array() as $row)
{
    echo $row['description'];
}

This doesn't work:

foreach ($query->result_array() as $row)
{
    echo $row['type_of_source.description'];
}

Or should I rename the columns (e.g. type_of_source_description)?

3 Answers 3

5

This actually has very little to do with CodeIgniter and a lot with how mysql_fetch_assoc provides the query results.

The solution is that you should rename the columns inside the query using "AS", e.g.

select type_of_source.description as type_of_source_description, origin.descripotion as origin_descripotion from ....
Sign up to request clarification or add additional context in comments.

2 Comments

using postgres, is it still the same?
I see no reason why it shouldn't be, "AS" is standard SQL syntax, and I'd wager PHP's pg_* functions work very much like mysql_* ones.
2

Just alias the columns in the SELECT statement. Do not modify your database. The standard practice is to use aliasing in your SQL statements.

From PostgreSQL's docs for "SELECT":

"Using the clause AS output_name, another name can be specified for an output column."

PostgreSQL SELECT

1 Comment

in my case I have a lot of queries without the AS and it would be very painful renaming all. is there any way to do this ?
1

I recommend not to use it that way instead, you can rename output columns with AS.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.