Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save mysiar/111daf841737e1ab42549bb86e17531f to your computer and use it in GitHub Desktop.
Save mysiar/111daf841737e1ab42549bb86e17531f to your computer and use it in GitHub Desktop.
PDO database connection Class with single static method
// dbconfig.json
{
"server": "localhost",
"dbname": "cl_shop",
"user" : "root",
"pass" : "root"
}
// class definition
class DB {
public static function &conn() {
$cfg = json_decode(file_get_contents('dbconfig.json', true));
$conn = NULL;
if ($conn == NULL) {
try {
$conn = new PDO('mysql:host=' . $cfg->server . ';dbname=' . $cfg->dbname, $cfg->user, $cfg->pass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo 'PDO Error: ' . $e->getMessage();
}
}
return $conn;
}
}
// usage example
$stm = DB::conn()->prepare('SELECT * FROM users');
$stm->execute();
$res = $stm->fetchAll(PDO::FETCH_CLASS);
var_dump($res);
var_dump($res[0]->id);
var_dump($res[0]->fname);
@ribafs
Copy link

ribafs commented Dec 3, 2020

Thank you!

@PAXANDDOS
Copy link

Interesting solution, thanks a lot! 🚀

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment