mysql_driver.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769
  1. <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
  2. /**
  3. * CodeIgniter
  4. *
  5. * An open source application development framework for PHP 5.1.6 or newer
  6. *
  7. * @package CodeIgniter
  8. * @author EllisLab Dev Team
  9. * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc.
  10. * @copyright Copyright (c) 2014 - 2015, British Columbia Institute of Technology (http://bcit.ca/)
  11. * @license http://codeigniter.com/user_guide/license.html
  12. * @link http://codeigniter.com
  13. * @since Version 1.0
  14. * @filesource
  15. */
  16. // ------------------------------------------------------------------------
  17. /**
  18. * MySQL Database Adapter Class
  19. *
  20. * Note: _DB is an extender class that the app controller
  21. * creates dynamically based on whether the active record
  22. * class is being used or not.
  23. *
  24. * @package CodeIgniter
  25. * @subpackage Drivers
  26. * @category Database
  27. * @author EllisLab Dev Team
  28. * @link http://codeigniter.com/user_guide/database/
  29. */
  30. class CI_DB_mysql_driver extends CI_DB {
  31. var $dbdriver = 'mysql';
  32. // The character used for escaping
  33. var $_escape_char = '`';
  34. // clause and character used for LIKE escape sequences - not used in MySQL
  35. var $_like_escape_str = '';
  36. var $_like_escape_chr = '';
  37. /**
  38. * Whether to use the MySQL "delete hack" which allows the number
  39. * of affected rows to be shown. Uses a preg_replace when enabled,
  40. * adding a bit more processing to all queries.
  41. */
  42. var $delete_hack = TRUE;
  43. /**
  44. * The syntax to count rows is slightly different across different
  45. * database engines, so this string appears in each driver and is
  46. * used for the count_all() and count_all_results() functions.
  47. */
  48. var $_count_string = 'SELECT COUNT(*) AS ';
  49. var $_random_keyword = ' RAND()'; // database specific random keyword
  50. // whether SET NAMES must be used to set the character set
  51. var $use_set_names;
  52. /**
  53. * Non-persistent database connection
  54. *
  55. * @access private called by the base class
  56. * @return resource
  57. */
  58. function db_connect()
  59. {
  60. if ($this->port != '')
  61. {
  62. $this->hostname .= ':'.$this->port;
  63. }
  64. return @mysql_connect($this->hostname, $this->username, $this->password, TRUE);
  65. }
  66. // --------------------------------------------------------------------
  67. /**
  68. * Persistent database connection
  69. *
  70. * @access private called by the base class
  71. * @return resource
  72. */
  73. function db_pconnect()
  74. {
  75. if ($this->port != '')
  76. {
  77. $this->hostname .= ':'.$this->port;
  78. }
  79. return @mysql_pconnect($this->hostname, $this->username, $this->password);
  80. }
  81. // --------------------------------------------------------------------
  82. /**
  83. * Reconnect
  84. *
  85. * Keep / reestablish the db connection if no queries have been
  86. * sent for a length of time exceeding the server's idle timeout
  87. *
  88. * @access public
  89. * @return void
  90. */
  91. function reconnect()
  92. {
  93. if (mysql_ping($this->conn_id) === FALSE)
  94. {
  95. $this->conn_id = FALSE;
  96. }
  97. }
  98. // --------------------------------------------------------------------
  99. /**
  100. * Select the database
  101. *
  102. * @access private called by the base class
  103. * @return resource
  104. */
  105. function db_select()
  106. {
  107. return @mysql_select_db($this->database, $this->conn_id);
  108. }
  109. // --------------------------------------------------------------------
  110. /**
  111. * Set client character set
  112. *
  113. * @access public
  114. * @param string
  115. * @param string
  116. * @return resource
  117. */
  118. function db_set_charset($charset, $collation)
  119. {
  120. if ( ! isset($this->use_set_names))
  121. {
  122. // mysql_set_charset() requires PHP >= 5.2.3 and MySQL >= 5.0.7, use SET NAMES as fallback
  123. $this->use_set_names = (version_compare(PHP_VERSION, '5.2.3', '>=') && version_compare(mysql_get_server_info(), '5.0.7', '>=')) ? FALSE : TRUE;
  124. }
  125. if ($this->use_set_names === TRUE)
  126. {
  127. return @mysql_query("SET NAMES '".$this->escape_str($charset)."' COLLATE '".$this->escape_str($collation)."'", $this->conn_id);
  128. }
  129. else
  130. {
  131. return @mysql_set_charset($charset, $this->conn_id);
  132. }
  133. }
  134. // --------------------------------------------------------------------
  135. /**
  136. * Version number query string
  137. *
  138. * @access public
  139. * @return string
  140. */
  141. function _version()
  142. {
  143. return "SELECT version() AS ver";
  144. }
  145. // --------------------------------------------------------------------
  146. /**
  147. * Execute the query
  148. *
  149. * @access private called by the base class
  150. * @param string an SQL query
  151. * @return resource
  152. */
  153. function _execute($sql)
  154. {
  155. $sql = $this->_prep_query($sql);
  156. return @mysql_query($sql, $this->conn_id);
  157. }
  158. // --------------------------------------------------------------------
  159. /**
  160. * Prep the query
  161. *
  162. * If needed, each database adapter can prep the query string
  163. *
  164. * @access private called by execute()
  165. * @param string an SQL query
  166. * @return string
  167. */
  168. function _prep_query($sql)
  169. {
  170. // "DELETE FROM TABLE" returns 0 affected rows This hack modifies
  171. // the query so that it returns the number of affected rows
  172. if ($this->delete_hack === TRUE)
  173. {
  174. if (preg_match('/^\s*DELETE\s+FROM\s+(\S+)\s*$/i', $sql))
  175. {
  176. $sql = preg_replace("/^\s*DELETE\s+FROM\s+(\S+)\s*$/", "DELETE FROM \\1 WHERE 1=1", $sql);
  177. }
  178. }
  179. return $sql;
  180. }
  181. // --------------------------------------------------------------------
  182. /**
  183. * Begin Transaction
  184. *
  185. * @access public
  186. * @return bool
  187. */
  188. function trans_begin($test_mode = FALSE)
  189. {
  190. if ( ! $this->trans_enabled)
  191. {
  192. return TRUE;
  193. }
  194. // When transactions are nested we only begin/commit/rollback the outermost ones
  195. if ($this->_trans_depth > 0)
  196. {
  197. return TRUE;
  198. }
  199. // Reset the transaction failure flag.
  200. // If the $test_mode flag is set to TRUE transactions will be rolled back
  201. // even if the queries produce a successful result.
  202. $this->_trans_failure = ($test_mode === TRUE) ? TRUE : FALSE;
  203. $this->simple_query('SET AUTOCOMMIT=0');
  204. $this->simple_query('START TRANSACTION'); // can also be BEGIN or BEGIN WORK
  205. return TRUE;
  206. }
  207. // --------------------------------------------------------------------
  208. /**
  209. * Commit Transaction
  210. *
  211. * @access public
  212. * @return bool
  213. */
  214. function trans_commit()
  215. {
  216. if ( ! $this->trans_enabled)
  217. {
  218. return TRUE;
  219. }
  220. // When transactions are nested we only begin/commit/rollback the outermost ones
  221. if ($this->_trans_depth > 0)
  222. {
  223. return TRUE;
  224. }
  225. $this->simple_query('COMMIT');
  226. $this->simple_query('SET AUTOCOMMIT=1');
  227. return TRUE;
  228. }
  229. // --------------------------------------------------------------------
  230. /**
  231. * Rollback Transaction
  232. *
  233. * @access public
  234. * @return bool
  235. */
  236. function trans_rollback()
  237. {
  238. if ( ! $this->trans_enabled)
  239. {
  240. return TRUE;
  241. }
  242. // When transactions are nested we only begin/commit/rollback the outermost ones
  243. if ($this->_trans_depth > 0)
  244. {
  245. return TRUE;
  246. }
  247. $this->simple_query('ROLLBACK');
  248. $this->simple_query('SET AUTOCOMMIT=1');
  249. return TRUE;
  250. }
  251. // --------------------------------------------------------------------
  252. /**
  253. * Escape String
  254. *
  255. * @access public
  256. * @param string
  257. * @param bool whether or not the string will be used in a LIKE condition
  258. * @return string
  259. */
  260. function escape_str($str, $like = FALSE)
  261. {
  262. if (is_array($str))
  263. {
  264. foreach ($str as $key => $val)
  265. {
  266. $str[$key] = $this->escape_str($val, $like);
  267. }
  268. return $str;
  269. }
  270. $str = mysql_real_escape_string($str, $this->conn_id);
  271. // escape LIKE condition wildcards
  272. if ($like === TRUE)
  273. {
  274. $str = str_replace(array('%', '_'), array('\\%', '\\_'), $str);
  275. }
  276. return $str;
  277. }
  278. // --------------------------------------------------------------------
  279. /**
  280. * Affected Rows
  281. *
  282. * @access public
  283. * @return integer
  284. */
  285. function affected_rows()
  286. {
  287. return @mysql_affected_rows($this->conn_id);
  288. }
  289. // --------------------------------------------------------------------
  290. /**
  291. * Insert ID
  292. *
  293. * @access public
  294. * @return integer
  295. */
  296. function insert_id()
  297. {
  298. return @mysql_insert_id($this->conn_id);
  299. }
  300. // --------------------------------------------------------------------
  301. /**
  302. * "Count All" query
  303. *
  304. * Generates a platform-specific query string that counts all records in
  305. * the specified database
  306. *
  307. * @access public
  308. * @param string
  309. * @return string
  310. */
  311. function count_all($table = '')
  312. {
  313. if ($table == '')
  314. {
  315. return 0;
  316. }
  317. $query = $this->query($this->_count_string . $this->_protect_identifiers('numrows') . " FROM " . $this->_protect_identifiers($table, TRUE, NULL, FALSE));
  318. if ($query->num_rows() == 0)
  319. {
  320. return 0;
  321. }
  322. $row = $query->row();
  323. $this->_reset_select();
  324. return (int) $row->numrows;
  325. }
  326. // --------------------------------------------------------------------
  327. /**
  328. * List table query
  329. *
  330. * Generates a platform-specific query string so that the table names can be fetched
  331. *
  332. * @access private
  333. * @param boolean
  334. * @return string
  335. */
  336. function _list_tables($prefix_limit = FALSE)
  337. {
  338. $sql = "SHOW TABLES FROM ".$this->_escape_char.$this->database.$this->_escape_char;
  339. if ($prefix_limit !== FALSE AND $this->dbprefix != '')
  340. {
  341. $sql .= " LIKE '".$this->escape_like_str($this->dbprefix)."%'";
  342. }
  343. return $sql;
  344. }
  345. // --------------------------------------------------------------------
  346. /**
  347. * Show column query
  348. *
  349. * Generates a platform-specific query string so that the column names can be fetched
  350. *
  351. * @access public
  352. * @param string the table name
  353. * @return string
  354. */
  355. function _list_columns($table = '')
  356. {
  357. return "SHOW COLUMNS FROM ".$this->_protect_identifiers($table, TRUE, NULL, FALSE);
  358. }
  359. // --------------------------------------------------------------------
  360. /**
  361. * Field data query
  362. *
  363. * Generates a platform-specific query so that the column data can be retrieved
  364. *
  365. * @access public
  366. * @param string the table name
  367. * @return object
  368. */
  369. function _field_data($table)
  370. {
  371. return "DESCRIBE ".$table;
  372. }
  373. // --------------------------------------------------------------------
  374. /**
  375. * The error message string
  376. *
  377. * @access private
  378. * @return string
  379. */
  380. function _error_message()
  381. {
  382. return mysql_error($this->conn_id);
  383. }
  384. // --------------------------------------------------------------------
  385. /**
  386. * The error message number
  387. *
  388. * @access private
  389. * @return integer
  390. */
  391. function _error_number()
  392. {
  393. return mysql_errno($this->conn_id);
  394. }
  395. // --------------------------------------------------------------------
  396. /**
  397. * Escape the SQL Identifiers
  398. *
  399. * This function escapes column and table names
  400. *
  401. * @access private
  402. * @param string
  403. * @return string
  404. */
  405. function _escape_identifiers($item)
  406. {
  407. if ($this->_escape_char == '')
  408. {
  409. return $item;
  410. }
  411. foreach ($this->_reserved_identifiers as $id)
  412. {
  413. if (strpos($item, '.'.$id) !== FALSE)
  414. {
  415. $str = $this->_escape_char. str_replace('.', $this->_escape_char.'.', $item);
  416. // remove duplicates if the user already included the escape
  417. return preg_replace('/['.$this->_escape_char.']+/', $this->_escape_char, $str);
  418. }
  419. }
  420. if (strpos($item, '.') !== FALSE)
  421. {
  422. $str = $this->_escape_char.str_replace('.', $this->_escape_char.'.'.$this->_escape_char, $item).$this->_escape_char;
  423. }
  424. else
  425. {
  426. $str = $this->_escape_char.$item.$this->_escape_char;
  427. }
  428. // remove duplicates if the user already included the escape
  429. return preg_replace('/['.$this->_escape_char.']+/', $this->_escape_char, $str);
  430. }
  431. // --------------------------------------------------------------------
  432. /**
  433. * From Tables
  434. *
  435. * This function implicitly groups FROM tables so there is no confusion
  436. * about operator precedence in harmony with SQL standards
  437. *
  438. * @access public
  439. * @param type
  440. * @return type
  441. */
  442. function _from_tables($tables)
  443. {
  444. if ( ! is_array($tables))
  445. {
  446. $tables = array($tables);
  447. }
  448. return '('.implode(', ', $tables).')';
  449. }
  450. // --------------------------------------------------------------------
  451. /**
  452. * Insert statement
  453. *
  454. * Generates a platform-specific insert string from the supplied data
  455. *
  456. * @access public
  457. * @param string the table name
  458. * @param array the insert keys
  459. * @param array the insert values
  460. * @return string
  461. */
  462. function _insert($table, $keys, $values)
  463. {
  464. return "INSERT INTO ".$table." (".implode(', ', $keys).") VALUES (".implode(', ', $values).")";
  465. }
  466. // --------------------------------------------------------------------
  467. /**
  468. * Replace statement
  469. *
  470. * Generates a platform-specific replace string from the supplied data
  471. *
  472. * @access public
  473. * @param string the table name
  474. * @param array the insert keys
  475. * @param array the insert values
  476. * @return string
  477. */
  478. function _replace($table, $keys, $values)
  479. {
  480. return "REPLACE INTO ".$table." (".implode(', ', $keys).") VALUES (".implode(', ', $values).")";
  481. }
  482. // --------------------------------------------------------------------
  483. /**
  484. * Insert_batch statement
  485. *
  486. * Generates a platform-specific insert string from the supplied data
  487. *
  488. * @access public
  489. * @param string the table name
  490. * @param array the insert keys
  491. * @param array the insert values
  492. * @return string
  493. */
  494. function _insert_batch($table, $keys, $values)
  495. {
  496. return "INSERT INTO ".$table." (".implode(', ', $keys).") VALUES ".implode(', ', $values);
  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
  508. * @param array the orderby clause
  509. * @param array the limit clause
  510. * @return string
  511. */
  512. function _update($table, $values, $where, $orderby = array(), $limit = FALSE)
  513. {
  514. foreach ($values as $key => $val)
  515. {
  516. $valstr[] = $key . ' = ' . $val;
  517. }
  518. $limit = ( ! $limit) ? '' : ' LIMIT '.$limit;
  519. $orderby = (count($orderby) >= 1)?' ORDER BY '.implode(", ", $orderby):'';
  520. $sql = "UPDATE ".$table." SET ".implode(', ', $valstr);
  521. $sql .= ($where != '' AND count($where) >=1) ? " WHERE ".implode(" ", $where) : '';
  522. $sql .= $orderby.$limit;
  523. return $sql;
  524. }
  525. // --------------------------------------------------------------------
  526. /**
  527. * Update_Batch statement
  528. *
  529. * Generates a platform-specific batch update string from the supplied data
  530. *
  531. * @access public
  532. * @param string the table name
  533. * @param array the update data
  534. * @param array the where clause
  535. * @return string
  536. */
  537. function _update_batch($table, $values, $index, $where = NULL)
  538. {
  539. $ids = array();
  540. $where = ($where != '' AND count($where) >=1) ? implode(" ", $where).' AND ' : '';
  541. foreach ($values as $key => $val)
  542. {
  543. $ids[] = $val[$index];
  544. foreach (array_keys($val) as $field)
  545. {
  546. if ($field != $index)
  547. {
  548. $final[$field][] = 'WHEN '.$index.' = '.$val[$index].' THEN '.$val[$field];
  549. }
  550. }
  551. }
  552. $sql = "UPDATE ".$table." SET ";
  553. $cases = '';
  554. foreach ($final as $k => $v)
  555. {
  556. $cases .= $k.' = CASE '."\n";
  557. foreach ($v as $row)
  558. {
  559. $cases .= $row."\n";
  560. }
  561. $cases .= 'ELSE '.$k.' END, ';
  562. }
  563. $sql .= substr($cases, 0, -2);
  564. $sql .= ' WHERE '.$where.$index.' IN ('.implode(',', $ids).')';
  565. return $sql;
  566. }
  567. // --------------------------------------------------------------------
  568. /**
  569. * Truncate statement
  570. *
  571. * Generates a platform-specific truncate string from the supplied data
  572. * If the database does not support the truncate() command
  573. * This function maps to "DELETE FROM table"
  574. *
  575. * @access public
  576. * @param string the table name
  577. * @return string
  578. */
  579. function _truncate($table)
  580. {
  581. return "TRUNCATE ".$table;
  582. }
  583. // --------------------------------------------------------------------
  584. /**
  585. * Delete statement
  586. *
  587. * Generates a platform-specific delete string from the supplied data
  588. *
  589. * @access public
  590. * @param string the table name
  591. * @param array the where clause
  592. * @param string the limit clause
  593. * @return string
  594. */
  595. function _delete($table, $where = array(), $like = array(), $limit = FALSE)
  596. {
  597. $conditions = '';
  598. if (count($where) > 0 OR count($like) > 0)
  599. {
  600. $conditions = "\nWHERE ";
  601. $conditions .= implode("\n", $this->ar_where);
  602. if (count($where) > 0 && count($like) > 0)
  603. {
  604. $conditions .= " AND ";
  605. }
  606. $conditions .= implode("\n", $like);
  607. }
  608. $limit = ( ! $limit) ? '' : ' LIMIT '.$limit;
  609. return "DELETE FROM ".$table.$conditions.$limit;
  610. }
  611. // --------------------------------------------------------------------
  612. /**
  613. * Limit string
  614. *
  615. * Generates a platform-specific LIMIT clause
  616. *
  617. * @access public
  618. * @param string the sql query string
  619. * @param integer the number of rows to limit the query to
  620. * @param integer the offset value
  621. * @return string
  622. */
  623. function _limit($sql, $limit, $offset)
  624. {
  625. if ($offset == 0)
  626. {
  627. $offset = '';
  628. }
  629. else
  630. {
  631. $offset .= ", ";
  632. }
  633. return $sql."LIMIT ".$offset.$limit;
  634. }
  635. // --------------------------------------------------------------------
  636. /**
  637. * Close DB Connection
  638. *
  639. * @access public
  640. * @param resource
  641. * @return void
  642. */
  643. function _close($conn_id)
  644. {
  645. @mysql_close($conn_id);
  646. }
  647. }
  648. /* End of file mysql_driver.php */
  649. /* Location: ./system/database/drivers/mysql/mysql_driver.php */