I made a simple blog script in PHP and SQL, on the page where the latest posts need to be displayed everything works fine, however, I made a page 'comments.php' that will load the comments of the selected post. If you click on let's say Post 1, the link generated by PHP would be 'comments.php?id=1'.
This is the code I have on the 'blog.php' page, where everything works fine and post content is displayed correctly:
$db = new PDO('mysql:hostname=localhost;dbname=test;charset=utf8', 'root', '');
$req = $db->query('SELECT id, title, content, DATE_FORMAT(creation, \'%d/%m/%Y at %H:%i\') AS datePosted, user FROM blogpost ORDER BY creation DESC LIMIT 0, 5');
while($data = $req->fetch()){
?>
<div class="blogpost-container">
<div class="blogpost-title">
<?php
echo htmlspecialchars($data['title']) . " | <em>Posted on ".$data['datePosted']."</em>";
?>
</div>
<div class="blogpost-content">
<?php
echo nl2br(htmlspecialchars($data['content']));
?>
</div>
<div class="blogpost-user">
<?php
echo "Posted by: ".$data['user'].".";
?>
</div>
<div class="blogpost-comments">
<a href=<?php echo "'comments.php?id=". $data['id']."'"; ?> >
Show comments
</a>
</div>
</div>
<?php
}
$req->closeCursor();
?>
Here, the post load correctly, but once I go on comments.php?id=1 for example, it doesn't show anything. Here's the code from the 'comments.php':
<?php
$db = new PDO('mysql:hostname=localhost;dbname=test;charset=utf8;', 'root', '');
$req = $db->prepare('SELECT id, title, content, DATE_FORMAT(creation, \'%d/%m/%Y at %H:%i), user FROM blogpost WHERE id = ?');
$req->execute(array(
$_GET['id']
));
$data = $req->fetch();
?>
<div class="blogpost-container">
<div class="blogpost-title">
<?php
echo htmlspecialchars($data['title']) . " | <em>Posted on ".$data['datePosted']."</em>";
?>
</div>
<div class="blogpost-content">
<?php
echo nl2br(htmlspecialchars($data['content']));
?>
</div>
<div class="blogpost-user">
<?php
echo "Posted by: ".$data['user'].".";
?>
</div>
</div>