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");
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.
@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“:
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.fieldThen 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.