Advertisement
Guest User

DB handler

a guest
Jun 1st, 2016
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.70 KB | None | 0 0
  1. <?PHP class DB {
  2.  
  3. private static $_instance = null;
  4. private static $_pdo = false;
  5.  
  6.  
  7.  
  8. private function __construct(){
  9.    
  10.      $_host = 'localhost';
  11.      $_db   = 'computer_monitor';
  12.      $_user = 'cm_handler';
  13.      $_pass = 'PASSWORD';
  14.  
  15.      try {
  16.         self::$_pdo = new PDO(
  17.             'mysql:host=' . $_host .
  18.             ';dbname=' . $_db .
  19.             ';charset=UTF8',
  20.             $_user,
  21.             $_pass
  22.         );
  23.     } catch( PDOException $e ){ echo $e->getMessage(); }
  24. }
  25.  
  26. private static function getInstance(){
  27.     if( !isset( self::$_instance ) ) self::$_instance = new self();
  28.     return self::$_instance;
  29. }
  30.  
  31.  
  32.  
  33. // https://www.owasp.org/index.php/PHP_Security_Cheat_Sheet#PDO_Prepared_Statement_Wrapper
  34. public static function query( $sql ){
  35.     self::getInstance();
  36.     $args = func_get_args();
  37.    
  38.     if( count( $args ) === 1 ){
  39.         if( !$result = self::$_pdo->query( $sql ) ){
  40.             $error = self::$_pdo->errorInfo();
  41.             trigger_error('Unable to prepare statement: ' . $sql . '<br>Reason: ' . $error[2] );
  42.             return false;
  43.         }
  44.         return $result->fetchAll( PDO::FETCH_ASSOC );
  45.        
  46.     } else {
  47.         if( !$stmt = self::$_pdo->prepare( $sql ) ){
  48.             $error = self::$_pdo->errorInfo();
  49.             trigger_error('Unable to prepare statement: ' . $sql . '<br>Reason: ' . $error[2] );
  50.             return false;
  51.         }
  52.        
  53.         array_shift( $args ); //remove $sql from args
  54.         $i = 0;
  55.         foreach( $args as &$v )
  56.             $stmt->bindValue( ++$i, $v, is_int( $v ) ? PDO::PARAM_INT : PDO::PARAM_STR );
  57.        
  58.         if( !$stmt->execute() ){
  59.             $error = $stmt->errorInfo();
  60.             trigger_error('Unable to prepare statement: ' . $sql . '<br>Reason: ' . $error[2] );
  61.             return false;
  62.         }
  63.         return $stmt->fetchAll( PDO::FETCH_ASSOC );
  64.        
  65.     }
  66. }
  67.  
  68. public static function lastID(){
  69.     return self::$_pdo->lastInsertId();
  70. }
  71.  
  72. } ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement