Advertisement
Guest User

Untitled

a guest
Jun 12th, 2016
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.32 KB | None | 0 0
  1. <?php
  2.     class classDatabase
  3.     {
  4.         protected static $instance = null;
  5.         protected static $host = 'localhost';
  6.         protected static $name = '';
  7.         protected static $username = '';
  8.         protected static $password = '';
  9.         protected static $charset = 'UTF8';
  10.  
  11.         protected function __construct(){}
  12.         protected function __clone(){}
  13.         protected function __wakeup(){}
  14.  
  15.         final public static
  16.         function getInstance() //this method can throw exception
  17.         {
  18.             if(is_null(static::$instance))
  19.             {
  20.                 $dsn =
  21.                     'mysql:host=' . static::$host .
  22.                     ';dbname=' . static::$name .
  23.                     ';charset=' . static::$charset;
  24.  
  25.                 $options = array
  26.                 (
  27.                     \PDO::ATTR_ERRMODE               => \PDO::ERRMODE_EXCEPTION,
  28.                     \PDO::ATTR_DEFAULT_FETCH_MODE    => \PDO::FETCH_ASSOC,
  29.                     \PDO::ATTR_TIMEOUT               => 4
  30.                 );
  31.  
  32.                 static::$instance = new \PDO
  33.                 (
  34.                     $dsn,
  35.                     static::$username,
  36.                     static::$password,
  37.                     $options
  38.                 );
  39.             }
  40.  
  41.             return static::$instance;
  42.         }
  43.     };
  44.  
  45.     try
  46.     {
  47.         $database = \saoDatabase::getInstance();
  48.  
  49.         $statement = $database->query
  50.         ("
  51.             SELECT `field`
  52.             FROM `database`
  53.             WHERE TRUE
  54.                 AND `condition`
  55.             LIMIT 1;
  56.         ");
  57.  
  58.         $fetched_field = $statement->fetchColumn();
  59.  
  60.         echo $fetched_field;
  61.     }
  62.     catch(\PDOException $exception)
  63.     {
  64.         echo 'SQL error occurred';
  65.     }
  66. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement