PHP + MySQL: When I select from two tables, how to define from which table I want to take "id"
I have two tables, each with an "id" field. Here are the two tables:
news : id, authorid, datetime, body
authors : id, name
I have this select query:
SELECT * FROM news, authors WHERE (news.authorid = authors.id) ORDER BY news.datetime DESC;
Then, in PHP, I want to use id of the table news. I have this code:
while ($row = mysql_fetch_array($result))
{
// I want开发者_StackOverflow to take news.id, but it gives an error:
echo $row["news.id"]; // error: "Undefined index: news.id"
// And when I write only "id", it takes it of authors.
echo $row["id"]; // this id is authors.id, but I want news.id
}
Give them aliases
SELECT news.id AS news_id FROM news, authors WHERE (news.author = authors.id) ORDER BY news.datetime DESC;
Or
SELECT *, news.id AS news_id FROM news, authors WHERE (news.author = authors.id) ORDER BY news.datetime DESC;
IN you SQL query, you can use aliases :
select table1.id as id_1, table2.id as id_2, ...
The columns will be available from PHP using the aliases, and not the names of the columns.
In your case, you'd have :
SELECT news.id as news_id, news.authorid, news.datetime, news.body,
authors.id as author_id, authors.name
FROM news, authors
WHERE (news.author = authors.id)
ORDER BY news.datetime DESC;
And, in your PHP code, you'd use the aliases :
echo $row["news_id"];
echo $row["author_id"];
You should explicitely define the fields you want to retrieve and alias the ambigous ones:
select news.id as news_id, news.authorid, news.datetime, news.body,
authors.id as authors_id, authors.name
FROM news, authors WHERE (news.author = authors.id)
ORDER BY news.datetime DESC authors.name
user As statement in sql like
select news.id as newsid, news.authorid as newsauthorid, authors.id as authorsid ....
and in php get as
echo $row["newsid"] ;
//
echo $row["authorsid"] ;
精彩评论