Advertisement
Guest User

Untitled

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