1

I have to create getConnection function inside of Database class. The function should connect to a database using PDO object and returning it. I have something like this:

class Database {

public function getConnection() {

    $result = new PDO('mysql:host=localhost;dbname=demo', 'root', '');
        return $result;

    }

}

Is it correct? How can i know if i'm connected to database?

artur47wien
  • 355
  • 2
  • 4
  • 13

2 Answers2

2

PDO will throw an exception if the connection attempt fails, so you can normalize that like this:

class Database {
    private $_conn = null;
    public function getConnection() {
        if (!is_null($this->_conn)) {
            return $this->_conn
        }
        $this->_conn = false;
        try {
            $this->_conn = new PDO('mysql:host=localhost;dbname=demo', 'root', '');
        } catch(PDOException $e) { }
        return $this->_conn;
    }
}
$db = new Database();
$conn = $db->getConnection();
if (!$conn) {
    die("Error connecting to the database");
}
$conn->whatever();
iam-decoder
  • 2,554
  • 1
  • 13
  • 28
2

How can i know if i'm connected to database?

PDO will throw an exception in case of connection error.

Is it correct?

Nope, it's not a good idea, because the method is called getConnection while in reality it creates a connection. And a public property asks to call it in the application code, resulting multiple connections from the same script.

Besides, you should always set PDO in exception mode. And you should set charset in DSN as well.

Depends on the proposed use of this function the code could be

protected function connect()
{
    $pdo = new PDO('mysql:host=localhost;dbname=demo;charset=utf8', 'root', '');
    $pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
    return $pdo;
}

if it's intended to be used only once in the constructor.

While for the getConnection() function you are bound to use a static variable ho hold the single instance of PDO.

Recently I took time to compile all the common mistakes for the database wrappers in the article Your first DB wrapper's childhood diseases. You may find this reading extremely useful.

mickmackusa
  • 43,625
  • 12
  • 83
  • 136
Your Common Sense
  • 156,878
  • 40
  • 214
  • 345