I try to achieve the following:
- Some great post title (posted in Sport)
- Another title of a post here (posted in Space)
- Cool title of some post (posted in Technologies)
- And so on...
I display all posts from all categories and put the category name next to each post. I do not understand where and why fail. All posts are multiplied by the number of categories. Here is what I have till now:
posts table:
post_id
post_title
post_content
category_id
categories table:
category_id
category_name
category_description
And my queries and PHP code:
// I select all categories with their id and name
$stmt = $db->prepare("SELECT * FROM categories");
$stmt->execute();
$row_categories = $stmt->fetchAll(PDO::FETCH_ASSOC);
// I select all posts too
$stmt = $db->prepare("SELECT * FROM posts");
$stmt->execute();
$row_posts_all = $stmt->fetchAll(PDO::FETCH_ASSOC);
And then:
foreach ($row_posts_all as $array_index_number => $name_of_index) {
foreach ($row_categories as $array_index_number_categories => $name_of_index_category) {
print $name_of_index['post_title'] . " posted in: " . $name_of_index_category['category_name'] . "<br><br>";
}
}
I think this two foreaches part do things wrong. I can do one foreach to display all the posts but I do not know how to get their category names and put them next.