I am attempting to do object oriented programming in right way, and appreciate any review to see if my approach is correct.
class_blogpost.php as below:
<?php
class BlogPosts {
function __construct() {
# code...
}
public function ListAllBlogPosts() {
$DB = DatabaseFactory::getFactory()->Connect();
$query = $DB->prepare("SELECT * FROM posts ORDER BY date DESC");
$query->execute();
$list_all = $query->fetchAll(PDO::FETCH_ASSOC);
return $list_all;
}
public function ShowABlogPost($post_id) {
if (isset((int)$_GET["id"];)) {
$post_id = (int)$_GET["id"];
$DB = DatabaseFactory::getFactory()->Connect();
$query = $DB->prepare("SELECT * FROM posts WHERE id = :post_id");
$query->bindParam(':post_id', $post_id, PDO::PARAM_INT);
$query->execute();
$show_post = $query->fetchAll(PDO::FETCH_ASSOC);
return $show_post[0];
} else {
echo "Post not found.";
}
}
}
$blogposts = new BlogPosts;
Below is code for home.php which uses ListAllBlogPosts() function:
<?php
include_once 'connect.php';
$title = "Home";
include_once 'header.php';
$list_all = $blogposts->ListAllBlogPosts();
?>
<!-- col starts -->
<div>
<?php
foreach ($list_all as $r) {
$id = $r["id"];
$title = $r["title"];
$post = $r["post"];
$date = $r["date"];
?>
<h1><?php echo $title; ?></h1>
<p><?php echo $post; ?></p>
<a href="post.php?id=<?php echo $id; ?>">more</a>
<?php
} #ends foreach loop
?>
</div>
And finally post.php below, user reaches as post.php?id=1 like that:
<?php
include_once 'connect.php';
$id = $blogposts->ShowABlogPost($_GET["id"])["id"];
$title = $blogposts->ShowABlogPost($id)["title"];
$date = $blogposts->ShowABlogPost($id)["date"];
$post = $blogposts->ShowABlogPost($id)["post"];
include_once 'header.php';
?>
<div>
<h1><?php echo $title; ?></h1>
<p><?php echo $post; ?></p>
</div>
$blogposts->ShowABlogPost($id)["title"];,$date = $blogposts->ShowABlogPost($id)["date"];? Or you would just fetch a single row and use its contents? What makes you think that fetching the same record from database four times in a row is a good OOP? \$\endgroup\$(int)$_GET["id"]before checking if itisset()? \$\endgroup\$