1 <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
5 * An open source application development framework for PHP 5.1.6 or newer
8 * @author ExpressionEngine Dev Team
9 * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc.
10 * @license http://codeigniter.com/user_guide/license.html
11 * @link http://codeigniter.com
16 // ------------------------------------------------------------------------
19 * MySQLi Database Adapter Class - MySQLi only works with PHP 5
21 * Note: _DB is an extender class that the app controller
22 * creates dynamically based on whether the active record
23 * class is being used or not.
25 * @package CodeIgniter
28 * @author ExpressionEngine Dev Team
29 * @link http://codeigniter.com/user_guide/database/
31 class CI_DB_mysqli_driver extends CI_DB {
33 var $dbdriver = 'mysqli';
35 // The character used for escaping
36 var $_escape_char = '`';
38 // clause and character used for LIKE escape sequences - not used in MySQL
39 var $_like_escape_str = '';
40 var $_like_escape_chr = '';
43 * The syntax to count rows is slightly different across different
44 * database engines, so this string appears in each driver and is
45 * used for the count_all() and count_all_results() functions.
47 var $_count_string = "SELECT COUNT(*) AS ";
48 var $_random_keyword = ' RAND()'; // database specific random keyword
51 * Whether to use the MySQL "delete hack" which allows the number
52 * of affected rows to be shown. Uses a preg_replace when enabled,
53 * adding a bit more processing to all queries.
55 var $delete_hack = TRUE;
57 // --------------------------------------------------------------------
60 * Non-persistent database connection
62 * @access private called by the base class
67 if ($this->port != '')
69 return @mysqli_connect($this->hostname, $this->username, $this->password, $this->database, $this->port);
73 return @mysqli_connect($this->hostname, $this->username, $this->password, $this->database);
78 // --------------------------------------------------------------------
81 * Persistent database connection
83 * @access private called by the base class
86 function db_pconnect()
88 return $this->db_connect();
91 // --------------------------------------------------------------------
96 * Keep / reestablish the db connection if no queries have been
97 * sent for a length of time exceeding the server's idle timeout
104 if (mysqli_ping($this->conn_id) === FALSE)
106 $this->conn_id = FALSE;
110 // --------------------------------------------------------------------
113 * Select the database
115 * @access private called by the base class
120 return @mysqli_select_db($this->conn_id, $this->database);
123 // --------------------------------------------------------------------
126 * Set client character set
133 function _db_set_charset($charset, $collation)
135 return @mysqli_query($this->conn_id, "SET NAMES '".$this->escape_str($charset)."' COLLATE '".$this->escape_str($collation)."'");
138 // --------------------------------------------------------------------
141 * Version number query string
148 return "SELECT version() AS ver";
151 // --------------------------------------------------------------------
156 * @access private called by the base class
157 * @param string an SQL query
160 function _execute($sql)
162 $sql = $this->_prep_query($sql);
163 $result = @mysqli_query($this->conn_id, $sql);
167 // --------------------------------------------------------------------
172 * If needed, each database adapter can prep the query string
174 * @access private called by execute()
175 * @param string an SQL query
178 function _prep_query($sql)
180 // "DELETE FROM TABLE" returns 0 affected rows This hack modifies
181 // the query so that it returns the number of affected rows
182 if ($this->delete_hack === TRUE)
184 if (preg_match('/^\s*DELETE\s+FROM\s+(\S+)\s*$/i', $sql))
186 $sql = preg_replace("/^\s*DELETE\s+FROM\s+(\S+)\s*$/", "DELETE FROM \\1 WHERE 1=1", $sql);
193 // --------------------------------------------------------------------
201 function trans_begin($test_mode = FALSE)
203 if ( ! $this->trans_enabled)
208 // When transactions are nested we only begin/commit/rollback the outermost ones
209 if ($this->_trans_depth > 0)
214 // Reset the transaction failure flag.
215 // If the $test_mode flag is set to TRUE transactions will be rolled back
216 // even if the queries produce a successful result.
217 $this->_trans_failure = ($test_mode === TRUE) ? TRUE : FALSE;
219 $this->simple_query('SET AUTOCOMMIT=0');
220 $this->simple_query('START TRANSACTION'); // can also be BEGIN or BEGIN WORK
224 // --------------------------------------------------------------------
232 function trans_commit()
234 if ( ! $this->trans_enabled)
239 // When transactions are nested we only begin/commit/rollback the outermost ones
240 if ($this->_trans_depth > 0)
245 $this->simple_query('COMMIT');
246 $this->simple_query('SET AUTOCOMMIT=1');
250 // --------------------------------------------------------------------
253 * Rollback Transaction
258 function trans_rollback()
260 if ( ! $this->trans_enabled)
265 // When transactions are nested we only begin/commit/rollback the outermost ones
266 if ($this->_trans_depth > 0)
271 $this->simple_query('ROLLBACK');
272 $this->simple_query('SET AUTOCOMMIT=1');
276 // --------------------------------------------------------------------
283 * @param bool whether or not the string will be used in a LIKE condition
286 function escape_str($str, $like = FALSE)
290 foreach ($str as $key => $val)
292 $str[$key] = $this->escape_str($val, $like);
298 if (function_exists('mysqli_real_escape_string') AND is_object($this->conn_id))
300 $str = mysqli_real_escape_string($this->conn_id, $str);
302 elseif (function_exists('mysql_escape_string'))
304 $str = mysql_escape_string($str);
308 $str = addslashes($str);
311 // escape LIKE condition wildcards
314 $str = str_replace(array('%', '_'), array('\\%', '\\_'), $str);
320 // --------------------------------------------------------------------
328 function affected_rows()
330 return @mysqli_affected_rows($this->conn_id);
333 // --------------------------------------------------------------------
343 return @mysqli_insert_id($this->conn_id);
346 // --------------------------------------------------------------------
351 * Generates a platform-specific query string that counts all records in
352 * the specified database
358 function count_all($table = '')
365 $query = $this->query($this->_count_string . $this->_protect_identifiers('numrows') . " FROM " . $this->_protect_identifiers($table, TRUE, NULL, FALSE));
367 if ($query->num_rows() == 0)
372 $row = $query->row();
373 return (int) $row->numrows;
376 // --------------------------------------------------------------------
381 * Generates a platform-specific query string so that the table names can be fetched
387 function _list_tables($prefix_limit = FALSE)
389 $sql = "SHOW TABLES FROM ".$this->_escape_char.$this->database.$this->_escape_char;
391 if ($prefix_limit !== FALSE AND $this->dbprefix != '')
393 $sql .= " LIKE '".$this->escape_like_str($this->dbprefix)."%'";
399 // --------------------------------------------------------------------
404 * Generates a platform-specific query string so that the column names can be fetched
407 * @param string the table name
410 function _list_columns($table = '')
412 return "SHOW COLUMNS FROM ".$this->_protect_identifiers($table, TRUE, NULL, FALSE);
415 // --------------------------------------------------------------------
420 * Generates a platform-specific query so that the column data can be retrieved
423 * @param string the table name
426 function _field_data($table)
428 return "SELECT * FROM ".$table." LIMIT 1";
431 // --------------------------------------------------------------------
434 * The error message string
439 function _error_message()
441 return mysqli_error($this->conn_id);
444 // --------------------------------------------------------------------
447 * The error message number
452 function _error_number()
454 return mysqli_errno($this->conn_id);
457 // --------------------------------------------------------------------
460 * Escape the SQL Identifiers
462 * This function escapes column and table names
468 function _escape_identifiers($item)
470 if ($this->_escape_char == '')
475 foreach ($this->_reserved_identifiers as $id)
477 if (strpos($item, '.'.$id) !== FALSE)
479 $str = $this->_escape_char. str_replace('.', $this->_escape_char.'.', $item);
481 // remove duplicates if the user already included the escape
482 return preg_replace('/['.$this->_escape_char.']+/', $this->_escape_char, $str);
486 if (strpos($item, '.') !== FALSE)
488 $str = $this->_escape_char.str_replace('.', $this->_escape_char.'.'.$this->_escape_char, $item).$this->_escape_char;
492 $str = $this->_escape_char.$item.$this->_escape_char;
495 // remove duplicates if the user already included the escape
496 return preg_replace('/['.$this->_escape_char.']+/', $this->_escape_char, $str);
499 // --------------------------------------------------------------------
504 * This function implicitly groups FROM tables so there is no confusion
505 * about operator precedence in harmony with SQL standards
511 function _from_tables($tables)
513 if ( ! is_array($tables))
515 $tables = array($tables);
518 return '('.implode(', ', $tables).')';
521 // --------------------------------------------------------------------
526 * Generates a platform-specific insert string from the supplied data
529 * @param string the table name
530 * @param array the insert keys
531 * @param array the insert values
534 function _insert($table, $keys, $values)
536 return "INSERT INTO ".$table." (".implode(', ', $keys).") VALUES (".implode(', ', $values).")";
539 // --------------------------------------------------------------------
542 * Insert_batch statement
544 * Generates a platform-specific insert string from the supplied data
547 * @param string the table name
548 * @param array the insert keys
549 * @param array the insert values
552 function _insert_batch($table, $keys, $values)
554 return "INSERT INTO ".$table." (".implode(', ', $keys).") VALUES ".implode(', ', $values);
557 // --------------------------------------------------------------------
562 * Generates a platform-specific update string from the supplied data
565 * @param string the table name
566 * @param array the update data
567 * @param array the where clause
568 * @param array the orderby clause
569 * @param array the limit clause
572 function _update($table, $values, $where, $orderby = array(), $limit = FALSE)
574 foreach ($values as $key => $val)
576 $valstr[] = $key." = ".$val;
579 $limit = ( ! $limit) ? '' : ' LIMIT '.$limit;
581 $orderby = (count($orderby) >= 1)?' ORDER BY '.implode(", ", $orderby):'';
583 $sql = "UPDATE ".$table." SET ".implode(', ', $valstr);
585 $sql .= ($where != '' AND count($where) >=1) ? " WHERE ".implode(" ", $where) : '';
587 $sql .= $orderby.$limit;
592 // --------------------------------------------------------------------
595 * Update_Batch statement
597 * Generates a platform-specific batch update string from the supplied data
600 * @param string the table name
601 * @param array the update data
602 * @param array the where clause
605 function _update_batch($table, $values, $index, $where = NULL)
608 $where = ($where != '' AND count($where) >=1) ? implode(" ", $where).' AND ' : '';
610 foreach ($values as $key => $val)
612 $ids[] = $val[$index];
614 foreach (array_keys($val) as $field)
616 if ($field != $index)
618 $final[$field][] = 'WHEN '.$index.' = '.$val[$index].' THEN '.$val[$field];
623 $sql = "UPDATE ".$table." SET ";
626 foreach ($final as $k => $v)
628 $cases .= $k.' = CASE '."\n";
634 $cases .= 'ELSE '.$k.' END, ';
637 $sql .= substr($cases, 0, -2);
639 $sql .= ' WHERE '.$where.$index.' IN ('.implode(',', $ids).')';
644 // --------------------------------------------------------------------
649 * Generates a platform-specific truncate string from the supplied data
650 * If the database does not support the truncate() command
651 * This function maps to "DELETE FROM table"
654 * @param string the table name
657 function _truncate($table)
659 return "TRUNCATE ".$table;
662 // --------------------------------------------------------------------
667 * Generates a platform-specific delete string from the supplied data
670 * @param string the table name
671 * @param array the where clause
672 * @param string the limit clause
675 function _delete($table, $where = array(), $like = array(), $limit = FALSE)
679 if (count($where) > 0 OR count($like) > 0)
681 $conditions = "\nWHERE ";
682 $conditions .= implode("\n", $this->ar_where);
684 if (count($where) > 0 && count($like) > 0)
686 $conditions .= " AND ";
688 $conditions .= implode("\n", $like);
691 $limit = ( ! $limit) ? '' : ' LIMIT '.$limit;
693 return "DELETE FROM ".$table.$conditions.$limit;
696 // --------------------------------------------------------------------
701 * Generates a platform-specific LIMIT clause
704 * @param string the sql query string
705 * @param integer the number of rows to limit the query to
706 * @param integer the offset value
709 function _limit($sql, $limit, $offset)
711 $sql .= "LIMIT ".$limit;
715 $sql .= " OFFSET ".$offset;
721 // --------------------------------------------------------------------
724 * Close DB Connection
730 function _close($conn_id)
732 @mysqli_close($conn_id);
739 /* End of file mysqli_driver.php */
740 /* Location: ./system/database/drivers/mysqli/mysqli_driver.php */