开发者

Get post author name and category name from other table by ID

I have three mysql tables, first holds information about articles (Article ID, author ID, title and content), second tables holds information about registered users on my site (ID, name, password, email), third holds information about categories (ID, name).

I need to get all the articles and displays title, author name and category name, but the article table holds information only about author and category ids, not name.

I know how get all the articles from articles table but how should I get author names and category names from another tables at the same time to display with article title?

Hope I'm clear.

Here is a code I use to display article titles:

$q = mysql_query("SELECT * FROM articles ORDER BY ID DESC");开发者_Python百科

if(!$q) die(mysql_error());

while($article = mysql_fetch_object($q)) {

echo '<div class="article">';
echo $article->title . '</a>';
echo '<p class="details">Author:' . $article->author_ID . '.</p>';
echo '</div>';
}  

As you guess the $article->ID variable display author ID but I want to display name instead, which is kept in authors table. The same for categories...

Can anyone please help?

Thanks in advance.


You have to JOIN the other tables together to get that information. Please see here for more information on SQL Joins. If you have not used joins before, poke around for more examples on how to do simple and complex joins between tables. Once you join your tables, all the data that you are asking for will be available.


@Tommy is right, you have to use JOINS, here's something to get you going.
Assuming your three tables are called "articles", "users" and "categories":

SELECT articles.title, users.name, categories.name FROM articles  
JOIN users ON users.id=articles.author_id  
JOIN categories ON categories.id=articles.category_id   
ORDER BY ID DESC

Now I am just guessing at your table and field names of course.
On the first line I called the required fields like so tablename.field
Then I JOINed the users table to the articles table where a user's id in the users table should be equal to the author_id's in the articles table.
Then similarly I joined the categories table specifying that category id's in the categories table are equal to the category_id's in the articles table.
After this you can have a WHERE clause to further narrow your selection, or just go straight to the ORDER BY since you're looking to grab them all.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜