Hi, i’m trying to display posts by category for a blog I am building.
I’m new to php and have been following a guide
This is in my functions.php to display posts by category.
function getPublishedPostsByCategory($category_id) {
global $conn;
$sql = "SELECT * FROM posts pc
WHERE pc.id IN
(SELECT post_id FROM post_category
WHERE category_id=$category_id GROUP BY post_id
HAVING COUNT(1) = 1)"
$result = mysqli_query($conn, $sql);
// fetch all posts as an associative array called $posts
$posts = mysqli_fetch_all($result, MYSQLI_ASSOC);
//* * * * * * * * * * * * * * */
$final_posts = array();
foreach ($posts as $post) {
$post['category'] = getPostCategory($post['id']);
array_push($final_posts, $post);
}
return $final_posts;
And in the page where I am displaying the posts I have
<?php // Get posts under a particular topic if (isset($_GET['category'])) { $categoy_id = $_GET['category']; $posts = getPublishedPostsByCategory($category_id); } ?>I’m getting the error
Notice : Undefined variable: posts in /home/ttestdmor/public_html/filtered_posts.php on line 31
Warning : Invalid argument supplied for foreach() in /home/ttestdmor/public_html/filtered_posts.php on line 31
Can anyone help me fix this? Don’t understand why it is happening.
EDIT: mangaed to get it down to just this error - Invalid argument supplied for foreach()
Thanks
Simon