mysqli_driver.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502
  1. <?php
  2. defined('IN_WEB') or die('Include Error!');
  3. /**
  4. * MySQLi Database Adapter Class
  5. *
  6. * Note: _DB is an extender class that the app controller
  7. * creates dynamically based on whether the query builder
  8. * class is being used or not.
  9. */
  10. class CI_DB_mysqli_driver extends CI_DB_query_builder {
  11. /**
  12. * Database driver
  13. *
  14. * @var string
  15. */
  16. public $dbdriver = 'mysqli';
  17. /**
  18. * Compression flag
  19. *
  20. * @var bool
  21. */
  22. public $compress = FALSE;
  23. /**
  24. * DELETE hack flag
  25. *
  26. * Whether to use the MySQL "delete hack" which allows the number
  27. * of affected rows to be shown. Uses a preg_replace when enabled,
  28. * adding a bit more processing to all queries.
  29. *
  30. * @var bool
  31. */
  32. public $delete_hack = TRUE;
  33. /**
  34. * Strict ON flag
  35. *
  36. * Whether we're running in strict SQL mode.
  37. *
  38. * @var bool
  39. */
  40. public $stricton;
  41. // --------------------------------------------------------------------
  42. /**
  43. * Identifier escape character
  44. *
  45. * @var string
  46. */
  47. protected $_escape_char = '`';
  48. // --------------------------------------------------------------------
  49. /**
  50. * MySQLi object
  51. *
  52. * Has to be preserved without being assigned to $conn_id.
  53. *
  54. * @var MySQLi
  55. */
  56. protected $_mysqli;
  57. // --------------------------------------------------------------------
  58. /**
  59. * Database connection
  60. *
  61. * @param bool $persistent
  62. * @return object
  63. */
  64. public function db_connect($persistent = FALSE)
  65. {
  66. // Do we have a socket path?
  67. if ($this->hostname[0] === '/')
  68. {
  69. $hostname = NULL;
  70. $port = NULL;
  71. $socket = $this->hostname;
  72. }
  73. else
  74. {
  75. $hostname = ($persistent === TRUE)
  76. ? 'p:'.$this->hostname : $this->hostname;
  77. $port = empty($this->port) ? NULL : $this->port;
  78. $socket = NULL;
  79. }
  80. $client_flags = ($this->compress === TRUE) ? MYSQLI_CLIENT_COMPRESS : 0;
  81. $this->_mysqli = mysqli_init();
  82. $this->_mysqli->options(MYSQLI_OPT_CONNECT_TIMEOUT, 10);
  83. if (isset($this->stricton))
  84. {
  85. if ($this->stricton)
  86. {
  87. $this->_mysqli->options(MYSQLI_INIT_COMMAND, 'SET SESSION sql_mode = CONCAT(@@sql_mode, ",", "STRICT_ALL_TABLES")');
  88. }
  89. else
  90. {
  91. $this->_mysqli->options(MYSQLI_INIT_COMMAND,
  92. 'SET SESSION sql_mode =
  93. REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(
  94. @@sql_mode,
  95. "STRICT_ALL_TABLES,", ""),
  96. ",STRICT_ALL_TABLES", ""),
  97. "STRICT_ALL_TABLES", ""),
  98. "STRICT_TRANS_TABLES,", ""),
  99. ",STRICT_TRANS_TABLES", ""),
  100. "STRICT_TRANS_TABLES", "")'
  101. );
  102. }
  103. }
  104. if (is_array($this->encrypt))
  105. {
  106. $ssl = array();
  107. empty($this->encrypt['ssl_key']) OR $ssl['key'] = $this->encrypt['ssl_key'];
  108. empty($this->encrypt['ssl_cert']) OR $ssl['cert'] = $this->encrypt['ssl_cert'];
  109. empty($this->encrypt['ssl_ca']) OR $ssl['ca'] = $this->encrypt['ssl_ca'];
  110. empty($this->encrypt['ssl_capath']) OR $ssl['capath'] = $this->encrypt['ssl_capath'];
  111. empty($this->encrypt['ssl_cipher']) OR $ssl['cipher'] = $this->encrypt['ssl_cipher'];
  112. if ( ! empty($ssl))
  113. {
  114. if (isset($this->encrypt['ssl_verify']))
  115. {
  116. if ($this->encrypt['ssl_verify'])
  117. {
  118. defined('MYSQLI_OPT_SSL_VERIFY_SERVER_CERT') && $this->_mysqli->options(MYSQLI_OPT_SSL_VERIFY_SERVER_CERT, TRUE);
  119. }
  120. // Apparently (when it exists), setting MYSQLI_OPT_SSL_VERIFY_SERVER_CERT
  121. // to FALSE didn't do anything, so PHP 5.6.16 introduced yet another
  122. // constant ...
  123. //
  124. // https://secure.php.net/ChangeLog-5.php#5.6.16
  125. // https://bugs.php.net/bug.php?id=68344
  126. elseif (defined('MYSQLI_CLIENT_SSL_DONT_VERIFY_SERVER_CERT'))
  127. {
  128. $client_flags |= MYSQLI_CLIENT_SSL_DONT_VERIFY_SERVER_CERT;
  129. }
  130. }
  131. $client_flags |= MYSQLI_CLIENT_SSL;
  132. $this->_mysqli->ssl_set(
  133. isset($ssl['key']) ? $ssl['key'] : NULL,
  134. isset($ssl['cert']) ? $ssl['cert'] : NULL,
  135. isset($ssl['ca']) ? $ssl['ca'] : NULL,
  136. isset($ssl['capath']) ? $ssl['capath'] : NULL,
  137. isset($ssl['cipher']) ? $ssl['cipher'] : NULL
  138. );
  139. }
  140. }
  141. if ($this->_mysqli->real_connect($hostname, $this->username, $this->password, $this->database, $port, $socket, $client_flags))
  142. {
  143. // Prior to version 5.7.3, MySQL silently downgrades to an unencrypted connection if SSL setup fails
  144. if (
  145. ($client_flags & MYSQLI_CLIENT_SSL)
  146. && version_compare($this->_mysqli->client_info, '5.7.3', '<=')
  147. && empty($this->_mysqli->query("SHOW STATUS LIKE 'ssl_cipher'")->fetch_object()->Value)
  148. )
  149. {
  150. $this->_mysqli->close();
  151. $message = 'MySQLi was configured for an SSL connection, but got an unencrypted connection instead!';
  152. log_message('error', $message);
  153. return ($this->db_debug) ? $this->display_error($message, '', TRUE) : FALSE;
  154. }
  155. return $this->_mysqli;
  156. }
  157. return FALSE;
  158. }
  159. // --------------------------------------------------------------------
  160. /**
  161. * Reconnect
  162. *
  163. * Keep / reestablish the db connection if no queries have been
  164. * sent for a length of time exceeding the server's idle timeout
  165. *
  166. * @return void
  167. */
  168. public function reconnect()
  169. {
  170. if ($this->conn_id !== FALSE && $this->conn_id->ping() === FALSE)
  171. {
  172. $this->conn_id = FALSE;
  173. }
  174. }
  175. // --------------------------------------------------------------------
  176. /**
  177. * Select the database
  178. *
  179. * @param string $database
  180. * @return bool
  181. */
  182. public function db_select($database = '')
  183. {
  184. if ($database === '')
  185. {
  186. $database = $this->database;
  187. }
  188. if ($this->conn_id->select_db($database))
  189. {
  190. $this->database = $database;
  191. $this->data_cache = array();
  192. return TRUE;
  193. }
  194. return FALSE;
  195. }
  196. // --------------------------------------------------------------------
  197. /**
  198. * Set client character set
  199. *
  200. * @param string $charset
  201. * @return bool
  202. */
  203. protected function _db_set_charset($charset)
  204. {
  205. return $this->conn_id->set_charset($charset);
  206. }
  207. // --------------------------------------------------------------------
  208. /**
  209. * Database version number
  210. *
  211. * @return string
  212. */
  213. public function version()
  214. {
  215. if (isset($this->data_cache['version']))
  216. {
  217. return $this->data_cache['version'];
  218. }
  219. return $this->data_cache['version'] = $this->conn_id->server_info;
  220. }
  221. // --------------------------------------------------------------------
  222. /**
  223. * Execute the query
  224. *
  225. * @param string $sql an SQL query
  226. * @return mixed
  227. */
  228. protected function _execute($sql)
  229. {
  230. return $this->conn_id->query($this->_prep_query($sql));
  231. }
  232. // --------------------------------------------------------------------
  233. /**
  234. * Prep the query
  235. *
  236. * If needed, each database adapter can prep the query string
  237. *
  238. * @param string $sql an SQL query
  239. * @return string
  240. */
  241. protected function _prep_query($sql)
  242. {
  243. // mysqli_affected_rows() returns 0 for "DELETE FROM TABLE" queries. This hack
  244. // modifies the query so that it a proper number of affected rows is returned.
  245. if ($this->delete_hack === TRUE && preg_match('/^\s*DELETE\s+FROM\s+(\S+)\s*$/i', $sql))
  246. {
  247. return trim($sql).' WHERE 1=1';
  248. }
  249. return $sql;
  250. }
  251. // --------------------------------------------------------------------
  252. /**
  253. * Begin Transaction
  254. *
  255. * @return bool
  256. */
  257. protected function _trans_begin()
  258. {
  259. $this->conn_id->autocommit(FALSE);
  260. return is_php('5.5')
  261. ? $this->conn_id->begin_transaction()
  262. : $this->simple_query('START TRANSACTION'); // can also be BEGIN or BEGIN WORK
  263. }
  264. // --------------------------------------------------------------------
  265. /**
  266. * Commit Transaction
  267. *
  268. * @return bool
  269. */
  270. protected function _trans_commit()
  271. {
  272. if ($this->conn_id->commit())
  273. {
  274. $this->conn_id->autocommit(TRUE);
  275. return TRUE;
  276. }
  277. return FALSE;
  278. }
  279. // --------------------------------------------------------------------
  280. /**
  281. * Rollback Transaction
  282. *
  283. * @return bool
  284. */
  285. protected function _trans_rollback()
  286. {
  287. if ($this->conn_id->rollback())
  288. {
  289. $this->conn_id->autocommit(TRUE);
  290. return TRUE;
  291. }
  292. return FALSE;
  293. }
  294. // --------------------------------------------------------------------
  295. /**
  296. * Platform-dependent string escape
  297. *
  298. * @param string
  299. * @return string
  300. */
  301. protected function _escape_str($str)
  302. {
  303. return $this->conn_id->real_escape_string($str);
  304. }
  305. // --------------------------------------------------------------------
  306. /**
  307. * Affected Rows
  308. *
  309. * @return int
  310. */
  311. public function affected_rows()
  312. {
  313. return $this->conn_id->affected_rows;
  314. }
  315. // --------------------------------------------------------------------
  316. /**
  317. * Insert ID
  318. *
  319. * @return int
  320. */
  321. public function insert_id()
  322. {
  323. return $this->conn_id->insert_id;
  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. * @param bool $prefix_limit
  332. * @return string
  333. */
  334. protected function _list_tables($prefix_limit = FALSE)
  335. {
  336. $sql = 'SHOW TABLES FROM '.$this->escape_identifiers($this->database);
  337. if ($prefix_limit !== FALSE && $this->dbprefix !== '')
  338. {
  339. return $sql." LIKE '".$this->escape_like_str($this->dbprefix)."%'";
  340. }
  341. return $sql;
  342. }
  343. // --------------------------------------------------------------------
  344. /**
  345. * Show column query
  346. *
  347. * Generates a platform-specific query string so that the column names can be fetched
  348. *
  349. * @param string $table
  350. * @return string
  351. */
  352. protected function _list_columns($table = '')
  353. {
  354. return 'SHOW COLUMNS FROM '.$this->protect_identifiers($table, TRUE, NULL, FALSE);
  355. }
  356. // --------------------------------------------------------------------
  357. /**
  358. * Returns an object with field data
  359. *
  360. * @param string $table
  361. * @return array
  362. */
  363. public function field_data($table)
  364. {
  365. if (($query = $this->query('SHOW COLUMNS FROM '.$this->protect_identifiers($table, TRUE, NULL, FALSE))) === FALSE)
  366. {
  367. return FALSE;
  368. }
  369. $query = $query->result_object();
  370. $retval = array();
  371. for ($i = 0, $c = count($query); $i < $c; $i++)
  372. {
  373. $retval[$i] = new stdClass();
  374. $retval[$i]->name = $query[$i]->Field;
  375. sscanf($query[$i]->Type, '%[a-z](%d)',
  376. $retval[$i]->type,
  377. $retval[$i]->max_length
  378. );
  379. $retval[$i]->default = $query[$i]->Default;
  380. $retval[$i]->primary_key = (int) ($query[$i]->Key === 'PRI');
  381. }
  382. return $retval;
  383. }
  384. // --------------------------------------------------------------------
  385. /**
  386. * Error
  387. *
  388. * Returns an array containing code and message of the last
  389. * database error that has occurred.
  390. *
  391. * @return array
  392. */
  393. public function error()
  394. {
  395. if ( ! empty($this->_mysqli->connect_errno))
  396. {
  397. return array(
  398. 'code' => $this->_mysqli->connect_errno,
  399. 'message' => $this->_mysqli->connect_error
  400. );
  401. }
  402. return array('code' => $this->conn_id->errno, 'message' => $this->conn_id->error);
  403. }
  404. // --------------------------------------------------------------------
  405. /**
  406. * FROM tables
  407. *
  408. * Groups tables in FROM clauses if needed, so there is no confusion
  409. * about operator precedence.
  410. *
  411. * @return string
  412. */
  413. protected function _from_tables()
  414. {
  415. if ( ! empty($this->qb_join) && count($this->qb_from) > 1)
  416. {
  417. return '('.implode(', ', $this->qb_from).')';
  418. }
  419. return implode(', ', $this->qb_from);
  420. }
  421. // --------------------------------------------------------------------
  422. /**
  423. * Close DB Connection
  424. *
  425. * @return void
  426. */
  427. protected function _close()
  428. {
  429. $this->conn_id->close();
  430. }
  431. }