Advertisement
Guest User

Untitled

a guest
Jul 19th, 2017
445
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 11.97 KB | None | 0 0
  1. <?php
  2. /*
  3.  *      class.db.php
  4.  *      
  5.  *      Copyright 2011 Andrei Aleksandovich Bagrintsev <a.bagrintsev@imedia.ru>
  6.  *      
  7.  *      This program is free software; you can redistribute it and/or modify
  8.  *      it under the terms of the GNU General Public License as published by
  9.  *      the Free Software Foundation; either version 2 of the License, or
  10.  *      (at your option) any later version.
  11.  *      
  12.  *      This program is distributed in the hope that it will be useful,
  13.  *      but WITHOUT ANY WARRANTY; without even the implied warranty of
  14.  *      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  15.  *      GNU General Public License for more details.
  16.  *      
  17.  *      You should have received a copy of the GNU General Public License
  18.  *      along with this program; if not, write to the Free Software
  19.  *      Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
  20.  *      MA 02110-1301, USA.
  21.  */
  22.  
  23. require ('config.db.php');
  24.  
  25. class db_i {
  26.    
  27.     public $mysqli = null;
  28.     private $init_time = 0;
  29.     private $current_db = '';
  30.     private $log = array ();
  31.     public $no_tpl_slash = false;
  32.     public $table_prefix = '';
  33.     public $last_insert_id = 0;
  34.     public $no_quote = array ();
  35.     public $query_info = array ();
  36.    
  37.     function __construct ()
  38.     {
  39.         if (!extension_loaded('mysqli'))
  40.             exit ("Can't find MySQLi extension. Try run `php -m` in your server terminal.");
  41.        
  42.         $this->init_time = $this->get_mt();
  43.         $this->do_log ('info', array ('data'=>'Starting generic Database layer with MySQLi extension. Version 0.2.'));
  44.        
  45.         if (!$GLOBALS['db_init'])
  46.         {
  47.             $GLOBALS['db'] =& $this;
  48.         }
  49.     }
  50.    
  51.     function __destruct ()
  52.     {
  53.         if ( !is_null($this->mysqli) && !mysqli_connect_errno() )
  54.             $this->mysqli->close();
  55.     }
  56.    
  57.     private function get_mt ()
  58.     {
  59.         list($usec, $sec) = explode(" ", microtime());
  60.         return ((float)$usec + (float)$sec);
  61.     }
  62.    
  63.     function init ($db_host=null, $db_user=null, $db_pass=null, $db_name=false, $force_init=false)
  64.     {
  65.         if ($force_init || $GLOBALS['db_init']) return;
  66.        
  67.         $conn_time = $this->get_mt();
  68.        
  69.         $this->mysqli = new mysqli ($db_host, $db_user, $db_pass, $db_name);
  70.        
  71.         if (mysqli_connect_errno())
  72.         {
  73.             // Error!
  74.             $this->do_log ('error',array('data'=>mysqli_connect_error()));
  75.             return false;
  76.         }
  77.         $conn_time = $this->get_mt() - $conn_time;
  78.        
  79.         $this->send_charset ($GLOBALS['config']['db_charset']);
  80.        
  81.         $this->do_log ('info',array('data'=>'Connected to server "'.$db_host.'" in '.round($conn_time,4).' sec'));
  82.        
  83.         $GLOBALS['db_init'] = true;
  84.        
  85.         if ($db_name)
  86.             return $this->select_db ($db_name);
  87.         return true;
  88.     }
  89.    
  90.     function db_table_name ($table)
  91.     {
  92.         $ss = ($this->no_tpl_slash?'':'`');
  93.         return ($this->current_db?$ss.$this->current_db.$ss.'.':'').$ss.$this->table_prefix.$table.$ss;
  94.     }
  95.    
  96.     function get_html_log ($show_types = array('info','error','query'))
  97.     {
  98.         $out = '<table cellpadding="3" cellspacing="0" border="1" width="100%">';
  99.         $out.= '<tr><th align="center">#</th><th align="center">Type</th><th>Time</th><th>Record</th></tr>';
  100.         foreach ($this->log as $n=>$rec)
  101.         {
  102.             if (!in_array($rec['type'], $show_types))
  103.                 continue;
  104.             $out .= '<tr><td align="center">'.($n+1).'</td>';
  105.             if ($rec['type'] == 'info')
  106.             {
  107.                 $out .= '<td align="center" style="color:navy">Info</td>';
  108.                 $out .= '<td>+ '.round($rec['time']-$this->init_time,4).' sec</td>';
  109.                 $out .= '<td><code>'.$rec['data'].'</code></td>';
  110.             }
  111.             if ($rec['type'] == 'error')
  112.             {
  113.                 $out .= '<td align="center" style="color:red">Error</td>';
  114.                 $out .= '<td>+ '.round($rec['time']-$this->init_time,4).' sec</td>';
  115.                 $out .= '<td><code>'.$rec['data'].'</code></td>';
  116.             }
  117.             if ($rec['type'] == 'query')
  118.             {
  119.                 $out .= '<td align="center" style="color:green">Query</td>';
  120.                 $out .= '<td>+ '.round($rec['time']-$this->init_time,4).' sec</td>';
  121.                 // Build query info
  122.                 $out .= '<td>';
  123.                 $out .= '<b>Query</b> : <code>'.$rec['query'].'</code><br/>';
  124.                 if (@$rec['error'])
  125.                 {
  126.                     $out .= '<b>Error</b> : <code style="color:red;">'.$rec['error'].'</code><br/>';
  127.                 }
  128.                 if (!@$rec['error'])
  129.                 {
  130.                     $out .= '<b>Result</b> : <b><code style="font-weight:bold;font-size:large;">'.$rec['result_rows'].'</code></b> rows<br/>';
  131.                 }
  132.                 if (@$rec['query_time'])
  133.                 {
  134.                     $out .= '<b>Time</b> : <code>'.round($rec['query_time'],4).'</code> sec<br/>';
  135.                 }
  136.                 $out .= '</td>';
  137.             }
  138.             $out .= '</tr>';
  139.         }
  140.         $out.='</table>';
  141.         return $out;
  142.     }
  143.    
  144.     function quotes ($in)
  145.     {
  146.         if (!is_numeric($in))
  147.         {
  148.             $in = "'".$in."'";
  149.         }
  150.        
  151.         return $this->escape_string ($in);
  152.     }
  153.    
  154.     function select_db ($db_name)
  155.     {
  156.         if (!$this->mysqli->select_db($db_name))
  157.         {
  158.             $this->do_log ('error',array('data'=>$this->mysqli->error));
  159.             return false;
  160.         } else {
  161.             $this->do_log ('info',array('data'=>"Selection DB '".$db_name."' is OK"));
  162.             $this->current_db = $db_name;
  163.             return true;
  164.         }
  165.     }
  166.    
  167.     function escape_string ($txt)
  168.     {
  169.         // Init DB if not connected
  170.         if (is_null ($this->mysqli))
  171.         {
  172.             $this->init($GLOBALS['config']['db_host'],
  173.                         $GLOBALS['config']['db_user'],
  174.                         $GLOBALS['config']['db_pass'],
  175.                         $GLOBALS['config']['db_base']);
  176.         }
  177.        
  178.         return $this->mysqli->real_escape_string ($txt);
  179.     }
  180.  
  181.     // QUERY FUNCTIONS
  182.  
  183.     function db_query ($query, $table='manual', $query_info=false)
  184.     {
  185.         // Init DB if not connected
  186.         if (is_null ($this->mysqli))
  187.         {
  188.             if (!$this->init($GLOBALS['config']['db_host'],
  189.                         $GLOBALS['config']['db_user'],
  190.                         $GLOBALS['config']['db_pass'],
  191.                         $GLOBALS['config']['db_base']))
  192.             return false;
  193.         }
  194.  
  195.         // do query
  196.         $qw_time = $this->get_mt();
  197.         $res = $this->mysqli->query ($query, MYSQLI_USE_RESULT);
  198.         $qw_time = $this->get_mt()-$qw_time;
  199.        
  200.         if (!$res || $this->mysqli->errno)
  201.         {
  202.             // Error!
  203.             $this->do_log ('query',array('query'=>$query, 'query_time'=>$qw_time, 'result_rows'=>0, 'error'=>$this->mysqli->error));
  204.             return false;
  205.         }
  206.        
  207.         // if query type is INSERT or similar, method query() returning bool TRUE or FALSE. We returning it to sub-methods of class.
  208.         if (is_bool ($res))
  209.         {
  210.             $out_data = $res;
  211.             $result_rows = 1;
  212.             // Query have insert type? Writing-in last insert id.
  213.             if ($this->mysqli->insert_id)
  214.                 $this->last_insert_id = $this->mysqli->insert_id;
  215.         } else {
  216.             // Prepare data
  217.             while ($line = $res->fetch_assoc())
  218.             {
  219.                 $out_data[] = $line;
  220.             }
  221.  
  222.             $result_rows = $res->num_rows;
  223.         }
  224.  
  225.         if ($query_info)
  226.         {
  227.             $query_info = array ('current_field'=>$res->current_field, 'field_count'=>$res->field_count,
  228.             'lenghts'=>$res->field_count, 'num_rows'=>$res->num_rows, 'type'=>$res->type);
  229.            
  230.             $this->query_info = $query_info;
  231.         }
  232.  
  233.         $this->do_log ('query',array('query'=>$query, 'query_time'=>$qw_time, 'result_rows'=>$result_rows, 'error'=>false));
  234.        
  235.         if (is_object($res))
  236.             $res->free ();
  237.        
  238.         return $out_data;
  239.     }
  240.    
  241.     private function do_log ($type, $data)
  242.     {
  243.         if (!@$data['type'])
  244.             $data['type'] = $type;
  245.            
  246.         if (!@$data['time'])
  247.             $data['time'] = $this->get_mt();
  248.        
  249.         $this->log[] = $data;
  250.     }
  251.    
  252.     function send_charset ($charset = 'UTF8')
  253.     {
  254.         $this->mysqli->set_charset ($charset);
  255.         $this->do_log ('info', array ('data'=>"Selection ".$charset." charset"));
  256.     }
  257.  
  258.     function select ($table, $what = '*', $exp = false)
  259.     {
  260.         if (is_array($what))
  261.         {
  262.             $what = '`'.implode('`,`', $what).'`';
  263.         }
  264.         if (!$exp) $exp = '1';
  265.  
  266.         $query = 'SELECT '.$what.' FROM '.$this->db_table_name($table).' WHERE '.$exp;
  267.        
  268.         return $this->db_query($query, $table);
  269.     }
  270.    
  271.    
  272.     function select_one ($table, $what = '*', $id, $id_text = 'id')
  273.     {
  274.         if (is_array($what))
  275.         {
  276.             $what = '`'.implode('`,`', $what).'`';
  277.         }
  278.         $exp = '`'.$id_text.'` = '.$this->quotes($id);
  279.  
  280.         $query = 'SELECT '.$what.' FROM '.$this->db_table_name($table).' WHERE '.$exp;
  281.         $res = $this->db_query($query, $table, false);
  282.         if (!@$res[0]) return $this->return_on_false;
  283.         return $res[0];
  284.     }
  285.  
  286.     function insert ($table, $data, $no_quote = array ())
  287.     {
  288.         $upd_data = array ();
  289.         $upd_keys = array ();
  290.         foreach ($data as $k=>$v)
  291.         {
  292.             if (!in_array($k, $no_quote))
  293.                 $v = "'".$this->escape_string ($v)."'";
  294.             $upd_keys[] = '`'.$k.'`';
  295.             $upd_data[] = $v;
  296.         }
  297.         $query = 'INSERT INTO '.$this->db_table_name($table).' ('.implode(',',$upd_keys).') VALUES ('.implode(',',$upd_data).')';
  298.        
  299.         // if query was success, return to user last insert id
  300.         if ($this->db_query($query, $table))
  301.             return $this->last_insert_id;
  302.     }
  303.  
  304.     function insert_id ()
  305.     {
  306.         if ($this->last_insert_id)
  307.             return $this->last_insert_id;
  308.         elseif ($this->mysqli->insert_id)
  309.             return $this->mysqli->insert_id;
  310.         else return false;
  311.     }
  312.  
  313.     function update_by_id ($table, $id, $data, $id_text = 'id', $no_quote = array ())
  314.     {
  315.         $upd_data = array ();
  316.         foreach ($data as $k=>$v)
  317.         {
  318.             if (!in_array($k, $no_quote))
  319.                 $v = $this->quotes ($v);
  320.             $upd_data[] = '`'.$k.'`='.$v;
  321.         }
  322.         $query = 'UPDATE '.$this->db_table_name($table).' SET '.implode(',',$upd_data).' WHERE `'.$id_text.'`='.$this->quote ($id);
  323.         return $this->db_query($query, $table);
  324.     }
  325.  
  326.     function update_by_exp ($table, $data, $exp='1')
  327.     {
  328.         $upd_data = array ();
  329.         $upd_keys = array ();
  330.         foreach ($data as $k=>$v)
  331.         {
  332.             if (!in_array($k, $this->no_quote))
  333.                 $v = $this->quotes ($v);
  334.             $upd_data[] = '`'.$k.'`='.$v;
  335.         }
  336.         $query = 'UPDATE '.$this->db_table_name($table).' SET '.implode(',',$upd_data).' WHERE '.$exp;
  337.         return $this->db_query($query, $table);
  338.     }
  339.    
  340.     function delete ($table, $what = false)
  341.     {
  342.         if ($table)
  343.             $table_name = " FROM `".$table."`";
  344.  
  345.         if (is_array($what))
  346.         {
  347.             //...
  348.             foreach ($what as $k=>$v)
  349.             {
  350.                 $where[] = "`".$k."`=".$this->quotes ($v);
  351.             }
  352.             $where = implode (' AND ', $where);
  353.         } elseif (!$what) {
  354.             $where = 1;
  355.         } else {
  356.             $where = $what;
  357.         }
  358.  
  359.         return $this->db_query ("DELETE".( ($table)?$table_name:'')." WHERE ".$where, $table );
  360.     }
  361.    
  362.     function count ($table, $exp = false)
  363.     {
  364.         if (!$exp) $exp = '1';
  365.         $query = 'SELECT COUNT(*) FROM '.$this->db_table_name($table).' WHERE '.$exp;
  366.         $res = $this->db_query($query, $table, false);
  367.         if (!@$res[0]['COUNT(*)']) return $this->return_on_false;
  368.         return $res[0]['COUNT(*)'];
  369.     }
  370. }
  371.  
  372. function select_db ($name)
  373. {
  374.     $GLOBALS['db']->select_db ($name) or die ('Database change to "'.$name.'" failed!');
  375.     return true;
  376. }
  377.  
  378. function db_c ($db)
  379. {
  380.     $GLOBALS['db']->current_db = $db;
  381. }
  382.  
  383. function db_select ($table, $what = '*', $exp = false)
  384. {
  385.     return $GLOBALS['db']->select($table, $what, $exp);
  386. }
  387.  
  388. function db_select_one ($table, $what = '*', $id, $id_text = 'id')
  389. {
  390.     return $GLOBALS['db']->select_one($table, $what, $id, $id_text);
  391. }
  392.  
  393. function db_count ($table, $exp = false)
  394. {
  395.     return $GLOBALS['db']->count($table, $exp);
  396. }
  397.  
  398. function db_insert ($table, $data, $no_quote = array ())
  399. {
  400.     return $GLOBALS['db']->insert($table, $data, $no_quote);
  401. }
  402.  
  403. function db_insert_id ()
  404. {
  405.     return $GLOBALS['db']->insert_id();
  406. }
  407.  
  408. function db_update_by_id ($table, $id, $data, $id_text = 'id', $no_quote = array ())
  409. {
  410.     return $GLOBALS['db']->update_by_id ($table, $id, $data, $id_text, $no_quote);
  411. }
  412.  
  413. function db_update_by_exp ($table, $data, $exp='1')
  414. {
  415.     return $GLOBALS['db']->update_by_exp ($table, $data, $exp);
  416. }
  417.  
  418. function db_query ($query, $table='direct_api', $drop = true)
  419. {
  420.     return $GLOBALS['db']->db_query ($query, $table, $drop);
  421. }
  422.  
  423. function db_stats ()
  424. {
  425.     return $GLOBALS['db']->log;
  426. }
  427.  
  428. function db_show_tables ($table = false)
  429. {
  430.     return $GLOBALS['db']->show_tables ($table);
  431. }
  432.  
  433. // alias for compatibility with old programs
  434. function db_del_row ($table, $where = false)
  435. {
  436.     return $GLOBALS['db']->delete ($table, $where);
  437. }
  438.  
  439. function db_delete ($table, $where = false)
  440. {
  441.     return $GLOBALS['db']->delete($table, $where);
  442. }
  443.  
  444. function real_escape_string ($txt)
  445. {
  446.     return $GLOBALS['db']->escape_string ($txt);
  447. }
  448.  
  449. function db_get_last_query_info ()
  450. {
  451.     if ($GLOBALS['db']->query_info)
  452.         return $GLOBALS['db']->query_info;
  453.     else return NULL;
  454. }
  455.  
  456. if (!$GLOBALS['db_init'])
  457.     $GLOBALS['db'] = new db_i;
  458. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement