Last active
December 11, 2021 17:22
-
-
Save mysiar/111daf841737e1ab42549bb86e17531f to your computer and use it in GitHub Desktop.
PDO database connection Class with single static method
This file contains 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
Interesting solution, thanks a lot! 🚀