Last active
December 18, 2015 08:18
-
-
Save shyamsalimkumar/5752547 to your computer and use it in GitHub Desktop.
PHP - Database connection using PDO
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 | |
// you can choose from MySQL and SQLite | |
define('DB_DRIVER', 'mysql'); | |
// SQLite don't use host parameter | |
define('DB_HOST', 'localhost'); | |
define('DB_USER', 'login'); | |
define('DB_PASS', 'password'); | |
// In case of SQLite usage, change it to path/to/your.db, for example | |
define('DB_NAME', 'testdb'); | |
function initDB(){ | |
// Switch correct pattern for chosen DBMS. | |
// You can add your own patterns for PostgreSQL or MS SQL, for example | |
if(DB_DRIVER=='mysql') | |
$pattern = '%1$s:host=%2$s;dbname=%3$s'; | |
elseif(DB_DRIVER=='sqlite') | |
$pattern = '%1$s:%3$s'; | |
else | |
die("Can't create DB instance! Reason: Unsuported DB driver"); | |
// Construct correct data source name for chosen database type | |
$dsn = sprintf($pattern, DB_DRIVER, DB_HOST, DB_NAME); | |
try{ | |
$pdoInst = new PDO($dsn, DB_USER, DB_PASS); | |
$pdoInst->setAttribute(PDO::ATTR_ERRMODE, | |
PDO::ERRMODE_EXCEPTION); | |
}catch(PDOException $e){ | |
// Stop script and throw message if error occurred | |
die($e->getMessage()); | |
} | |
// Let us know that all is ok. Only for debug. | |
echo 'PDO Instance created!'; | |
return $pdoInst; | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment