Bas Schreuder
Bas Schreuder

Reputation: 172

Use variable outside foreach loop

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";}

 } 

Upvotes: 0

Views: 621

Answers (1)

Berriel
Berriel

Reputation: 13601

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";}
} 

Upvotes: 1

Related Questions