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.