Advertisement
anton_slim

classes/pdo_mysql.php

Feb 21st, 2012
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 7.07 KB | None | 0 0
  1. <?php
  2.  
  3. /*$host $user,$pass,$table беруться из файла config.class.php */
  4.  
  5.  
  6. class pdo_mysql
  7. {
  8.     protected $_host = 'localhost';
  9.     protected $_user = 'sites';
  10.     protected $_pass = '';
  11.     protected $_dbname = 'sites_sklad';
  12.     protected $_init_command = "SET names utf8, lc_time_names = ru_RU, time_zone='Europe/Moscow'";
  13.    
  14.     protected $_db;
  15.     protected static $_dbInstance;
  16.     protected static $_instance;
  17.    
  18.     protected function _connect()
  19.     {
  20.         if (null !== self::$_dbInstance) return self::$_dbInstance;
  21.        
  22.         try {
  23.             # MySQL через PDO_MYSQL  
  24.             $driver_options = array(
  25.                 PDO::MYSQL_ATTR_INIT_COMMAND => $this->_init_command,
  26.             );
  27.             self::$_dbInstance = new PDO("mysql:host={$this->host};dbname={$this->_dbname}", $this->_user, $this->_pass, $driver_options);
  28.             self::$_dbInstance->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
  29.             self::$_dbInstance->exec("SET names utf8");
  30.         }
  31.         catch(PDOException $e) {  
  32.             echo $e->getMessage();
  33.         }
  34.         return self::$_dbInstance;
  35.     }
  36.        
  37.     public function __destruct()
  38.     {
  39.         self::$_dbInstance = null;
  40.     }
  41.    
  42.     public static function getDbAdapter()
  43.     {
  44.         if (!self::$_dbInstance) {
  45.             self::$_instance = new self();
  46.             self::$_dbInstance = self::$_instance->_connect();
  47.         }
  48.         return self::$_dbInstance;
  49.     }
  50. }
  51.  
  52. /* mysql queries
  53. $db = new mysql;
  54. $db->insert( 'magazin', array( 'filter' => 'test', 'id_user' => '0', 'author' => 'robot', 'data' => new mysql_expr('NOW()') ) );
  55. $db->update( 'magazin', array( 'filter' => 'test', 'id_user' => '0', 'author' => 'robot', 'data' => new mysql_expr('NOW()') ), array('id_user' => 0) );
  56. $db->query("SELECT FROM `magazin`")
  57. */
  58. class mysql
  59. {  
  60.     public function __construct()
  61.     {
  62.         $this->_db = pdo_mysql::getDbAdapter();
  63.     }
  64.    
  65.     public function fetchAll($q, $where = false)
  66.     {
  67.         $STH = $this->_query($q, $where);
  68.         return $STH->fetchAll();
  69.     }
  70.    
  71.     public function fetch($q, $where = false)
  72.     {
  73.         $STH = $this->_query($q, $where);
  74.         if ($STH->rowCount()) {
  75.             return $STH->fetch();
  76.         }
  77.         return null;
  78.     }
  79.    
  80.     public function fetchOne($q, $where = false)
  81.     {
  82.         $STH = $this->_query($q, $where);
  83.        
  84.     }
  85.    
  86.     public function fetchPairs($q, $where = false)
  87.     {
  88.         $rows = array();
  89.         $STH = $this->_query($q, $where);
  90.         if ($STH->rowCount()) {
  91.             while($row = $STH->fetch()) {
  92.                 $row_key1 = current($row);
  93.                 $row_key2 = next($row);
  94.                 if (!$row_key2) $row_key2 = $row_key1;
  95.                 $rows[$row_key1] = $row_key2;
  96.             }
  97.         }
  98.         return $rows;
  99.     }
  100.  
  101.     function exec($q)
  102.     {
  103.         $this->_db->exec($q);
  104.     }
  105.    
  106.     // old function, delete please from all code
  107.     function query($q, $where = false)
  108.     {
  109.         return $this->fetchAll($q, $where);
  110.     }
  111.    
  112.     // old function, delete please from all code
  113.     function query_one($q, $where = false)
  114.     {
  115.         return $this->fetchOne($q, $where);
  116.     }
  117.  
  118.     // old function, delete please from all code
  119.    function query_clear($q)
  120.     {
  121.         return $this->exec($q);
  122.     }
  123.    
  124.     protected function _query($sql, $where = false)
  125.     {
  126.         try {
  127.             if ($where) {
  128.                 $sql = str_replace('%where%', 'WHERE ' . $this->_where($where), $sql);
  129.             } else {
  130.                 $sql = str_replace('%where%', '', $sql);
  131.             }
  132.             $STH = $this->_db->prepare($sql);
  133.             $STH->setFetchMode(PDO::FETCH_ASSOC);
  134.             $STH->execute();
  135.         }
  136.         catch(PDOException $e) {
  137.             $error = $STH->errorInfo();
  138.             trigger_error("Error in mysql->_query: " . var_export($error, true));
  139.         }
  140.        
  141.         return $STH;
  142.     }
  143.    
  144.     function insert($table, $insert_vals)
  145.     {
  146.         $keys = array_keys($insert_vals);
  147.         $vals = $insert_vals;
  148.         array_walk($vals, function(&$val, $key, &$insert_vals) {
  149.             if ($val instanceof mysql_expr) {
  150.                 $val = $val->__toString();
  151.                 unset($insert_vals[$key]);
  152.             } else {
  153.                 $val = ':' . $key;
  154.             }
  155.         }, $insert_vals);
  156.         $sql = "INSERT INTO `{$table}` (`" . implode('`, `', $keys) . "`) VALUES (" . implode(', ', $vals) . ")";
  157.        
  158.         try {
  159.             $STH = $this->_db->prepare($sql);
  160.             $STH = $this->_bindArrayValue($STH, $insert_vals);
  161.             $STH->execute();
  162.         }
  163.         catch(PDOException $e) {
  164.             $error = $STH->errorInfo();
  165.             trigger_error("Error in mysql->insert: " . var_export($error, true));
  166.         }
  167.     }
  168.  
  169.     // $this->simple_query_clear("UPDATE tovars SET s_from = '$from',s_to = '$to', r_status = '$status', kol = '$kol' WHERE id = '$id' LIMIT 1");
  170.     function update($table, $set_vals, $where = array(), $limit = 1)
  171.     {
  172.         $vals = $set_vals;
  173.         array_walk($vals, function(&$val, $key, &$set_vals) {
  174.             // `key` = ...
  175.             $ret_val = '`'.$key.'`' . ' = ';
  176.             if ($val instanceof mysql_expr) {
  177.                 $ret_val .= $val->__toString();
  178.                 unset($set_vals[$key]);
  179.             } else {
  180.                 $ret_val .= ':' . $key;
  181.             }
  182.             $val = $ret_val;
  183.         }, $set_vals);
  184.         $sql = "UPDATE `{$table}` SET ".implode(', ', $vals);
  185.        
  186.         if ($where) {
  187.             $sql .= ' WHERE ' . $this->_where($where);
  188.         }
  189.         if ($limit) {
  190.             $sql .= ' LIMIT ' . $limit;
  191.         }
  192.         try {
  193.             $STH = $this->_db->prepare($sql);
  194.             //var_dump($set_vals);die;
  195.             $STH = $this->_bindArrayValue($STH, $set_vals);
  196.             $STH->execute();
  197.         }
  198.         catch(PDOException $e) {
  199.             $error = $STH->errorInfo();
  200.             trigger_error("Error in mysql->update: " . var_export($error, true));
  201.         }
  202.     }
  203.    
  204.     public function delete($table, $where, $limit = 1)
  205.     {
  206.         $where = $this->_where($where);
  207.         $sql = "DELETE FROM `{$table}` WHERE {$where} LIMIT {$limit}";
  208.         try {
  209.             $STH = $this->_db->prepare($sql);
  210.             $STH->execute();
  211.         }
  212.         catch(PDOException $e) {
  213.             $error = $STH->errorInfo();
  214.             trigger_error("Error in mysql->delete: " . var_export($error, true));
  215.         }
  216.     }
  217.    
  218.     public function getDbAdapter()
  219.     {
  220.         return $this->_db;
  221.     }
  222.    
  223.     public function escape($string)
  224.     {
  225.         return $this->getDbAdapter()->quote($string);
  226.     }
  227.    
  228.     protected function _where($expr)
  229.     {
  230.         if (is_array($expr)) {
  231.             foreach ($expr as $key => $val) {
  232.                 if ($val instanceof mysql_expr) {
  233.                     $val = $val->__toString();
  234.                 } else if (is_string($key)) {
  235.                     $val = $this->_db->quote($val);
  236.                 }
  237.                 if (is_int($key)) {
  238.                     $where_vals[] = "({$val})";
  239.                 } else {
  240.                     $where_vals[] = "(`{$key}` = {$val})";
  241.                 }
  242.             }
  243.             $expr = implode(' AND ', $where_vals);
  244.         }
  245.         return $expr;
  246.     }
  247.    
  248.     protected function _bindArrayValue($req, $array, $typeArray = false)
  249.     {
  250.         if(is_object($req) && ($req instanceof PDOStatement))
  251.         {
  252.             foreach($array as $key => $value)
  253.             {
  254.                 if($typeArray && isset($typeArray[$key])) {
  255.                     $req->bindValue(':' . $key, $value, $typeArray[$key]);
  256.                 } else {
  257.                     if(is_int($value))
  258.                         $param = PDO::PARAM_INT;
  259.                     elseif(is_bool($value))
  260.                         $param = PDO::PARAM_BOOL;
  261.                     elseif(is_null($value))
  262.                         $param = PDO::PARAM_NULL;
  263.                     elseif(is_string($value))
  264.                         $param = PDO::PARAM_STR;
  265.                     else
  266.                         $param = FALSE;
  267.                        
  268.                     if($param)
  269.                         $req->bindValue(':' . $key, $value, $param);
  270.                 }
  271.             }
  272.             return $req;
  273.         }
  274.     }
  275.  
  276. }
  277.  
  278. class mysql_expr
  279. {
  280.     protected $_expression;
  281.    
  282.     public function __construct($expression)
  283.     {
  284.         $this->_expression = (string) $expression;
  285.     }
  286.    
  287.     public function __toString()
  288.     {
  289.         return $this->_expression;
  290.     }
  291.  
  292. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement