I'm working on a blog site, and over the past few days I've been cleaning it up so it uses a lot more included functions rather than inline php. So far it's been really helpful.
Right now I'm trying to use a function to get all the blogposts in the database, which are stored like this:
Previously I was doing this right in my main blog.php file, which includes all the html. That looked like this:
$stmt = $db->prepare("SELECT * FROM blog_posts ORDER BY id DESC");
$stmt->execute();
foreach($stmt as $blogPost)
{
$dateTime = date("j F, Y g:i a", (strtotime($blogPost['date_posted'])));
echo "<div class='blog-main-preview'>";
echo "<p class='blog-preview-title'>" . $blogPost['title'] . "</p>";
echo "<p id='blog-preview-date'>" . $dateTime . "</p><br>";
$post = $blogPost['post'];
$post = strip_tags($post);
$post = substr($post, 0, 200);
echo "<p id='blog-preview-post'>" . $post . "...</p><br>";
echo "<a href='blog-post.php?postid=" . $blogPost['id'] . "' id='read-more'><p>Read More</p></a><br>";
echo "</div>";
}
This worked great but I was looking to move it to a function too. I realize I could just move the whole thing to a function, I was just hoping there was a solution where I didn't have to have any of the html in the function, and it could return something with which I could run the foreach loop in the main blog.php file. Can I do this?
Edit: So to clarify, what I'm looking for is to have my blog.php page look like:
$blogPosts = getBlogPosts($db);
foreach($blogPosts as $blogPost)
{
$dateTime = date("j F, Y g:i a", (strtotime($blogPost['date_posted'])));
echo "<div class='blog-main-preview'>";
echo "<p class='blog-preview-title'>" . $blogPost['title'] . "</p>";
echo "<p id='blog-preview-date'>" . $dateTime . "</p><br>";
$post = $blogPost['post'];
$post = strip_tags($post);
$post = substr($post, 0, 200);
echo "<p id='blog-preview-post'>" . $post . "...</p><br>";
echo "<a href='blog-post.php?postid=" . $blogPost['id'] . "' id='read-more'><p>Read More</p></a><br>";
echo "</div>";
}
And the functions file will contain the function which retrieves and returns the blogPosts.
