Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select same column name from two tables

Tags:

php

mysql

I have this query:

$result3 = mysql_query("SELECT posts.id, posts.date, posts.title, comments.post, comments.id, comments.date FROM posts, comments WHERE posts.id = comments.post")       
or die(mysql_error());  

while($row2 = mysql_fetch_array( $result3 )) {
    echo $row2['title'];
}

The problem is with the posts.id , posts.date and comments.id , comments.date . How can I get out id, date for both tables $row2['....]; I tried $row2['posts.id']; but it didn't work!

like image 634
mypoint Avatar asked Aug 07 '26 21:08

mypoint


1 Answers

Name the column in your query (this is called an column alias) like this:

SELECT 
    posts.id as postsID, 
    posts.date, 
    posts.title, 
    comments.post, 
    comments.id as CommentsID, 
    comments.date 
FROM 
    jaut_posts, 
    f1_comments 
WHERE 
    jaut_posts.id = f1_comments.post

Then you can use:

echo $row2['postsID'];
echo $row2['commentsID'];

Edit:

You may also benefit from this question I wrote and answered which discusses many common SQL queries and requests.

like image 193
Fluffeh Avatar answered Aug 10 '26 12:08

Fluffeh