I'm new to PHP and MySQL and I'm currently making a blog portal. On the index page, all recent posts are shown with the title, author, date, the first 150 characters of the post plus an image from the post.
I have two tables in MySQL: "post" and "image" and I'm looping through both of these with foreach to check if a post has an image connected to it with the same postId. My problem is if a post has more than one image, I only want one image to show and not all of them like it does now. I tried making a query selecting all posts from a user where post.id = image.postId, but then the posts with no images were not shown.
I appreciate any input or suggestion on how to make this work, or maybe an entirely different approach.
In PHP/HTML file (removed the part of the code in the loop where title/content and so on is added):
<?php foreach($allPosts as $key => $onePost): ?>
<?php foreach($allImages as $one => $oneImage): ?>
<?php if ($oneImage['postId'] === $onePost['id']): ?>
<?php echo '<img src="../Images/' . $oneImage['filename'] . $secondString; ?>
<?php endif; ?>
<?php endforeach;?>
<?php endforeach;?>
In PHP/database file:
function selectAllPosts($conn)
{
$sql = '
SELECT p.*
, u.username
FROM post p
JOIN users u
ON p.userId = u.id
ORDER
BY created DESC
';
return $allPosts = db_select($conn, $sql);
}
function selectAllImages($conn)
{
$sql = 'SELECT * FROM image';
return $postImages = db_select($conn, $sql);
}