Skip to content

Instantly share code, notes, and snippets.

@Ellestad1995
Created May 25, 2019 14:57
Show Gist options
  • Save Ellestad1995/14eccdfb0fa17269c58ab548edf5ab46 to your computer and use it in GitHub Desktop.
Save Ellestad1995/14eccdfb0fa17269c58ab548edf5ab46 to your computer and use it in GitHub Desktop.
Database connection/PDO in php
<?php
return array(
'dbname' => 'somedbname',
'host' => 'database',
'username' => 'admin',
'password' => 'admin',
);
?>
<?php
/*
* Database connection
*/
class DB {
private static $db = null;
private $conn = NULL;
private function __construct() {
// Array with configuration values
$dbConfig = require_once(realpath(dirname(__FILE__)) . "DBConfig.php");
if(is_null($this->conn)){
// No connection to video is made by yet. Let's make one
$dsn = 'mysql:dbname=' . $dbConfig['dbname'] . ';host=' . $dbConfig['host'];
try {
$this->conn = new PDO($dsn, $dbConfig['username'], $dbConfig['password']);
} catch (PDOException $e) {
// NOTE IKKE BRUK DETTE I PRODUKSJON
print('Connection failed: ' . $e->getMessage());
}
}
}
/**
*
* @return Database connection for database / PDO object
*/
public static function getDBConnection(){
if (DB::$db==null) {
DB::$db = new self();
}
return DB::$db->conn;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment