Skip to content
Advertisement

How to create PDO connection in __construct()?

I have one class that is containing three methods. All of those methods need to database, Then I want to create a system for connection to database before everything. Something like this:

Class myclass
{
    private $db;

    public function __construct() {

        $db = new PDO("mysql:host = hostname; dbname = database",username, password);
    }

    function one()   {/* it needs to database and I will use it like this: */
                         $this->$db->prepare("select ...");
                     }
    function two()   {/* also it needs to database */}
    function three() {/* also it needs to database */}
}

Now I want to know (in first) what I did is a standard approach? and (in second) how can I check [if connection was disconnect (in other word connection does not exist) then connect] ?

Advertisement

Answer

To access class properties, you have to use -> syntax:

Class myclass
{
    private $db;

    public function __construct() {

        $this->db = new PDO("mysql:host = hostname; dbname = database",username, password);
    }

    function one()   {/* it needs to database and I will use it like this: */
        $this->db->prepare("select ...");
    }
    function two()   {/* also it needs to database */}
    function three() {/* also it needs to database */}
}

If you want to detect errors, enable error signalling with

$this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

and use try/catch around the code that uses the DB:

function one() {
    try {
        $this->db->prepare(...);
    } catch (PDOException $e) {
        // handle error
    }
}
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement