Created
May 25, 2019 14:57
-
-
Save Ellestad1995/14eccdfb0fa17269c58ab548edf5ab46 to your computer and use it in GitHub Desktop.
Database connection/PDO in php
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
<?php | |
return array( | |
'dbname' => 'somedbname', | |
'host' => 'database', | |
'username' => 'admin', | |
'password' => 'admin', | |
); | |
?> |
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
<?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