0
<?php
        $sql = "SELECT * FROM posts ORDER BY created_at DESC";
        $statement = $connection->prepare($sql);
        $statement->execute();
        $statement->setFetchMode(PDO::FETCH_ASSOC);
        $posts = $statement->fetchAll();
?>


<?php foreach ($posts as $post) { ?>
            
                <div class="blog-post">
                    <a href="single-post.php"><h2 class="blog-post-title"> <?php echo($post['title']) ?></h2></a>
                    <p class="blog-post-meta"><?php echo($post['created_at']) ?> by <a href="#"> <?php echo($post['author']) ?></a></p>
                    <p><?php echo($post['body']) ?></p>
                </div>
                    
<?php } ?>


In this example, I loop though every single "post" from my blog's database and as you can see, the posts title is also a link that leads to its specific post's separate page. In that single-page.php file, instead of looping thought each row or rather "post" from my database I want it to generate an exact post I clicked on.

Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
qouillyan
  • 25
  • 5
  • An easy way is to put the post ID into your href target as a parameter, and inside your `single-post.php` code, retrieve that parameter and use it in the query. You'll have something like `` as a result. Don't use the title. – droopsnoot Nov 02 '22 at 07:49
  • Thanks for your input, I appreciate it, but; what if I have 1000 posts in my database? Doing that manually is not a way to go, I wish to automatically generate the right post. – qouillyan Nov 02 '22 at 07:55
  • Well, of course. You're already in a loop displaying the titles, so you edit the code to also include the post unique ID in the href target, just the same as you put the post title into the href text. Something like `$target = "single-post.php?pid=" . $post['unique-id']` for example. – droopsnoot Nov 02 '22 at 07:56
  • I'll let you know if it worked out for me :D – qouillyan Nov 02 '22 at 08:00
  • It should do, it's a pretty standard way of doing things. – droopsnoot Nov 02 '22 at 08:07
  • 1
    By the way, your question is neither related to PDO or databasesl – Your Common Sense Nov 02 '22 at 08:27

0 Answers0