Hello folks. I was writing a script for a blog a month ago which I couldn’t finish. I was taking on something too complicated and have started work on something simpler.
This is a very simple blog. I can retrieve the title and body from the mysql database on the main page. The title has a hyperlink and I want to know how I can get that link to take me to the main body of that article.
Using procedural programming.
<?php
include 'inc/header.php';
?>
<?php
// connect to a database
include 'inc/db.php';
// retrieve data from database
try {
$sql = 'SELECT * FROM posts';
$result = $pdo->query($sql);
}
catch (PDOException $e){
echo 'Sorry cannot fetch data at this point' .$e->getMessage();
}
$main_posts = array();
while ($row = $result->fetch()) {
$main_posts[] = array (
'id' => $row ['id'],
'title' => $row ['title'],
'body' => $row ['body']
);
}
//include file where it is to be displayed
include 'inc/main.php';
?>
<?php
include 'inc/sidebar.php';
include 'inc/footer.php';
?>
here is a copy of main.php
<div id="main-section">
<div class="wrap">
<?php foreach ($main_posts as $main_post): ?>
<h1><a href="single.php?id=<?php $main_post['id'];?>"> <?php echo $main_post ['title']; ?> </a></h1>
<p> <?php echo $main_post ['body']; ?> </p>
<?php endforeach; ?>
</div><!-- end wrap-->
</div><!-- end main section-->
Now we’ve got <a href="single.php?id=<?php $main_post['id'];?>">
But I get an error once the posts run out. The error understandably states:
Notice: Trying to get property of non-object in C:\xampp1\htdocs\blog\single.php on line 17
I have created a page that says “Sorry, no more posts to be displayed”. How do I go about displaying that once the posts run out? The only thing I believe I am missing is how I can refer to the fact that there are no posts remaining.
For instance
if (code for no object returned) {
include ‘error.php’;
}