Advertisement
Krokit

MySQLi to PDO

Sep 5th, 2015
384
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 12.12 KB | None | 0 0
  1. class DBLayer
  2. {
  3.     var $prefix;
  4.     var $link_id;
  5.     var $query_result;
  6.  
  7.     var $saved_queries = array();
  8.     var $num_queries = 0;
  9.  
  10.     var $datatype_transformations = array(
  11.         '/^SERIAL$/'    =>  'INT(10) UNSIGNED AUTO_INCREMENT'
  12.     );
  13.  
  14.  
  15.     function DBLayer($db_host, $db_username, $db_password, $db_name, $db_prefix, $p_connect)
  16.     {
  17.         $this->prefix = $db_prefix;
  18.  
  19.         // Was a custom port supplied with $db_host?
  20.         if (strpos($db_host, ':') !== false)
  21.             list($db_host, $db_port) = explode(':', $db_host);
  22.  
  23.         $p_connect = $p_connect && version_compare(PHP_VERSION, '5.3.0', '>=') ? 'p:' : '';
  24.  
  25.         if (isset($db_port))
  26.             $this->link_id = @new PDO($p_connect.$db_host, $db_username, $db_password, $db_name, $db_port);
  27.         else
  28.             $this->link_id = @new PDO($p_connect.$db_host, $db_username, $db_password, $db_name);
  29.  
  30.         if (!$this->link_id)
  31.             error('Unable to connect to MySQL server. MySQL say '.mysqli_connect_error(), __FILE__, __LINE__);
  32.  
  33.         // Setup the client-server character set (UTF-8)
  34.         if (!defined('FORUM_NO_SET_NAMES'))
  35.             $this->set_names('utf8');
  36.  
  37.         return $this->link_id;
  38.     }
  39.  
  40.  
  41.     function start_transaction()
  42.     {
  43.         return;
  44.     }
  45.  
  46.  
  47.     function end_transaction()
  48.     {
  49.         return;
  50.     }
  51.  
  52.  
  53.     function query($sql, $unbuffered = false)
  54.     {
  55.         if (strlen($sql) > 140000)
  56.             die('Insanely great request. Interrupted.');
  57.  
  58.         if (defined('FORUM_SHOW_QUERIES'))
  59.             $q_start = get_microtime();
  60.  
  61.         $this->query_result = @mysqli_query($this->link_id, $sql);
  62.  
  63.         if ($this->query_result)
  64.         {
  65.             if (defined('FORUM_SHOW_QUERIES'))
  66.                 $this->saved_queries[] = array($sql, sprintf('%.5f', get_microtime() - $q_start));
  67.  
  68.             ++$this->num_queries;
  69.  
  70.             return $this->query_result;
  71.         }
  72.         else
  73.         {
  74.             if (defined('FORUM_SHOW_QUERIES'))
  75.                 $this->saved_queries[] = array($sql, 0);
  76.  
  77.             return false;
  78.         }
  79.     }
  80.  
  81.  
  82.     function query_build($query, $return_query_string = false, $unbuffered = false)
  83.     {
  84.         $sql = '';
  85.  
  86.         if (isset($query['SELECT']))
  87.         {
  88.             $sql = 'SELECT '.$query['SELECT'].' FROM '.(isset($query['PARAMS']['NO_PREFIX']) ? '' : $this->prefix).$query['FROM'];
  89.  
  90.             if (isset($query['JOINS']))
  91.             {
  92.                 foreach ($query['JOINS'] as $cur_join)
  93.                     $sql .= ' '.key($cur_join).' '.(isset($query['PARAMS']['NO_PREFIX']) ? '' : $this->prefix).current($cur_join).' ON '.$cur_join['ON'];
  94.             }
  95.  
  96.             if (!empty($query['WHERE']))
  97.                 $sql .= ' WHERE '.$query['WHERE'];
  98.             if (!empty($query['GROUP BY']))
  99.                 $sql .= ' GROUP BY '.$query['GROUP BY'];
  100.             if (!empty($query['HAVING']))
  101.                 $sql .= ' HAVING '.$query['HAVING'];
  102.             if (!empty($query['ORDER BY']))
  103.                 $sql .= ' ORDER BY '.$query['ORDER BY'];
  104.             if (!empty($query['LIMIT']))
  105.                 $sql .= ' LIMIT '.$query['LIMIT'];
  106.         }
  107.         else if (isset($query['INSERT']))
  108.         {
  109.             $sql = 'INSERT INTO '.(isset($query['PARAMS']['NO_PREFIX']) ? '' : $this->prefix).$query['INTO'];
  110.  
  111.             if (!empty($query['INSERT']))
  112.                 $sql .= ' ('.$query['INSERT'].')';
  113.  
  114.             if (is_array($query['VALUES']))
  115.                 $sql .= ' VALUES('.implode('),(', $query['VALUES']).')';
  116.             else
  117.                 $sql .= ' VALUES('.$query['VALUES'].')';
  118.         }
  119.         else if (isset($query['UPDATE']))
  120.         {
  121.             $query['UPDATE'] = (isset($query['PARAMS']['NO_PREFIX']) ? '' : $this->prefix).$query['UPDATE'];
  122.  
  123.             $sql = 'UPDATE '.$query['UPDATE'].' SET '.$query['SET'];
  124.  
  125.             if (!empty($query['WHERE']))
  126.                 $sql .= ' WHERE '.$query['WHERE'];
  127.         }
  128.         else if (isset($query['DELETE']))
  129.         {
  130.             $sql = 'DELETE FROM '.(isset($query['PARAMS']['NO_PREFIX']) ? '' : $this->prefix).$query['DELETE'];
  131.  
  132.             if (!empty($query['WHERE']))
  133.                 $sql .= ' WHERE '.$query['WHERE'];
  134.         }
  135.         else if (isset($query['REPLACE']))
  136.         {
  137.             $sql = 'REPLACE INTO '.(isset($query['PARAMS']['NO_PREFIX']) ? '' : $this->prefix).$query['INTO'];
  138.  
  139.             if (!empty($query['REPLACE']))
  140.                 $sql .= ' ('.$query['REPLACE'].')';
  141.  
  142.             $sql .= ' VALUES('.$query['VALUES'].')';
  143.         }
  144.  
  145.         return ($return_query_string) ? $sql : $this->query($sql, $unbuffered);
  146.     }
  147.  
  148.  
  149.     function result($query_id = 0, $row = 0, $col = 0)
  150.     {
  151.         if ($query_id)
  152.         {
  153.             if ($row)
  154.                 @mysqli_data_seek($query_id, $row);
  155.  
  156.             $cur_row = @mysqli_fetch_row($query_id);
  157.             return $cur_row[$col];
  158.         }
  159.         else
  160.             return false;
  161.     }
  162.  
  163.  
  164.     function fetch_assoc($query_id = 0)
  165.     {
  166.         return ($query_id) ? @mysqli_fetch_assoc($query_id) : false;
  167.     }
  168.  
  169.  
  170.     function fetch_row($query_id = 0)
  171.     {
  172.         return ($query_id) ? @mysqli_fetch_row($query_id) : false;
  173.     }
  174.  
  175.  
  176.     function num_rows($query_id = 0)
  177.     {
  178.         return ($query_id) ? @mysqli_num_rows($query_id) : false;
  179.     }
  180.  
  181.  
  182.     function affected_rows()
  183.     {
  184.         return ($this->link_id) ? @mysqli_affected_rows($this->link_id) : false;
  185.     }
  186.  
  187.  
  188.     function insert_id()
  189.     {
  190.         return ($this->link_id) ? @mysqli_insert_id($this->link_id) : false;
  191.     }
  192.  
  193.  
  194.     function get_num_queries()
  195.     {
  196.         return $this->num_queries;
  197.     }
  198.  
  199.  
  200.     function get_saved_queries()
  201.     {
  202.         return $this->saved_queries;
  203.     }
  204.  
  205.  
  206.     function free_result($query_id = false)
  207.     {
  208.         return ($query_id) ? @mysqli_free_result($query_id) : false;
  209.     }
  210.  
  211.  
  212.     function escape($str)
  213.     {
  214.         return is_array($str) ? '' : mysqli_real_escape_string($this->link_id, $str);
  215.     }
  216.  
  217.  
  218.     function error()
  219.     {
  220.         $result['error_sql'] = @current(@end($this->saved_queries));
  221.         $result['error_no'] = @mysqli_errno($this->link_id);
  222.         $result['error_msg'] = @mysqli_error($this->link_id);
  223.  
  224.         return $result;
  225.     }
  226.  
  227.  
  228.     function close()
  229.     {
  230.         if ($this->link_id)
  231.         {
  232.             if ($this->query_result)
  233.                 @mysqli_free_result($this->query_result);
  234.  
  235.             return @mysqli_close($this->link_id);
  236.         }
  237.         else
  238.             return false;
  239.     }
  240.  
  241.  
  242.     function set_names($names)
  243.     {
  244.         return $this->query('SET NAMES \''.$this->escape($names).'\'');
  245.     }
  246.  
  247.  
  248.     function get_version()
  249.     {
  250.         $result = $this->query('SELECT VERSION()');
  251.  
  252.         return array(
  253.             'name'      => 'MySQL Improved',
  254.             'version'   => preg_replace('/^([^-]+).*$/', '\\1', $this->result($result))
  255.         );
  256.     }
  257.  
  258.  
  259.     function table_exists($table_name, $no_prefix = false)
  260.     {
  261.         $result = $this->query('SHOW TABLES LIKE \''.($no_prefix ? '' : $this->prefix).$this->escape($table_name).'\'');
  262.         return $this->num_rows($result) > 0;
  263.     }
  264.  
  265.  
  266.     function field_exists($table_name, $field_name, $no_prefix = false)
  267.     {
  268.         $result = $this->query('SHOW COLUMNS FROM '.($no_prefix ? '' : $this->prefix).$table_name.' LIKE \''.$this->escape($field_name).'\'');
  269.         return $this->num_rows($result) > 0;
  270.     }
  271.  
  272.  
  273.     function index_exists($table_name, $index_name, $no_prefix = false)
  274.     {
  275.         $exists = false;
  276.  
  277.         $result = $this->query('SHOW INDEX FROM '.($no_prefix ? '' : $this->prefix).$table_name);
  278.         while ($cur_index = $this->fetch_assoc($result))
  279.         {
  280.             if ($cur_index['Key_name'] == ($no_prefix ? '' : $this->prefix).$table_name.'_'.$index_name)
  281.             {
  282.                 $exists = true;
  283.                 break;
  284.             }
  285.         }
  286.  
  287.         return $exists;
  288.     }
  289.  
  290.  
  291.     function create_table($table_name, $schema, $no_prefix = false)
  292.     {
  293.         if ($this->table_exists($table_name, $no_prefix))
  294.             return;
  295.  
  296.         $query = 'CREATE TABLE '.($no_prefix ? '' : $this->prefix).$table_name." (\n";
  297.  
  298.         // Go through every schema element and add it to the query
  299.         foreach ($schema['FIELDS'] as $field_name => $field_data)
  300.         {
  301.             $field_data['datatype'] = preg_replace(array_keys($this->datatype_transformations), array_values($this->datatype_transformations), $field_data['datatype']);
  302.  
  303.             $query .= $field_name.' '.$field_data['datatype'];
  304.  
  305.             if (isset($field_data['collation']))
  306.                 $query .= 'CHARACTER SET utf8 COLLATE utf8_'.$field_data['collation'];
  307.  
  308.             if (!$field_data['allow_null'])
  309.                 $query .= ' NOT NULL';
  310.  
  311.             if (isset($field_data['default']))
  312.                 $query .= ' DEFAULT '.$field_data['default'];
  313.  
  314.             $query .= ",\n";
  315.         }
  316.  
  317.         // If we have a primary key, add it
  318.         if (isset($schema['PRIMARY KEY']))
  319.             $query .= 'PRIMARY KEY ('.implode(',', $schema['PRIMARY KEY']).'),'."\n";
  320.  
  321.         // Add unique keys
  322.         if (isset($schema['UNIQUE KEYS']))
  323.         {
  324.             foreach ($schema['UNIQUE KEYS'] as $key_name => $key_fields)
  325.                 $query .= 'UNIQUE KEY '.($no_prefix ? '' : $this->prefix).$table_name.'_'.$key_name.'('.implode(',', $key_fields).'),'."\n";
  326.         }
  327.  
  328.         // Add indexes
  329.         if (isset($schema['INDEXES']))
  330.         {
  331.             foreach ($schema['INDEXES'] as $index_name => $index_fields)
  332.                 $query .= 'KEY '.($no_prefix ? '' : $this->prefix).$table_name.'_'.$index_name.'('.implode(',', $index_fields).'),'."\n";
  333.         }
  334.  
  335.         // We remove the last two characters (a newline and a comma) and add on the ending
  336.         $query = substr($query, 0, strlen($query) - 2)."\n".') ENGINE='.(isset($schema['ENGINE']) ? $schema['ENGINE'] : 'MyISAM').' CHARACTER SET utf8';
  337.  
  338.         $this->query($query) or error(__FILE__, __LINE__);
  339.     }
  340.  
  341.  
  342.     function drop_table($table_name, $no_prefix = false)
  343.     {
  344.         if (!$this->table_exists($table_name, $no_prefix))
  345.             return;
  346.  
  347.         $this->query('DROP TABLE '.($no_prefix ? '' : $this->prefix).$table_name) or error(__FILE__, __LINE__);
  348.     }
  349.  
  350.  
  351.     function add_field($table_name, $field_name, $field_type, $allow_null, $default_value = null, $after_field = null, $no_prefix = false)
  352.     {
  353.         if ($this->field_exists($table_name, $field_name, $no_prefix))
  354.             return;
  355.  
  356.         $field_type = preg_replace(array_keys($this->datatype_transformations), array_values($this->datatype_transformations), $field_type);
  357.  
  358.         if ($default_value !== null && !is_int($default_value) && !is_float($default_value))
  359.             $default_value = '\''.$this->escape($default_value).'\'';
  360.  
  361.         $this->query('ALTER TABLE '.($no_prefix ? '' : $this->prefix).$table_name.' ADD '.$field_name.' '.$field_type.($allow_null ? ' ' : ' NOT NULL').($default_value !== null ? ' DEFAULT '.$default_value : ' ').($after_field != null ? ' AFTER '.$after_field : '')) or error(__FILE__, __LINE__);
  362.     }
  363.  
  364.  
  365.     function alter_field($table_name, $field_name, $field_type, $allow_null, $default_value = null, $after_field = null, $no_prefix = false)
  366.     {
  367.         if (!$this->field_exists($table_name, $field_name, $no_prefix))
  368.             return;
  369.  
  370.         $field_type = preg_replace(array_keys($this->datatype_transformations), array_values($this->datatype_transformations), $field_type);
  371.  
  372.         if ($default_value !== null && !is_int($default_value) && !is_float($default_value))
  373.             $default_value = '\''.$this->escape($default_value).'\'';
  374.  
  375.         $this->query('ALTER TABLE '.($no_prefix ? '' : $this->prefix).$table_name.' MODIFY '.$field_name.' '.$field_type.($allow_null ? ' ' : ' NOT NULL').($default_value !== null ? ' DEFAULT '.$default_value : ' ').($after_field != null ? ' AFTER '.$after_field : '')) or error(__FILE__, __LINE__);
  376.     }
  377.  
  378.  
  379.     function rename_field($table_name, $field_name, $field_new_name, $field_type, $allow_null, $default_value = null, $no_prefix = false)
  380.     {
  381.         if (!$this->field_exists($table_name, $field_name, $no_prefix))
  382.             return;
  383.  
  384.         $field_type = preg_replace(array_keys($this->datatype_transformations), array_values($this->datatype_transformations), $field_type);
  385.  
  386.         if ($default_value !== null && !is_int($default_value) && !is_float($default_value))
  387.             $default_value = '\''.$this->escape($default_value).'\'';
  388.  
  389.         $this->query('ALTER TABLE '.($no_prefix ? '' : $this->prefix).$table_name.' CHANGE '.$field_name.' '.$field_new_name.' '.$field_type.($allow_null ? ' ' : ' NOT NULL').($default_value !== null ? ' DEFAULT '.$default_value : ' ')) or error(__FILE__, __LINE__);
  390.     }
  391.  
  392.  
  393.     function drop_field($table_name, $field_name, $no_prefix = false)
  394.     {
  395.         if (!$this->field_exists($table_name, $field_name, $no_prefix))
  396.             return;
  397.  
  398.         $this->query('ALTER TABLE '.($no_prefix ? '' : $this->prefix).$table_name.' DROP '.$field_name) or error(__FILE__, __LINE__);
  399.     }
  400.  
  401.  
  402.     function add_index($table_name, $index_name, $index_fields, $unique = false, $no_prefix = false)
  403.     {
  404.         if ($this->index_exists($table_name, $index_name, $no_prefix))
  405.             return;
  406.  
  407.         $this->query('ALTER TABLE '.($no_prefix ? '' : $this->prefix).$table_name.' ADD '.($unique ? 'UNIQUE ' : '').'INDEX '.($no_prefix ? '' : $this->prefix).$table_name.'_'.$index_name.' ('.implode(',', $index_fields).')') or error(__FILE__, __LINE__);
  408.     }
  409.  
  410.  
  411.     function drop_index($table_name, $index_name, $no_prefix = false)
  412.     {
  413.         if (!$this->index_exists($table_name, $index_name, $no_prefix))
  414.             return;
  415.  
  416.         $this->query('ALTER TABLE '.($no_prefix ? '' : $this->prefix).$table_name.' DROP INDEX '.($no_prefix ? '' : $this->prefix).$table_name.'_'.$index_name) or error(__FILE__, __LINE__);
  417.     }
  418. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement