Forked from mysiar/PDO database connection Class with single static method
Created
December 3, 2020 10:39
-
-
Save ribafs/7df6e725721c3975c7c832a25ae22afa to your computer and use it in GitHub Desktop.
PDO database connection Class with single static method
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment