Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- // in the config file:
- define('MYSQL_USER', 'mydb');
- define('MYSQL_PASS', 'myUser');
- define('MYSQL_DB', 'db_myDB');
- define('PDO_CONNECTION', true);
- define('PDO_MYSQL_DSN', 'mysql:dbname='.MYSQL_DB.';host=localhost;charset=UTF-8');
- // Singleton
- class DB{
- private static $_PdoDbInstance;
- /*
- * Class Constructor - Create a new database connection if one doesn't exist
- * Set to private so no-one can create a new instance via ' = new DB();'
- */
- private function __construct() {}
- /*
- * Like the constructor, we make __clone private so nobody can clone the instance
- */
- private function __clone() {}
- /*
- * Returns DB instance or create initial connection
- * @param
- * @return $_PdoDbInstance;
- */
- public static function getDB( ) {
- if ( !isset(self::$_PdoDbInstance) ){
- $errorString = '';
- if( !defined('PDO_MYSQL_DSN') ) { $errorString .= 'PDO_MYSQL Data Source Name (DSN) hasn\'t been defined!'.PHP_EOL; }
- if( !defined('MYSQL_USER') ) { $errorString .= 'MySQL username hasn\'t been defined!'.PHP_EOL; }
- if( !defined('MYSQL_PASS') ) { $errorString .= 'MySQL password hasn\'t been defined!'.PHP_EOL; }
- if( !defined('MYSQL_USER') ) { $errorString .= 'MySQL username hasn\'t been defined!'.PHP_EOL; }
- if( !empty($errorString) ) { $errorString .= 'Class: '.__CLASS__; throw new PDOException( $errorString ); }
- // if no errors have occurred, we create an instance of the PDO database object
- self::$_PdoDbInstance = new PDO( PDO_MYSQL_DSN, MYSQL_USER, MYSQL_PASS, array( PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8' ) );
- // it should throw exceptions in case of any errors
- self::$_PdoDbInstance->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
- }
- return self::$_PdoDbInstance;
- }
- /*
- * Release database connection by setting it to NULL
- * @param none
- * @return none
- */
- public static function setNull(){
- self::$_PdoDbInstance = NULL;
- }
- }
- /////////////////////
- // USING THE CLASS //
- /////////////////////
- try {
- $query = 'SELECT * FROM `test_table` WHERE test_data = :test_data_stuff ';
- $stmt = DB::getDB()->prepare($query);
- $test_data_var = 'blabla';
- $stmt->bindParam( ':test_data_stuff', $test_data_var );
- $stmt->execute();
- $assoc_array = $stmt->fetchAll(PDO::FETCH_ASSOC);
- echo '.<pre>';
- print_r($assoc_array);
- echo '</pre>';
- } catch (PDOException $e) {
- DB::setNull();
- echo 'Database error blah-blah...<br />';
- // exception messages should rather be logged!!
- echo $e->getMessage();
- } catch (Exception $e) {
- DB::setNull();
- echo 'Any other exceptions blah-blah...<br />';
- // exception messages should rather be logged!!
- echo $e->getMessage();
- }
- // THAT'S ALL!
- ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement