0

I try to create a simple cms for learning purposes. I wrote a function that gets the posts of a specific category. To print the posts I used a foreach loop. But I would like to use the cat_title only once on top of the screen. The all posts related to that cat_title/cat_id should be shown. I cannot seem to get this to work.

  function get_cat_posts($cat_id, $conn)
 {
    $result = $conn->query("SELECT blog_item.id, blog_item.title, blog_item.category_id, blog_item.posted_on, blog_item.content, menu_item.cat_title, menu_item.cat_id FROM blog_item INNER JOIN menu_item ON blog_item.category_id = menu_item.cat_id WHERE menu_item.cat_id= $cat_id");
    if($result->rowCount() != 0) {
        //   - category title - 
                foreach($result as $row) {              
                                echo '<hr>';
                                echo '<a href="post_cat_template.php/?category=' .$row['cat_id'] . '?post_id=' .$row['id'] . '">' . $row['title'] . '</a> - <em>' . $row['posted_on'] . '</em>';
                                echo '<hr>';
                } 
    }
    else { echo "no posts in this category";}

 } 
2
  • 1
    Why cant you just echo cat_title then do the foreach to display your posts after? Commented Aug 14, 2015 at 23:32
  • that is my question exactly. Why can't I. And If I can, how ? Commented Aug 15, 2015 at 16:04

1 Answer 1

1

As long as you are inside the if($result->rowCount() != 0) {, you know a $result[0] exists and, based on the SQL, all the $result have the same cat_title, so you can do this:

function get_cat_posts($cat_id, $conn)
{
   $data = $conn->query("SELECT blog_item.id, blog_item.title, blog_item.category_id, blog_item.posted_on, blog_item.content, menu_item.cat_title, menu_item.cat_id FROM blog_item INNER JOIN menu_item ON blog_item.category_id = menu_item.cat_id WHERE menu_item.cat_id= $cat_id");
   if($data->rowCount() != 0) {
       $result = $data->fetchAll(PDO::FETCH_ASSOC);
       echo $result[0]['cat_title']; // format as you want
       foreach($result as $row) {              
                               echo '<hr>';
                               echo '<a href="post_cat_template.php/? category=' .$row['cat_id'] . '?post_id=' .$row['id'] . '">' . $row['title'] . '</a> - <em>' . $row['posted_on'] . '</em>';
                               echo '<hr>';
               } 
   }
   else { echo "no posts in this category";}
} 
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. If I do what you proposed it says: Cannot use object of type PDOStatement as array
I updated the answer (modified line 3 and added line 5). Thought I read a fetchAll() in the first time.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.