Home » Php » php – How to make just one mysql connection with PDO

php – How to make just one mysql connection with PDO

Posted by: admin February 25, 2020 Leave a comment

Questions:

I’m trying to make just one connection with my code down below.

Inside func.php I added function __construct but does not work. Error:

Uncaught Error: Call to protected method dbh::connect() from context ‘getPosts’.

I read some articles and I don’t really understand where function __construct should be placed. Inside my connect.php or func.php?

public $conn;

public function __construct() {
    $this->conn = new dbh();
    $this->conn = $this->conn->connect();

}

MY code:
connect.php

    class dbh{

        private $host = "localhost";
        private $user = "root";
        private $pwd = "12345";
        private $dbname = "posts";

        protected function connect() {
            $dsn = 'mysql:host=' . $this->host . ';dbname=' . $this->dbname;
            $pdo = new PDO ($dsn, $this->user, $this->pwd);
            $pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
            return $pdo;

    }
}

func.php

class PostsData extends dbh{

    public function getPosts() {

            $sql = "SELECT * FROM posts_tbl";
            $stmt = $this->connect()->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->connect()->prepare($sql);
            $stmt->execute([$filter_author, $filter_title, $filter_txt]);

        }

    }
How to&Answers:
class PostsData extends dbh{


private $conn;

public function __construct() {
$this->conn = new dbh();
$this->conn = $this->conn->connect();

}



   public function getPosts() {

            $sql = "SELECT * FROM posts_tbl";
            $stmt = $this->connect()->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->connect()->prepare($sql);
            $stmt->execute([$filter_author, $filter_title, $filter_txt]);

        }

    }

$post = new PostsData();
$posts = $post->getPosts();

foreach ($posts as $post) { 

echo $post->post_title;

}