php - Use variable outside foreach loop

Solution:
As long as you are inside theif($result->rowCount() != 0) {
, you know a$result[0]
exists and, based on the SQL, all the$result
have the samecat_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";}
}
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: fastcgi sent in stderr: "primary script unknown" while reading response header from upstream
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.