Best way to connect database in PHP with classes

时间:2016-04-04 17:06:35

标签: php mysql class pdo subclass

I'm looking for the best way to connect MySQL database in PHP with PDO driver when using classes.

I don't want to make connection in every file. I did following class.DbConnection.php, is it useable in this case or should I do this totally different way? Is it possible to use subclasses or something?

Is this safe way to connect to database with PDO?

class DbConnection {

    protected $type = "mysql";
    protected $host = "127.0.0.1";
    protected $db = "databaseName";
    protected $user = "myUser";
    protected $pass = "myPass";

    public function __construct() {

        $this->db_connect();
    }


    public function db_connect() {

        try {
            $pdo = new PDO($this->type . ':host=' . $this->host . '; dbname=' . $this->db, $this->user, $this->pass);
            $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            $pdo->setAttribute(PDO::ATTR_TIMEOUT, 5);
            $pdo->exec("SET NAMES utf8");

        } catch (PDOException $e) {
            include("dbError.php");
            die();
        }
    }

}

Thanks in advance!

0 个答案:

没有答案