Your method creates a connection each time you run a query.
That method creates a single connection for each object and uses it for all the queries in the object.
Better still would be to create a single connection for the page and pass that one connection to each new object when it is created.
At the top of each page, have
require 'db_inc.php'; // <--- CONTAINS ----- # const HOST = "localhost";
# const USER = "root";
# const PWD = "";
# const DBNAME = "cms";
#
# function pdoconnect()
# {
# $dsn = 'mysql:host=' . HOST . ';dbname=' . DBNAME;
# $pdo = new PDO ($dsn, USER, PWD);
# $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
# $pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
# $pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
# return $pdo;
# }
#
$connection = pdoconnect(); // create connection
then your code becomes
<?php
class dbh {
protected $conn;
public function __construct($connection)
{
$this->conn = $connection;
}
}
class PostsData extends dbh{
public function getPosts() {
$sql = "SELECT * FROM posts_tbl";
$stmt = $this->conn->prepare($sql);
$stmt->execute();
$result = $stmt->fetchAll((PDO::FETCH_OBJ));
return $result;
}
public function addPost($filter_author, $filter_title, $filter_txt) {
$sql = "INSERT INTO posts_tbl (post_author, post_title, post_txt) VALUES (?, ?, ?)";
$stmt = $this->conn->prepare($sql);
$stmt->execute([$filter_author, $filter_title, $filter_txt]);
}
}
$post = new PostsData($connection); // pass connection to new object
$posts = $post->getPosts();
foreach ($posts as $post) {
echo $post->post_title . '<br>';
}
?>