-
-
Save ribafs/0b457c9a3fb313ab9b6a98fffba47c4f to your computer and use it in GitHub Desktop.
PDO Connection Class using Singleton
This file contains hidden or 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 | |
/** | |
* PDO Singleton Class v.1.0 | |
* | |
* @author Ademílson F. Tonato | |
* @link https://twitter.com/ftonato | |
* | |
*/ | |
class DB { | |
protected static $instance; | |
protected function __construct() {} | |
public static function getInstance() { | |
if(empty(self::$instance)) { | |
$db_info = array( | |
"db_host" => "localhost", | |
"db_port" => "3306", | |
"db_user" => "user", | |
"db_pass" => "pass", | |
"db_name" => "ftonato", | |
"db_charset" => "UTF-8"); | |
try { | |
self::$instance = new PDO("mysql:host=".$db_info['db_host'].';port='.$db_info['db_port'].';dbname='.$db_info['db_name'], $db_info['db_user'], $db_info['db_pass']); | |
self::$instance->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT); | |
self::$instance->query('SET NAMES utf8'); | |
self::$instance->query('SET CHARACTER SET utf8'); | |
} catch(PDOException $error) { | |
echo $error->getMessage(); | |
} | |
} | |
return self::$instance; | |
} | |
public static function setCharsetEncoding() { | |
if (self::$instance == null) { | |
self::connect(); | |
} | |
self::$instance->exec( | |
"SET NAMES 'utf8'; | |
SET character_set_connection=utf8; | |
SET character_set_client=utf8; | |
SET character_set_results=utf8"); | |
} | |
} | |
?> |
This file contains hidden or 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 | |
require_once ('database.class.php'); | |
try { | |
$db = DB::getInstance(); | |
DB::setCharsetEncoding(); | |
$sqlExample = 'SELECT * FROM users WHERE _id = 1'; | |
$stm = $db->prepare($sqlExample); | |
$stm->execute(); | |
return $stm->fetchAll(PDO::FETCH_ASSOC); | |
} catch (Exception $e) { | |
print $e->getMessage(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment