Reputation: 57
Alright, so I've been foraging through the web as well as stackoverflow for sometime for an answer to my question(below), however nearly every explanation and/or topic I've found is either too convoluted for me or doesn't cater to my specific needs...
In short I have a blog that outputs numerous POSTs. Each POST contains multiple IMAGES. The POST contains data like TITLE, DESCRIPTION, POST DATE.. These things are contained in ONE Table called tbl_blog. The IMAGES belong to their own table called tbl_blog_imgs.
Right now, my code "works", however it only displays one blog post with images that match that blog post's ID. (In tbl_blog_imgs, I have a row called blog_key that matches the ID of each entry in tbl_blog)
Problem is naturally that I have more than one blog post and only one seems to post... IN
My Code...
<?php
require('myownsecretfile.php');
$sql = "SELECT blog_id, blog_title, blog_desc, date_format(blog_post_date,'%d/%m/%Y') as blog_post_date ";
$sql .= "FROM tbl_blog ";
$result = mysql_query($sql);
while($row = mysql_fetch_assoc($result)) {
$blog_id = $row['blog_id'];
$blog_title = $row['blog_title'];
$blog_desc = $row['blog_desc'];
$blog_post_date = $row['blog_post_date'];
?>
<div class="blog-title"><a href="blog_more.php?blog_title=<?php echo $blog_title; ?>"><?php echo $blog_title; ?></a>
<p class="blog-post-date-style">- <?php echo $blog_post_date; ?> -</p>
<br>
<div class="blog-desc">
<p class="blog-description-style"><?php echo $blog_desc; ?></p>
</div>
</div>
<br>
<?php
$sql = "SELECT * ";
$sql .= "FROM tbl_blog_imgs ";
$sql .= "WHERE blog_img_key='$blog_id' ";
$result = mysql_query($sql);
while($row = mysql_fetch_assoc($result)) {
$blog_img_key = $row['blog_img_key'];
$blog_img_path = $row['blog_img_path'];
$blog_img_alt = $row['blog_img_alt'];
$blog_img_title = $row['blog_img_title'];
?>
<img src="images/blog/<?php echo $blog_img_path; ?>" alt="<?php echo $blog_img_alt; ?>" title="<?php echo $blog_img_title; ?>"><br>
<?php
}
}
?>
Must I perform an INNER JOIN? If not, what would be the smartest and most efficient way of acheiving a loop inside of a loop...
Upvotes: 2
Views: 129
Reputation: 780724
You're using the same variable $result
for both queries. So when it finishes displaying all the images for the first blog, and returns to the beginning of the outer loop, it does
$row = mysql_fetch_assoc($result);
But now $result
contains the result of the image query, not the blog query. And since that query has returned all its rows, this returns false
, so the outer loop terminates.
Change them to $result_blog
and $result_img
and I think your problem should be solved.
It's also confusing to use the same variable $row
for both loops. In this case it doesn't cause a problem, because you immediately set variables to the elements of those arrays. But it's a bad habit, so I suggest you rename them as well.
Upvotes: 1