Singleton pattern
<?php
class Database {
private static $_db = null;
public static function connect($host, $dbname, $user, $password) {
if (self::$_db === null) {
$dsn = 'mysql:host=' . $host . ';dbname=' . $dbname . ';charset=utf8';
self::$_db = new PDO($dsn, $user, $password);
self::$_db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
return self::$_db;
}
}
$db = Database::connect('localhost', 'dbname', 'user', 'password');
$stmt = $db->query('SELECT fname FROM tbl_students');
var_dump($stmt->fetchAll(PDO::FETCH_ASSOC));