I made a blog. Everything is working correctly except for one thing; being able to compare my id in order to open the appropriate article.
I’m using FETCH_ASSOC:
$sth->setFetchMode(PDO::FETCH_ASSOC);
I’m checking $_GET for an id:
if (isset($_GET['id']) && ($_GET['id'] == $blogid['id'])) { **PROBLEM IS WITH $blogid
$row = $sth->fetch()
//... Code to display html and db values
If true, it shows the entire blog post. Else it displays all the blog intros:
<?php } else { ?>
<?php while($row = $sth->fetch()) { ?>
//... Code to display html and db values
How can I access the id in my if statement? If I do something like:
$blogid = $sth->fetch()
it screws up $row = $sth->fetch() by reordering the posts
EDIT Query added:
$sth = $dbh->query('SELECT id, title, slug, body, image, author, date, category from blog ORDER BY date DESC');
You’re using PDO and MySQL slightly wrong here. Instead of getting all the blog posts and checking to see whether the one you’ve got has the correct ID, you should only get one blog post (row) from the DB using a
WHEREclause, like this:PDO handles this for you fantastically well by allowing you to use placeholders:
Here, I’ve used the placeholder
:theBlogIDwhich will be replaced by the$_GETparameter .Using PDO, your final code needs to prepare the query, bind a parameter to it, execute it and then get the result (checking if there actually is a result using
PDO::rowCount()) something like this:It’s not clear how much of the above you currently have as you only give one or two line snippets here and there, but this should give a good outline of what you need to do.