简体   繁体   中英

How to make just one mysql connection with PDO

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]);

        }

    }
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;

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM