database.mysqli.inc

Database interface code for MySQL database servers using the mysqli client libraries. mysqli is included in PHP 5 by default and allows developers to use the advanced features of MySQL 4.1.x, 5.0.x and beyond.

File

drupal-6.x/includes/database.mysqli.inc
View source
  1. <?php
  2. /**
  3. * @file
  4. * Database interface code for MySQL database servers using the mysqli client libraries. mysqli is included in PHP 5 by default and allows developers to use the advanced features of MySQL 4.1.x, 5.0.x and beyond.
  5. */
  6. // Maintainers of this file should consult:
  7. // http://www.php.net/manual/en/ref.mysqli.php
  8. /**
  9. * @ingroup database
  10. * @{
  11. */
  12. // Include functions shared between mysql and mysqli.
  13. require_once './includes/database.mysql-common.inc';
  14. /**
  15. * Report database status.
  16. */
  17. function db_status_report($phase) {
  18. $t = get_t();
  19. $version = db_version();
  20. $form['mysql'] = array(
  21. 'title' => $t('MySQL database'),
  22. 'value' => ($phase == 'runtime') ? l($version, 'admin/reports/status/sql') : $version,
  23. );
  24. if (version_compare($version, DRUPAL_MINIMUM_MYSQL) < 0) {
  25. $form['mysql']['severity'] = REQUIREMENT_ERROR;
  26. $form['mysql']['description'] = $t('Your MySQL Server is too old. Drupal requires at least MySQL %version.', array('%version' => DRUPAL_MINIMUM_MYSQL));
  27. }
  28. return $form;
  29. }
  30. /**
  31. * Returns the version of the database server currently in use.
  32. *
  33. * @return Database server version
  34. */
  35. function db_version() {
  36. global $active_db;
  37. list($version) = explode('-', mysqli_get_server_info($active_db));
  38. return $version;
  39. }
  40. /**
  41. * Initialise a database connection.
  42. *
  43. * Note that mysqli does not support persistent connections.
  44. */
  45. function db_connect($url) {
  46. // Check if MySQLi support is present in PHP
  47. if (!function_exists('mysqli_init') && !extension_loaded('mysqli')) {
  48. _db_error_page('Unable to use the MySQLi database because the MySQLi extension for PHP is not installed. Check your <code>php.ini</code> to see how you can enable it.');
  49. }
  50. $url = parse_url($url);
  51. // Decode urlencoded information in the db connection string
  52. $url['user'] = urldecode($url['user']);
  53. // Test if database URL has a password.
  54. $url['pass'] = isset($url['pass']) ? urldecode($url['pass']) : '';
  55. $url['host'] = urldecode($url['host']);
  56. $url['path'] = urldecode($url['path']);
  57. if (!isset($url['port'])) {
  58. $url['port'] = NULL;
  59. }
  60. $connection = mysqli_init();
  61. @mysqli_real_connect($connection, $url['host'], $url['user'], $url['pass'], substr($url['path'], 1), $url['port'], NULL, MYSQLI_CLIENT_FOUND_ROWS);
  62. if (mysqli_connect_errno() > 0) {
  63. _db_error_page(mysqli_connect_error());
  64. }
  65. // Force MySQL to use the UTF-8 character set. Also set the collation, if a
  66. // certain one has been set; otherwise, MySQL defaults to 'utf8_general_ci'
  67. // for UTF-8.
  68. if (!empty($GLOBALS['db_collation'])) {
  69. mysqli_query($connection, 'SET NAMES utf8 COLLATE ' . $GLOBALS['db_collation']);
  70. }
  71. else {
  72. mysqli_query($connection, 'SET NAMES utf8');
  73. }
  74. return $connection;
  75. }
  76. /**
  77. * Helper function for db_query().
  78. */
  79. function _db_query($query, $debug = 0) {
  80. global $active_db, $queries, $user;
  81. if (variable_get('dev_query', 0)) {
  82. list($usec, $sec) = explode(' ', microtime());
  83. $timer = (float)$usec + (float)$sec;
  84. // If devel.module query logging is enabled, prepend a comment with the username and calling function
  85. // to the SQL string. This is useful when running mysql's SHOW PROCESSLIST to learn what exact
  86. // code is issueing the slow query.
  87. $bt = debug_backtrace();
  88. // t() may not be available yet so we don't wrap 'Anonymous'
  89. $name = $user->uid ? $user->name : variable_get('anonymous', 'Anonymous');
  90. // str_replace() to prevent SQL injection via username or anonymous name.
  91. $name = str_replace(array('*', '/'), '', $name);
  92. $query = '/* '. $name .' : '. $bt[2]['function'] .' */ '. $query;
  93. }
  94. $result = mysqli_query($active_db, $query);
  95. if (variable_get('dev_query', 0)) {
  96. $query = $bt[2]['function'] ."\n". $query;
  97. list($usec, $sec) = explode(' ', microtime());
  98. $stop = (float)$usec + (float)$sec;
  99. $diff = $stop - $timer;
  100. $queries[] = array($query, $diff);
  101. }
  102. if ($debug) {
  103. print '<p>query: '. $query .'<br />error:'. mysqli_error($active_db) .'</p>';
  104. }
  105. if (!mysqli_errno($active_db)) {
  106. return $result;
  107. }
  108. else {
  109. // Indicate to drupal_error_handler that this is a database error.
  110. ${DB_ERROR} = TRUE;
  111. trigger_error(check_plain(mysqli_error($active_db) ."\nquery: ". $query), E_USER_WARNING);
  112. return FALSE;
  113. }
  114. }
  115. /**
  116. * Fetch one result row from the previous query as an object.
  117. *
  118. * @param $result
  119. * A database query result resource, as returned from db_query().
  120. * @return
  121. * An object representing the next row of the result, or FALSE. The attributes
  122. * of this object are the table fields selected by the query.
  123. */
  124. function db_fetch_object($result) {
  125. if ($result) {
  126. $object = mysqli_fetch_object($result);
  127. return isset($object) ? $object : FALSE;
  128. }
  129. }
  130. /**
  131. * Fetch one result row from the previous query as an array.
  132. *
  133. * @param $result
  134. * A database query result resource, as returned from db_query().
  135. * @return
  136. * An associative array representing the next row of the result, or FALSE.
  137. * The keys of this object are the names of the table fields selected by the
  138. * query, and the values are the field values for this result row.
  139. */
  140. function db_fetch_array($result) {
  141. if ($result) {
  142. $array = mysqli_fetch_array($result, MYSQLI_ASSOC);
  143. return isset($array) ? $array : FALSE;
  144. }
  145. }
  146. /**
  147. * Return an individual result field from the previous query.
  148. *
  149. * Only use this function if exactly one field is being selected; otherwise,
  150. * use db_fetch_object() or db_fetch_array().
  151. *
  152. * @param $result
  153. * A database query result resource, as returned from db_query().
  154. * @return
  155. * The resulting field or FALSE.
  156. */
  157. function db_result($result) {
  158. if ($result && mysqli_num_rows($result) > 0) {
  159. // The mysqli_fetch_row function has an optional second parameter $row
  160. // but that can't be used for compatibility with Oracle, DB2, etc.
  161. $array = mysqli_fetch_row($result);
  162. return $array[0];
  163. }
  164. return FALSE;
  165. }
  166. /**
  167. * Determine whether the previous query caused an error.
  168. */
  169. function db_error() {
  170. global $active_db;
  171. return mysqli_errno($active_db);
  172. }
  173. /**
  174. * Determine the number of rows changed by the preceding query.
  175. */
  176. function db_affected_rows() {
  177. global $active_db; /* mysqli connection resource */
  178. return mysqli_affected_rows($active_db);
  179. }
  180. /**
  181. * Runs a limited-range query in the active database.
  182. *
  183. * Use this as a substitute for db_query() when a subset of the query is to be
  184. * returned.
  185. * User-supplied arguments to the query should be passed in as separate parameters
  186. * so that they can be properly escaped to avoid SQL injection attacks.
  187. *
  188. * @param $query
  189. * A string containing an SQL query.
  190. * @param ...
  191. * A variable number of arguments which are substituted into the query
  192. * using printf() syntax. The query arguments can be enclosed in one
  193. * array instead.
  194. * Valid %-modifiers are: %s, %d, %f, %b (binary data, do not enclose
  195. * in '') and %%.
  196. *
  197. * NOTE: using this syntax will cast NULL and FALSE values to decimal 0,
  198. * and TRUE values to decimal 1.
  199. *
  200. * @param $from
  201. * The first result row to return.
  202. * @param $count
  203. * The maximum number of result rows to return.
  204. * @return
  205. * A database query result resource, or FALSE if the query was not executed
  206. * correctly.
  207. */
  208. function db_query_range($query) {
  209. $args = func_get_args();
  210. $count = array_pop($args);
  211. $from = array_pop($args);
  212. array_shift($args);
  213. $query = db_prefix_tables($query);
  214. if (isset($args[0]) and is_array($args[0])) { // 'All arguments in one array' syntax
  215. $args = $args[0];
  216. }
  217. _db_query_callback($args, TRUE);
  218. $query = preg_replace_callback(DB_QUERY_REGEXP, '_db_query_callback', $query);
  219. $query .= ' LIMIT '. (int)$from .', '. (int)$count;
  220. return _db_query($query);
  221. }
  222. /**
  223. * Runs a SELECT query and stores its results in a temporary table.
  224. *
  225. * Use this as a substitute for db_query() when the results need to be stored
  226. * in a temporary table.
  227. *
  228. * User-supplied arguments to the query should be passed in as separate parameters
  229. * so that they can be properly escaped to avoid SQL injection attacks.
  230. *
  231. * Note that if you need to know how many results were returned, you should do
  232. * a SELECT COUNT(*) on the temporary table afterwards. db_affected_rows() does
  233. * not give consistent result across different database types in this case.
  234. *
  235. * @param $query
  236. * A string containing a normal SELECT SQL query.
  237. * @param ...
  238. * A variable number of arguments which are substituted into the query
  239. * using printf() syntax. The query arguments can be enclosed in one
  240. * array instead.
  241. * Valid %-modifiers are: %s, %d, %f, %b (binary data, do not enclose
  242. * in '') and %%.
  243. *
  244. * NOTE: using this syntax will cast NULL and FALSE values to decimal 0,
  245. * and TRUE values to decimal 1.
  246. * @param $table
  247. * The name of the temporary table to select into. This name will not be
  248. * prefixed as there is no risk of collision.
  249. *
  250. * @return
  251. * A database query result resource, or FALSE if the query was not executed
  252. * correctly.
  253. */
  254. function db_query_temporary($query) {
  255. $args = func_get_args();
  256. $tablename = array_pop($args);
  257. array_shift($args);
  258. $query = preg_replace('/^SELECT/i', 'CREATE TEMPORARY TABLE '. $tablename .' Engine=HEAP SELECT', db_prefix_tables($query));
  259. if (isset($args[0]) and is_array($args[0])) { // 'All arguments in one array' syntax
  260. $args = $args[0];
  261. }
  262. _db_query_callback($args, TRUE);
  263. $query = preg_replace_callback(DB_QUERY_REGEXP, '_db_query_callback', $query);
  264. return _db_query($query);
  265. }
  266. /**
  267. * Returns a properly formatted Binary Large Object value.
  268. *
  269. * @param $data
  270. * Data to encode.
  271. * @return
  272. * Encoded data.
  273. */
  274. function db_encode_blob($data) {
  275. global $active_db;
  276. return "'". mysqli_real_escape_string($active_db, $data) ."'";
  277. }
  278. /**
  279. * Returns text from a Binary Large OBject value.
  280. *
  281. * @param $data
  282. * Data to decode.
  283. * @return
  284. * Decoded data.
  285. */
  286. function db_decode_blob($data) {
  287. return $data;
  288. }
  289. /**
  290. * Prepare user input for use in a database query, preventing SQL injection attacks.
  291. */
  292. function db_escape_string($text) {
  293. global $active_db;
  294. return mysqli_real_escape_string($active_db, $text);
  295. }
  296. /**
  297. * Lock a table.
  298. */
  299. function db_lock_table($table) {
  300. db_query('LOCK TABLES {'. db_escape_table($table) .'} WRITE');
  301. }
  302. /**
  303. * Unlock all locked tables.
  304. */
  305. function db_unlock_tables() {
  306. db_query('UNLOCK TABLES');
  307. }
  308. /**
  309. * Check if a table exists.
  310. *
  311. * @param $table
  312. * The name of the table.
  313. *
  314. * @return
  315. * TRUE if the table exists, and FALSE if the table does not exist.
  316. */
  317. function db_table_exists($table) {
  318. return (bool) db_fetch_object(db_query("SHOW TABLES LIKE '{". db_escape_table($table) ."}'"));
  319. }
  320. /**
  321. * Check if a column exists in the given table.
  322. *
  323. * @param $table
  324. * The name of the table.
  325. * @param $column
  326. * The name of the column.
  327. *
  328. * @return
  329. * TRUE if the column exists, and FALSE if the column does not exist.
  330. */
  331. function db_column_exists($table, $column) {
  332. return (bool) db_fetch_object(db_query("SHOW COLUMNS FROM {". db_escape_table($table) ."} LIKE '". db_escape_table($column) ."'"));
  333. }
  334. /**
  335. * @} End of "ingroup database".
  336. */