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 * MySQL Database Adapter Class
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_mysql_driver extends CI_DB {
33 var $dbdriver = 'mysql';
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 * Whether to use the MySQL "delete hack" which allows the number
44 * of affected rows to be shown. Uses a preg_replace when enabled,
45 * adding a bit more processing to all queries.
47 var $delete_hack = TRUE;
50 * The syntax to count rows is slightly different across different
51 * database engines, so this string appears in each driver and is
52 * used for the count_all() and count_all_results() functions.
54 var $_count_string = 'SELECT COUNT(*) AS ';
55 var $_random_keyword = ' RAND()'; // database specific random keyword
58 * Non-persistent database connection
60 * @access private called by the base class
65 if ($this->port != '')
67 $this->hostname .= ':'.$this->port;
70 return @mysql_connect($this->hostname, $this->username, $this->password, TRUE);
73 // --------------------------------------------------------------------
76 * Persistent database connection
78 * @access private called by the base class
81 function db_pconnect()
83 if ($this->port != '')
85 $this->hostname .= ':'.$this->port;
88 return @mysql_pconnect($this->hostname, $this->username, $this->password);
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 (mysql_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 @mysql_select_db($this->database, $this->conn_id);
123 // --------------------------------------------------------------------
126 * Set client character set
133 function db_set_charset($charset, $collation)
135 return @mysql_query("SET NAMES '".$this->escape_str($charset)."' COLLATE '".$this->escape_str($collation)."'", $this->conn_id);
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 return @mysql_query($sql, $this->conn_id);
166 // --------------------------------------------------------------------
171 * If needed, each database adapter can prep the query string
173 * @access private called by execute()
174 * @param string an SQL query
177 function _prep_query($sql)
179 // "DELETE FROM TABLE" returns 0 affected rows This hack modifies
180 // the query so that it returns the number of affected rows
181 if ($this->delete_hack === TRUE)
183 if (preg_match('/^\s*DELETE\s+FROM\s+(\S+)\s*$/i', $sql))
185 $sql = preg_replace("/^\s*DELETE\s+FROM\s+(\S+)\s*$/", "DELETE FROM \\1 WHERE 1=1", $sql);
192 // --------------------------------------------------------------------
200 function trans_begin($test_mode = FALSE)
202 if ( ! $this->trans_enabled)
207 // When transactions are nested we only begin/commit/rollback the outermost ones
208 if ($this->_trans_depth > 0)
213 // Reset the transaction failure flag.
214 // If the $test_mode flag is set to TRUE transactions will be rolled back
215 // even if the queries produce a successful result.
216 $this->_trans_failure = ($test_mode === TRUE) ? TRUE : FALSE;
218 $this->simple_query('SET AUTOCOMMIT=0');
219 $this->simple_query('START TRANSACTION'); // can also be BEGIN or BEGIN WORK
223 // --------------------------------------------------------------------
231 function trans_commit()
233 if ( ! $this->trans_enabled)
238 // When transactions are nested we only begin/commit/rollback the outermost ones
239 if ($this->_trans_depth > 0)
244 $this->simple_query('COMMIT');
245 $this->simple_query('SET AUTOCOMMIT=1');
249 // --------------------------------------------------------------------
252 * Rollback Transaction
257 function trans_rollback()
259 if ( ! $this->trans_enabled)
264 // When transactions are nested we only begin/commit/rollback the outermost ones
265 if ($this->_trans_depth > 0)
270 $this->simple_query('ROLLBACK');
271 $this->simple_query('SET AUTOCOMMIT=1');
275 // --------------------------------------------------------------------
282 * @param bool whether or not the string will be used in a LIKE condition
285 function escape_str($str, $like = FALSE)
289 foreach ($str as $key => $val)
291 $str[$key] = $this->escape_str($val, $like);
297 if (function_exists('mysql_real_escape_string') AND is_resource($this->conn_id))
299 $str = mysql_real_escape_string($str, $this->conn_id);
301 elseif (function_exists('mysql_escape_string'))
303 $str = mysql_escape_string($str);
307 $str = addslashes($str);
310 // escape LIKE condition wildcards
313 $str = str_replace(array('%', '_'), array('\\%', '\\_'), $str);
319 // --------------------------------------------------------------------
327 function affected_rows()
329 return @mysql_affected_rows($this->conn_id);
332 // --------------------------------------------------------------------
342 return @mysql_insert_id($this->conn_id);
345 // --------------------------------------------------------------------
350 * Generates a platform-specific query string that counts all records in
351 * the specified database
357 function count_all($table = '')
364 $query = $this->query($this->_count_string . $this->_protect_identifiers('numrows') . " FROM " . $this->_protect_identifiers($table, TRUE, NULL, FALSE));
366 if ($query->num_rows() == 0)
371 $row = $query->row();
372 return (int) $row->numrows;
375 // --------------------------------------------------------------------
380 * Generates a platform-specific query string so that the table names can be fetched
386 function _list_tables($prefix_limit = FALSE)
388 $sql = "SHOW TABLES FROM ".$this->_escape_char.$this->database.$this->_escape_char;
390 if ($prefix_limit !== FALSE AND $this->dbprefix != '')
392 $sql .= " LIKE '".$this->escape_like_str($this->dbprefix)."%'";
398 // --------------------------------------------------------------------
403 * Generates a platform-specific query string so that the column names can be fetched
406 * @param string the table name
409 function _list_columns($table = '')
411 return "SHOW COLUMNS FROM ".$this->_protect_identifiers($table, TRUE, NULL, FALSE);
414 // --------------------------------------------------------------------
419 * Generates a platform-specific query so that the column data can be retrieved
422 * @param string the table name
425 function _field_data($table)
427 return "SELECT * FROM ".$table." LIMIT 1";
430 // --------------------------------------------------------------------
433 * The error message string
438 function _error_message()
440 return mysql_error($this->conn_id);
443 // --------------------------------------------------------------------
446 * The error message number
451 function _error_number()
453 return mysql_errno($this->conn_id);
456 // --------------------------------------------------------------------
459 * Escape the SQL Identifiers
461 * This function escapes column and table names
467 function _escape_identifiers($item)
469 if ($this->_escape_char == '')
474 foreach ($this->_reserved_identifiers as $id)
476 if (strpos($item, '.'.$id) !== FALSE)
478 $str = $this->_escape_char. str_replace('.', $this->_escape_char.'.', $item);
480 // remove duplicates if the user already included the escape
481 return preg_replace('/['.$this->_escape_char.']+/', $this->_escape_char, $str);
485 if (strpos($item, '.') !== FALSE)
487 $str = $this->_escape_char.str_replace('.', $this->_escape_char.'.'.$this->_escape_char, $item).$this->_escape_char;
491 $str = $this->_escape_char.$item.$this->_escape_char;
494 // remove duplicates if the user already included the escape
495 return preg_replace('/['.$this->_escape_char.']+/', $this->_escape_char, $str);
498 // --------------------------------------------------------------------
503 * This function implicitly groups FROM tables so there is no confusion
504 * about operator precedence in harmony with SQL standards
510 function _from_tables($tables)
512 if ( ! is_array($tables))
514 $tables = array($tables);
517 return '('.implode(', ', $tables).')';
520 // --------------------------------------------------------------------
525 * Generates a platform-specific insert string from the supplied data
528 * @param string the table name
529 * @param array the insert keys
530 * @param array the insert values
533 function _insert($table, $keys, $values)
535 return "INSERT INTO ".$table." (".implode(', ', $keys).") VALUES (".implode(', ', $values).")";
538 // --------------------------------------------------------------------
544 * Generates a platform-specific replace 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 _replace($table, $keys, $values)
554 return "REPLACE INTO ".$table." (".implode(', ', $keys).") VALUES (".implode(', ', $values).")";
557 // --------------------------------------------------------------------
560 * Insert_batch statement
562 * Generates a platform-specific insert string from the supplied data
565 * @param string the table name
566 * @param array the insert keys
567 * @param array the insert values
570 function _insert_batch($table, $keys, $values)
572 return "INSERT INTO ".$table." (".implode(', ', $keys).") VALUES ".implode(', ', $values);
575 // --------------------------------------------------------------------
581 * Generates a platform-specific update string from the supplied data
584 * @param string the table name
585 * @param array the update data
586 * @param array the where clause
587 * @param array the orderby clause
588 * @param array the limit clause
591 function _update($table, $values, $where, $orderby = array(), $limit = FALSE)
593 foreach ($values as $key => $val)
595 $valstr[] = $key . ' = ' . $val;
598 $limit = ( ! $limit) ? '' : ' LIMIT '.$limit;
600 $orderby = (count($orderby) >= 1)?' ORDER BY '.implode(", ", $orderby):'';
602 $sql = "UPDATE ".$table." SET ".implode(', ', $valstr);
604 $sql .= ($where != '' AND count($where) >=1) ? " WHERE ".implode(" ", $where) : '';
606 $sql .= $orderby.$limit;
611 // --------------------------------------------------------------------
615 * Update_Batch statement
617 * Generates a platform-specific batch update string from the supplied data
620 * @param string the table name
621 * @param array the update data
622 * @param array the where clause
625 function _update_batch($table, $values, $index, $where = NULL)
628 $where = ($where != '' AND count($where) >=1) ? implode(" ", $where).' AND ' : '';
630 foreach ($values as $key => $val)
632 $ids[] = $val[$index];
634 foreach (array_keys($val) as $field)
636 if ($field != $index)
638 $final[$field][] = 'WHEN '.$index.' = '.$val[$index].' THEN '.$val[$field];
643 $sql = "UPDATE ".$table." SET ";
646 foreach ($final as $k => $v)
648 $cases .= $k.' = CASE '."\n";
654 $cases .= 'ELSE '.$k.' END, ';
657 $sql .= substr($cases, 0, -2);
659 $sql .= ' WHERE '.$where.$index.' IN ('.implode(',', $ids).')';
664 // --------------------------------------------------------------------
670 * Generates a platform-specific truncate string from the supplied data
671 * If the database does not support the truncate() command
672 * This function maps to "DELETE FROM table"
675 * @param string the table name
678 function _truncate($table)
680 return "TRUNCATE ".$table;
683 // --------------------------------------------------------------------
688 * Generates a platform-specific delete string from the supplied data
691 * @param string the table name
692 * @param array the where clause
693 * @param string the limit clause
696 function _delete($table, $where = array(), $like = array(), $limit = FALSE)
700 if (count($where) > 0 OR count($like) > 0)
702 $conditions = "\nWHERE ";
703 $conditions .= implode("\n", $this->ar_where);
705 if (count($where) > 0 && count($like) > 0)
707 $conditions .= " AND ";
709 $conditions .= implode("\n", $like);
712 $limit = ( ! $limit) ? '' : ' LIMIT '.$limit;
714 return "DELETE FROM ".$table.$conditions.$limit;
717 // --------------------------------------------------------------------
722 * Generates a platform-specific LIMIT clause
725 * @param string the sql query string
726 * @param integer the number of rows to limit the query to
727 * @param integer the offset value
730 function _limit($sql, $limit, $offset)
741 return $sql."LIMIT ".$offset.$limit;
744 // --------------------------------------------------------------------
747 * Close DB Connection
753 function _close($conn_id)
755 @mysql_close($conn_id);
761 /* End of file mysql_driver.php */
762 /* Location: ./system/database/drivers/mysql/mysql_driver.php */