blob: a164552ed88371750588eb3181761490ca1cf189 [file] [log] [blame]
Derek Allardd2df9bc2007-04-15 17:41:17 +00001<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
2/**
3 * CodeIgniter
4 *
5 * An open source application development framework for PHP 4.3.2 or newer
6 *
7 * @package CodeIgniter
8 * @author Rick Ellis
9 * @copyright Copyright (c) 2006, EllisLab, Inc.
Derek Allard6838f002007-10-04 19:29:59 +000010 * @license http://www.codeigniter.com/user_guide/license.html
Derek Allardd2df9bc2007-04-15 17:41:17 +000011 * @link http://www.codeigniter.com
12 * @since Version 1.0
13 * @filesource
14 */
15
16// ------------------------------------------------------------------------
17
18/**
19 * MySQL Database Adapter Class
20 *
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.
24 *
25 * @package CodeIgniter
26 * @subpackage Drivers
27 * @category Database
28 * @author Rick Ellis
29 * @link http://www.codeigniter.com/user_guide/database/
30 */
31class CI_DB_mysql_driver extends CI_DB {
32
33 /**
34 * Whether to use the MySQL "delete hack" which allows the number
35 * of affected rows to be shown. Uses a preg_replace when enabled,
36 * adding a bit more processing to all queries.
37 */
38 var $delete_hack = TRUE;
Derek Allard6ddb5a12007-12-18 17:22:50 +000039
40 /**
41 * The syntax to count rows is slightly different across different
42 * database engines, so this string appears in each driver and is
43 * used for the count_all() and count_all_results() functions.
44 */
Derek Allard39b622d2008-01-16 21:10:09 +000045 var $_count_string = 'SELECT COUNT(*) AS ';
Derek Allard6ddb5a12007-12-18 17:22:50 +000046 var $_random_keyword = ' RAND()'; // database specific random keyword
Derek Allardd2df9bc2007-04-15 17:41:17 +000047
48 /**
49 * Non-persistent database connection
50 *
51 * @access private called by the base class
52 * @return resource
53 */
54 function db_connect()
55 {
56 return @mysql_connect($this->hostname, $this->username, $this->password, TRUE);
57 }
58
59 // --------------------------------------------------------------------
60
61 /**
62 * Persistent database connection
63 *
64 * @access private called by the base class
65 * @return resource
66 */
67 function db_pconnect()
68 {
69 return @mysql_pconnect($this->hostname, $this->username, $this->password);
70 }
71
72 // --------------------------------------------------------------------
73
74 /**
75 * Select the database
76 *
77 * @access private called by the base class
78 * @return resource
79 */
80 function db_select()
81 {
82 return @mysql_select_db($this->database, $this->conn_id);
83 }
84
85 // --------------------------------------------------------------------
86
87 /**
Derek Allard39b622d2008-01-16 21:10:09 +000088 * Set client character set
89 *
90 * @access public
91 * @param string
92 * @param string
93 * @return resource
94 */
95 function db_set_charset($charset, $collation)
96 {
97 return @mysql_query("SET NAMES '".$this->escape_str($charset)."' COLLATE '".$this->escape_str($collation)."'", $this->conn_id);
98 }
99
100 // --------------------------------------------------------------------
101
102 /**
Derek Allardd2df9bc2007-04-15 17:41:17 +0000103 * Version number query string
104 *
105 * @access public
106 * @return string
107 */
108 function _version()
109 {
110 return "SELECT version() AS ver";
111 }
112
113 // --------------------------------------------------------------------
114
115 /**
116 * Execute the query
117 *
118 * @access private called by the base class
119 * @param string an SQL query
120 * @return resource
121 */
122 function _execute($sql)
123 {
124 $sql = $this->_prep_query($sql);
125 return @mysql_query($sql, $this->conn_id);
126 }
127
128 // --------------------------------------------------------------------
129
130 /**
131 * Prep the query
132 *
133 * If needed, each database adapter can prep the query string
134 *
135 * @access private called by execute()
136 * @param string an SQL query
137 * @return string
138 */
139 function _prep_query($sql)
140 {
141 // "DELETE FROM TABLE" returns 0 affected rows This hack modifies
142 // the query so that it returns the number of affected rows
143 if ($this->delete_hack === TRUE)
144 {
145 if (preg_match('/^\s*DELETE\s+FROM\s+(\S+)\s*$/i', $sql))
146 {
147 $sql = preg_replace("/^\s*DELETE\s+FROM\s+(\S+)\s*$/", "DELETE FROM \\1 WHERE 1=1", $sql);
148 }
149 }
150
151 return $sql;
152 }
153
154 // --------------------------------------------------------------------
155
156 /**
157 * Begin Transaction
158 *
159 * @access public
160 * @return bool
161 */
162 function trans_begin($test_mode = FALSE)
163 {
164 if ( ! $this->trans_enabled)
165 {
166 return TRUE;
167 }
168
169 // When transactions are nested we only begin/commit/rollback the outermost ones
170 if ($this->_trans_depth > 0)
171 {
172 return TRUE;
173 }
174
175 // Reset the transaction failure flag.
176 // If the $test_mode flag is set to TRUE transactions will be rolled back
177 // even if the queries produce a successful result.
178 $this->_trans_failure = ($test_mode === TRUE) ? TRUE : FALSE;
179
180 $this->simple_query('SET AUTOCOMMIT=0');
181 $this->simple_query('START TRANSACTION'); // can also be BEGIN or BEGIN WORK
182 return TRUE;
183 }
184
185 // --------------------------------------------------------------------
186
187 /**
188 * Commit Transaction
189 *
190 * @access public
191 * @return bool
192 */
193 function trans_commit()
194 {
195 if ( ! $this->trans_enabled)
196 {
197 return TRUE;
198 }
199
200 // When transactions are nested we only begin/commit/rollback the outermost ones
201 if ($this->_trans_depth > 0)
202 {
203 return TRUE;
204 }
205
206 $this->simple_query('COMMIT');
207 $this->simple_query('SET AUTOCOMMIT=1');
208 return TRUE;
209 }
210
211 // --------------------------------------------------------------------
212
213 /**
214 * Rollback Transaction
215 *
216 * @access public
217 * @return bool
218 */
219 function trans_rollback()
220 {
221 if ( ! $this->trans_enabled)
222 {
223 return TRUE;
224 }
225
226 // When transactions are nested we only begin/commit/rollback the outermost ones
227 if ($this->_trans_depth > 0)
228 {
229 return TRUE;
230 }
231
232 $this->simple_query('ROLLBACK');
233 $this->simple_query('SET AUTOCOMMIT=1');
234 return TRUE;
235 }
236
237 // --------------------------------------------------------------------
238
239 /**
240 * Escape String
241 *
242 * @access public
243 * @param string
244 * @return string
245 */
246 function escape_str($str)
247 {
Derek Allard694b5b82007-12-18 15:58:03 +0000248 if (is_array($str))
249 {
250 foreach($str as $key => $val)
251 {
252 $str[$key] = $this->escape_str($val);
253 }
254
255 return $str;
256 }
257
258 if (function_exists('mysql_real_escape_string') AND is_resource($this->conn_id))
Derek Allardd2df9bc2007-04-15 17:41:17 +0000259 {
260 return mysql_real_escape_string($str, $this->conn_id);
261 }
262 elseif (function_exists('mysql_escape_string'))
263 {
264 return mysql_escape_string($str);
265 }
266 else
267 {
268 return addslashes($str);
269 }
270 }
271
272 // --------------------------------------------------------------------
273
274 /**
275 * Affected Rows
276 *
277 * @access public
278 * @return integer
279 */
280 function affected_rows()
281 {
282 return @mysql_affected_rows($this->conn_id);
283 }
284
285 // --------------------------------------------------------------------
286
287 /**
288 * Insert ID
289 *
290 * @access public
291 * @return integer
292 */
293 function insert_id()
294 {
295 return @mysql_insert_id($this->conn_id);
296 }
297
298 // --------------------------------------------------------------------
299
300 /**
301 * "Count All" query
302 *
303 * Generates a platform-specific query string that counts all records in
304 * the specified database
305 *
306 * @access public
307 * @param string
308 * @return string
309 */
310 function count_all($table = '')
311 {
312 if ($table == '')
313 return '0';
314
Derek Allard6ddb5a12007-12-18 17:22:50 +0000315 $query = $this->query($this->_count_string . "FROM `".$this->dbprefix.$table."`");
Derek Allardd2df9bc2007-04-15 17:41:17 +0000316
317 if ($query->num_rows() == 0)
318 return '0';
319
320 $row = $query->row();
321 return $row->numrows;
322 }
323
324 // --------------------------------------------------------------------
325
326 /**
327 * List table query
328 *
329 * Generates a platform-specific query string so that the table names can be fetched
330 *
331 * @access private
Derek Allard39b622d2008-01-16 21:10:09 +0000332 * @param boolean
Derek Allardd2df9bc2007-04-15 17:41:17 +0000333 * @return string
334 */
Derek Allard694b5b82007-12-18 15:58:03 +0000335 function _list_tables($prefix_limit = FALSE)
Derek Allardd2df9bc2007-04-15 17:41:17 +0000336 {
Derek Allard694b5b82007-12-18 15:58:03 +0000337 $sql = "SHOW TABLES FROM `".$this->database."`";
Derek Allard39b622d2008-01-16 21:10:09 +0000338
339 if ($prefix_limit !== FALSE AND $this->dbprefix != '')
Derek Allard694b5b82007-12-18 15:58:03 +0000340 {
Derek Allard39b622d2008-01-16 21:10:09 +0000341 $sql .= " LIKE '".$this->dbprefix."%'";
Derek Allard694b5b82007-12-18 15:58:03 +0000342 }
Derek Allard39b622d2008-01-16 21:10:09 +0000343
Derek Allard694b5b82007-12-18 15:58:03 +0000344 return $sql;
Derek Allardd2df9bc2007-04-15 17:41:17 +0000345 }
346
347 // --------------------------------------------------------------------
348
349 /**
350 * Show column query
351 *
352 * Generates a platform-specific query string so that the column names can be fetched
353 *
354 * @access public
355 * @param string the table name
356 * @return string
357 */
358 function _list_columns($table = '')
359 {
360 return "SHOW COLUMNS FROM ".$this->_escape_table($table);
361 }
362
363 // --------------------------------------------------------------------
364
365 /**
366 * Field data query
367 *
368 * Generates a platform-specific query so that the column data can be retrieved
369 *
370 * @access public
371 * @param string the table name
372 * @return object
373 */
374 function _field_data($table)
375 {
376 return "SELECT * FROM ".$this->_escape_table($table)." LIMIT 1";
377 }
378
379 // --------------------------------------------------------------------
380
381 /**
382 * The error message string
383 *
384 * @access private
385 * @return string
386 */
387 function _error_message()
388 {
389 return mysql_error($this->conn_id);
390 }
391
392 // --------------------------------------------------------------------
393
394 /**
395 * The error message number
396 *
397 * @access private
398 * @return integer
399 */
400 function _error_number()
401 {
402 return mysql_errno($this->conn_id);
403 }
404
405 // --------------------------------------------------------------------
406
407 /**
408 * Escape Table Name
409 *
410 * This function adds backticks if the table name has a period
411 * in it. Some DBs will get cranky unless periods are escaped
412 *
413 * @access private
414 * @param string the table name
415 * @return string
416 */
417 function _escape_table($table)
418 {
Derek Allard39b622d2008-01-16 21:10:09 +0000419 if (strpos($table, '.') !== FALSE)
Derek Allardd2df9bc2007-04-15 17:41:17 +0000420 {
Derek Allard39b622d2008-01-16 21:10:09 +0000421 $table = str_replace('.', '`.`', $table);
Derek Allardd2df9bc2007-04-15 17:41:17 +0000422 }
423
424 return $table;
425 }
Derek Allard39b622d2008-01-16 21:10:09 +0000426
427 // --------------------------------------------------------------------
428
429 /**
430 * Protect Identifiers
431 *
432 * This function adds backticks if appropriate based on db type
433 *
434 * @access private
435 * @param mixed the item to escape
436 * @param boolean only affect the first word
437 * @return mixed the item with backticks
438 */
439 function _protect_identifiers($item, $first_word_only = FALSE)
440 {
441 if (is_array($item))
442 {
443 $escaped_array = array();
444
445 foreach($item as $k=>$v)
446 {
447 $escaped_array[$this->_protect_identifiers($k)] = $this->_protect_identifiers($v, $first_word_only);
448 }
449
450 return $escaped_array;
451 }
452
453 // This function may get "item1 item2" as a string, and so
454 // we may need "`item1` `item2`" and not "`item1 item2`"
455 if (strpos($item, ' ') !== FALSE)
456 {
457 // This function may get "field >= 1", and need it to return "`field` >= 1"
458 if ($first_word_only === TRUE)
459 {
460 return '`'.preg_replace('/ /', '` ', $item, 1);
461 }
462
463 $item = preg_replace('/(^|\s|\()([\w\d\-\_]+?)(\s|\)|$)/iS', '$1`$2`$3', $item);
464 }
465
466 $exceptions = array('AS', '/', '-', '%', '+', '*');
Derek Allardd2df9bc2007-04-15 17:41:17 +0000467
Derek Allard39b622d2008-01-16 21:10:09 +0000468 foreach ($exceptions as $exception)
469 {
470
471 if (stristr($item, " `{$exception}` ") !== FALSE)
472 {
473 $item = preg_replace('/ `('.preg_quote($exception).')` /i', ' $1 ', $item);
474 }
475 }
476 return $item;
477 }
478
Derek Allardd2df9bc2007-04-15 17:41:17 +0000479 // --------------------------------------------------------------------
480
481 /**
482 * Insert statement
483 *
484 * Generates a platform-specific insert string from the supplied data
485 *
486 * @access public
487 * @param string the table name
488 * @param array the insert keys
489 * @param array the insert values
490 * @return string
491 */
492 function _insert($table, $keys, $values)
493 {
494 return "INSERT INTO ".$this->_escape_table($table)." (".implode(', ', $keys).") VALUES (".implode(', ', $values).")";
495 }
496
497 // --------------------------------------------------------------------
498
499 /**
500 * Update statement
501 *
502 * Generates a platform-specific update string from the supplied data
503 *
504 * @access public
505 * @param string the table name
506 * @param array the update data
507 * @param array the where clause
Derek Allard39b622d2008-01-16 21:10:09 +0000508 * @param array the orderby clause
509 * @param array the limit clause
Derek Allardd2df9bc2007-04-15 17:41:17 +0000510 * @return string
511 */
Derek Allard39b622d2008-01-16 21:10:09 +0000512 function _update($table, $values, $where, $orderby = array(), $limit = FALSE)
Derek Allardd2df9bc2007-04-15 17:41:17 +0000513 {
514 foreach($values as $key => $val)
515 {
516 $valstr[] = $key." = ".$val;
517 }
Derek Allardda6d2402007-12-19 14:49:29 +0000518
519 $limit = (!$limit) ? '' : ' LIMIT '.$limit;
Derek Allard39b622d2008-01-16 21:10:09 +0000520
521 $orderby = (count($orderby) >= 1)?' ORDER BY '.implode(", ", $orderby):'';
Derek Allardd2df9bc2007-04-15 17:41:17 +0000522
Derek Allard39b622d2008-01-16 21:10:09 +0000523 return "UPDATE ".$this->_escape_table($table)." SET ".implode(', ', $valstr)." WHERE ".implode(" ", $where).$orderby.$limit;
524 }
525
526 // --------------------------------------------------------------------
527
528 /**
529 * Truncate statement
530 *
531 * Generates a platform-specific truncate string from the supplied data
532 * If the database does not support the truncate() command
533 * This function maps to "DELETE FROM table"
534 *
535 * @access public
536 * @param string the table name
537 * @return string
538 */
539 function _truncate($table)
540 {
541 return "TRUNCATE ".$this->_escape_table($table);
Derek Allardd2df9bc2007-04-15 17:41:17 +0000542 }
543
544 // --------------------------------------------------------------------
545
546 /**
547 * Delete statement
548 *
549 * Generates a platform-specific delete string from the supplied data
550 *
551 * @access public
552 * @param string the table name
553 * @param array the where clause
Derek Allard39b622d2008-01-16 21:10:09 +0000554 * @param string the limit clause
Derek Allardd2df9bc2007-04-15 17:41:17 +0000555 * @return string
556 */
Derek Allard39b622d2008-01-16 21:10:09 +0000557 function _delete($table, $where = array(), $like = array(), $limit = FALSE)
Derek Allardd2df9bc2007-04-15 17:41:17 +0000558 {
Derek Allard39b622d2008-01-16 21:10:09 +0000559 $conditions = '';
560
561 if (count($where) > 0 || count($like) > 0)
562 {
563 $conditions = "\nWHERE ";
564 $conditions .= implode("\n", $this->ar_where);
565
566 if (count($where) > 0 && count($like) > 0)
567 {
568 $conditions .= " AND ";
569 }
570 $conditions .= implode("\n", $like);
571 }
572
Derek Allarde77d77c2007-12-19 15:01:55 +0000573 $limit = (!$limit) ? '' : ' LIMIT '.$limit;
574
Derek Allard39b622d2008-01-16 21:10:09 +0000575 return "DELETE FROM ".$table.$conditions.$limit;
Derek Allardd2df9bc2007-04-15 17:41:17 +0000576 }
577
578 // --------------------------------------------------------------------
579
580 /**
581 * Limit string
582 *
583 * Generates a platform-specific LIMIT clause
584 *
585 * @access public
586 * @param string the sql query string
587 * @param integer the number of rows to limit the query to
588 * @param integer the offset value
589 * @return string
590 */
591 function _limit($sql, $limit, $offset)
592 {
593 if ($offset == 0)
594 {
595 $offset = '';
596 }
597 else
598 {
599 $offset .= ", ";
600 }
601
602 return $sql."LIMIT ".$offset.$limit;
603 }
604
605 // --------------------------------------------------------------------
606
607 /**
608 * Close DB Connection
609 *
610 * @access public
611 * @param resource
612 * @return void
613 */
614 function _close($conn_id)
615 {
616 @mysql_close($conn_id);
617 }
618
619}
620
admin046000b2006-09-24 18:12:07 +0000621?>