Guest User

Untitled

a guest
Jun 1st, 2018
335
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 10.12 KB | None | 0 0
  1. <?php
  2.  
  3. class MySQL {
  4.     # link
  5.    private $link;
  6.     # connection info
  7.    private $hostname, $port, $user, $password, $db_name, $table_prefix, $charset, $collation;
  8.     # query results
  9.    private $affected_rows, $num_rows, $insert_id;
  10.     # query log
  11.    private $count_queries = 0;
  12.     private $queries = array();
  13.  
  14.     /**
  15.      * @param $hostname
  16.      * @param $port
  17.      * @param $user
  18.      * @param $password
  19.      * @param $db_name
  20.      * @param $table_prefix
  21.      * @param $charset
  22.      * @param $collation
  23.      */
  24.     public function __construct($hostname, $port, $user, $password, $db_name, $table_prefix, $charset, $collation) {
  25.         $this->hostname = $hostname;
  26.         $this->port = $port;
  27.         $this->user = $user;
  28.         $this->password = $password;
  29.         $this->db_name = $db_name;
  30.         $this->table_prefix = $table_prefix;
  31.         $this->charset = $charset;
  32.         $this->collation = $collation;
  33.     }
  34.  
  35.     /**
  36.      * Destructor
  37.      */
  38.     function __destruct() {
  39.         (isset($this->link)) ? @mysql_close($this->link) : false;
  40.     }
  41.  
  42.     /**
  43.      * Open database connection
  44.      * @return  bool
  45.      */
  46.     public function connect() {
  47.         if (empty($this->hostname)) {
  48.             return false;
  49.         }
  50.  
  51.         $this->link = @mysql_connect($this->hostname . ':' . $this->port, $this->user, $this->password);
  52.  
  53.         if (!$this->link) {
  54.             $this->_error('Connection error: ' . mysql_error());
  55.         }
  56.  
  57.         if (@mysql_select_db($this->db_name, $this->link) === FALSE) {
  58.             $this->_error('Database selection error: ' . mysql_error($this->link));
  59.         }
  60.  
  61.  
  62.         $this->query('SET NAMES \'' . $this->charset . '\' COLLATE \'' . $this->collation . '\' ;');
  63.  
  64.         return true;
  65.     }
  66.  
  67.     /**
  68.      * Exec database query
  69.      *
  70.      * @param string query string
  71.      * @return  mixed
  72.      */
  73.     function query($sql) {
  74.         # Benchmark start
  75.        $query_time = microtime(TRUE);
  76.  
  77.  
  78.         $return = TRUE;
  79.         if (($result = @mysql_query($sql, $this->link)) === FALSE) {
  80.             $this->_error('Query error - ' . mysql_error($this->link) . ' (' . $sql . ')');
  81.         }
  82.         if (preg_match("/^\\s*(insert|delete|update|replace|alter|set) /i", $sql)) {
  83.             $this->affected_rows = @mysql_affected_rows($this->link);
  84.  
  85.             if (preg_match("/^\\s*(insert|replace) /i", $sql)) {
  86.                 $this->insert_id = @mysql_insert_id($this->link);
  87.             }
  88.         } else {
  89.             $this->num_rows = mysql_num_rows($result);
  90.             $return = array();
  91.  
  92.             if ($this->num_rows != 0) {
  93.                 while ($row = @mysql_fetch_assoc($result)) {
  94.                     $return[] = $row;
  95.                 }
  96.             }
  97.             @mysql_free_result($result);
  98.         }
  99.  
  100.         # Query logging
  101.        $this->count_queries++;
  102.         $this->queries[] = array('sql' => $sql, 'result' => $return, # benchmark end
  103.            'time' => number_format((microtime(true) - $query_time), 6) . 'sec');
  104.  
  105.         return $return;
  106.     }
  107.  
  108.     /**
  109.      * Count values
  110.      * @param string table name
  111.      * @param array Associative array row=>value
  112.      * @return int
  113.      */
  114.     public function count($table, $where = array()) {
  115.         $table = $this->prefix() . $table;
  116.  
  117.         $query = 'SELECT COUNT(*) FROM `' . $table . '` ';
  118.         if (!empty($where)) {
  119.             $query .= 'WHERE ' . $this->prepare_where($where);
  120.         }
  121.  
  122.         $result = mysql_query($query, $this->link);
  123.         return mysql_result($result, 0);
  124.     }
  125.  
  126.     /**
  127.      * Select record from table (simple WHERE)
  128.      * @param $table
  129.      * @param array $where
  130.      * @param bool $limit
  131.      * @param bool $offset
  132.      * @return mixed
  133.      */
  134.     public function select($table, $where = array(), $limit = FALSE, $offset = FALSE) {
  135.         $table = $this->prefix() . $table;
  136.         if (($where = $this->prepare_where($where)) === FALSE) {
  137.             $where = '1=1';
  138.         }
  139.         return $this->query('SELECT * FROM `' . $table . '` WHERE ' . $where . ' ' . $this->prepare_limit($limit, $offset) . ' ;');
  140.     }
  141.  
  142.     /**
  143.      * Insert record
  144.      * @param   string
  145.      * @param   array
  146.      * @return  bool
  147.      */
  148.     public function insert($table, $data = array()) {
  149.         $table = $this->prefix() . $table;
  150.         if (($set = $this->prepare_set($data)) === FALSE) {
  151.             return FALSE;
  152.         }
  153.         return $this->query('INSERT INTO `' . $table . '` SET ' . $set . ' ;');
  154.     }
  155.  
  156.     /**
  157.      * Update record in table (simple WHERE)
  158.      * @param $table
  159.      * @param array $set
  160.      * @param array $where
  161.      * @param int $limit
  162.      * @param bool $offset
  163.      * @return bool|mixed
  164.      */
  165.     public function update($table, $set = array(), $where = array(), $limit = 1, $offset = FALSE) {
  166.         $table = $this->prefix() . $table;
  167.         if (($set = $this->prepare_set($set)) === FALSE) {
  168.             return FALSE;
  169.         }
  170.         if (($where = $this->prepare_where($where)) === FALSE) {
  171.             $where = '1=1';
  172.         }
  173.         return $this->query('UPDATE `' . $table . '` SET ' . $set . ' WHERE ' . $where . ' ' . $this->prepare_limit($limit, $offset) . ' ;');
  174.     }
  175.  
  176.     /**
  177.      * Delete records from table (simple WHERE)
  178.      * @param $table
  179.      * @param array $where
  180.      * @param int $limit
  181.      * @param bool $offset
  182.      * @return mixed
  183.      */
  184.     public function delete($table, $where = array(), $limit = 1, $offset = FALSE) {
  185.         $table = $this->prefix() . $table;
  186.         if (($where = $this->prepare_where($where)) === FALSE) {
  187.             $where = '1=1';
  188.         }
  189.         return $this->query('DELETE FROM `' . $table . '` WHERE ' . $where . ' ' . $this->prepare_limit($limit, $offset) . ' ;');
  190.     }
  191.  
  192.     /**
  193.      * Escape string
  194.      * @param   mixed
  195.      * @return  mixed
  196.      */
  197.     public function escape($str) {
  198.         if (is_array($str)) {
  199.             foreach ($str as $key => $value) {
  200.                 $str[$key] = $this->escape($value);
  201.             }
  202.             return $str;
  203.         }
  204.  
  205.         if (function_exists('mysql_real_escape_string') && is_resource($this->link)) {
  206.             $str = mysql_real_escape_string($str, $this->link);
  207.         } else {
  208.             $str = addslashes($str);
  209.         }
  210.         return $str;
  211.     }
  212.  
  213.     /**
  214.      * Get affected rows
  215.      * @return  int
  216.      */
  217.     function getAffectedRows() {
  218.         return $this->affected_rows;
  219.     }
  220.  
  221.     /**
  222.      * Get num selected rows
  223.      * @return  int
  224.      */
  225.     public function getNumRows() {
  226.         return $this->num_rows;
  227.     }
  228.  
  229.     /**
  230.      * Get last inserted id
  231.      * @return  int
  232.      */
  233.     public function getInsertId() {
  234.         return $this->insert_id;
  235.     }
  236.  
  237.     /**
  238.      * Return query history
  239.      * @return array
  240.      */
  241.     public function getQueries() {
  242.         return $this->queries;
  243.     }
  244.  
  245.     /**
  246.      * Return count queries
  247.      * @return int
  248.      */
  249.     public function getCountQueries() {
  250.         return $this->count_queries;
  251.     }
  252.  
  253.     /**
  254.      * Get table prefix
  255.      * @return string
  256.      */
  257.     public function prefix() {
  258.         return $this->table_prefix;
  259.     }
  260.  
  261.     /**
  262.      *
  263.      *
  264.      * @param   string
  265.      * @return  string
  266.      */
  267.     private function prepare_query($sql) {
  268.         // "DELETE FROM TABLE" возвращает 0 в затронутых строка
  269.         // это решение исправляет этот недостаток
  270.         if (preg_match('/^\s*DELETE\s+FROM\s+(\S+)\s*$/i', $sql)) {
  271.             $sql = preg_replace("/^\s*DELETE\s+FROM\s+(\S+)\s*$/", "DELETE FROM \\1 WHERE 1=1", $sql);
  272.         }
  273.         return $sql;
  274.     }
  275.  
  276.     /**
  277.      * Подготавливает данные для SET и UPDATE
  278.      *
  279.      * @param   array
  280.      * @return  string
  281.      */
  282.     private function prepare_set($data = array()) {
  283.         if (!is_array($data) || count($data) == 0) {
  284.             return FALSE;
  285.         }
  286.  
  287.         $bits = array();
  288.         foreach ($data as $key => $value) {
  289.             $bits[] = "`$key` = '" . $this->escape($value) . "'";
  290.         }
  291.         return implode(', ', $bits);
  292.     }
  293.  
  294.     /**
  295.      * Подготавливает данные для WHERE
  296.      *
  297.      * @param   array
  298.      * @return  string
  299.      */
  300.     private function prepare_where($data = array()) {
  301.         if (!is_array($data) || count($data) == 0) {
  302.             return FALSE;
  303.         }
  304.  
  305.         $bits = array();
  306.         foreach ($data as $key => $value) {
  307.  
  308.             if (!$this->_has_operator($key)) {
  309.                 $key = '`' . $key . '` =';
  310.             } else {
  311.                 $alias = '';
  312.                 if (strpos($key, ' ') !== FALSE) {
  313.                     $alias = strstr($key, ' ');
  314.                     $key = substr($key, 0, -strlen($alias));
  315.                 }
  316.                 $key = '`' . $key . '`' . $alias;
  317.             }
  318.  
  319.             $escape = TRUE;
  320.             if (strpos($key, '#') !== FALSE) {
  321.                 $escape = FALSE;
  322.                 $key = str_replace('#', '', $key);
  323.             }
  324.  
  325.             $bits[] = $key . ' ' . ($escape ? '\'' . $this->escape($value) . '\'' : $value); //;
  326.         }
  327.         return implode(' AND ', $bits);
  328.     }
  329.  
  330.     /**
  331.      * Prepare data for LIMIT
  332.      *
  333.      * @param   int
  334.      * @param   int
  335.      * @return  string
  336.      */
  337.     private function prepare_limit($limit = FALSE, $offset = FALSE) {
  338.         if ($limit === FALSE) {
  339.             return '';
  340.         }
  341.         $offset = ($offset === FALSE) ? '' : ', ' . $offset;
  342.         return 'LIMIT ' . $limit . $offset;
  343.     }
  344.  
  345.     /**
  346.      *
  347.      *
  348.      * @param   string
  349.      * @return  bool
  350.      */
  351.     private function _has_operator($str) {
  352.         $str = trim($str);
  353.         if (!preg_match("/(\s|<?|!|=|is null|is not null)/i", $str)) {
  354.             return FALSE;
  355.         }
  356.         return TRUE;
  357.     }
  358.  
  359.     /**
  360.      * Show database error
  361.      * @param string Error message
  362.      * @access private
  363.      * @return void
  364.      */
  365.     private function _error($message) {
  366.         throw new Exception('MySQL Error: ' . $message);
  367.     }
  368.  
  369. }
Add Comment
Please, Sign In to add comment