2 // $Id: database.mysql.inc,v 1.66.2.2 2007/10/19 21:49:26 drumm Exp $
6 * Database interface code for MySQL database servers.
16 * Report database status.
18 function db_status_report($phase) {
21 $version = db_version();
23 $form['mysql'] = array(
24 'title' => $t('MySQL database'),
25 'value' => ($phase == 'runtime') ? l($version, 'admin/logs/status/sql') : $version,
28 if (version_compare($version, DRUPAL_MINIMUM_MYSQL) < 0) {
29 $form['mysql']['severity'] = REQUIREMENT_ERROR;
30 $form['mysql']['description'] = $t('Your MySQL Server is too old. Drupal requires at least MySQL %version.', array('%version' => DRUPAL_MINIMUM_MYSQL));
37 * Returns the version of the database server currently in use.
39 * @return Database server version
41 function db_version() {
42 list($version) = explode('-', mysql_get_server_info());
47 * Initialize a database connection.
49 * Note that you can change the mysql_connect() call to mysql_pconnect() if you
50 * want to use persistent connections. This is not recommended on shared hosts,
51 * and might require additional database/webserver tuning. It can increase
52 * performance, however, when the overhead to connect to your database is high
53 * (e.g. your database and web server live on different machines).
55 function db_connect($url) {
56 $url = parse_url($url);
58 // Check if MySQL support is present in PHP
59 if (!function_exists('mysql_connect')) {
60 // Redirect to installer if using default DB credentials
61 if ($url['user'] == 'username' && $url['pass'] == 'password') {
62 include_once 'includes/install.inc';
63 install_goto('install.php');
65 drupal_maintenance_theme();
66 drupal_set_title('PHP MySQL support not enabled');
67 print theme('maintenance_page', '<p>We were unable to use the MySQL database because the MySQL extension for PHP is not installed. Check your <code>PHP.ini</code> to see how you can enable it.</p>
68 <p>For more help, see the <a href="http://drupal.org/node/258">Installation and upgrading handbook</a>. If you are unsure what these terms mean you should probably contact your hosting provider.</p>');
72 // Decode url-encoded information in the db connection string
73 $url['user'] = urldecode($url['user']);
74 // Test if database url has a password.
75 if(isset($url['pass'])) {
76 $url['pass'] = urldecode($url['pass']);
81 $url['host'] = urldecode($url['host']);
82 $url['path'] = urldecode($url['path']);
84 // Allow for non-standard MySQL port.
85 if (isset($url['port'])) {
86 $url['host'] = $url['host'] .':'. $url['port'];
89 // - TRUE makes mysql_connect() always open a new link, even if
90 // mysql_connect() was called before with the same parameters.
91 // This is important if you are using two databases on the same
93 // - 2 means CLIENT_FOUND_ROWS: return the number of found
94 // (matched) rows, not the number of affected rows.
95 $connection = @mysql_connect($url['host'], $url['user'], $url['pass'], TRUE, 2);
97 // Redirect to installer if using default DB credentials
98 if ($url['user'] == 'username' && $url['pass'] == 'password') {
99 include_once 'includes/install.inc';
100 install_goto('install.php');
103 // Show error screen otherwise
104 drupal_maintenance_theme();
105 drupal_set_header('HTTP/1.1 503 Service Unavailable');
106 drupal_set_title('Unable to connect to database server');
107 print theme('maintenance_page', '<p>If you still have to install Drupal, proceed to the <a href="'. base_path() .'install.php">installation page</a>.</p>
108 <p>If you have already finished installing Drupal, this either means that the username and password information in your <code>settings.php</code> file is incorrect or that we can\'t connect to the MySQL database server. This could mean your hosting provider\'s database server is down.</p>
109 <p>The MySQL error was: '. theme('placeholder', mysql_error()) .'.</p>
110 <p>Currently, the username is '. theme('placeholder', $url['user']) .' and the database server is '. theme('placeholder', $url['host']) .'.</p>
112 <li>Are you sure you have the correct username and password?</li>
113 <li>Are you sure that you have typed the correct hostname?</li>
114 <li>Are you sure that the database server is running?</li>
116 <p>For more help, see the <a href="http://drupal.org/node/258">Installation and upgrading handbook</a>. If you are unsure what these terms mean you should probably contact your hosting provider.</p>');
120 if (!mysql_select_db(substr($url['path'], 1))) {
121 drupal_maintenance_theme();
122 drupal_set_title('Unable to select database');
123 print theme('maintenance_page', '<p>We were able to connect to the MySQL database server (which means your username and password are okay) but not able to select the database.</p>
124 <p>The MySQL error was: '. theme('placeholder', mysql_error($connection)) .'.</p>
125 <p>Currently, the database is '. theme('placeholder', substr($url['path'], 1)) .'. The username is '. theme('placeholder', $url['user']) .' and the database server is '. theme('placeholder', $url['host']) .'.</p>
127 <li>Are you sure you have the correct database name?</li>
128 <li>Are you sure the database exists?</li>
129 <li>Are you sure the username has permission to access the database?</li>
131 <p>For more help, see the <a href="http://drupal.org/node/258">Installation and upgrading handbook</a>. If you are unsure what these terms mean you should probably contact your hosting provider.</p>');
135 /* On MySQL 4.1 and later, force UTF-8 */
136 if (version_compare(mysql_get_server_info(), '4.1.0', '>=')) {
137 mysql_query('SET NAMES "utf8"', $connection);
143 * Helper function for db_query().
145 function _db_query($query, $debug = 0) {
146 global $active_db, $queries;
148 if (variable_get('dev_query', 0)) {
149 list($usec, $sec) = explode(' ', microtime());
150 $timer = (float)$usec + (float)$sec;
153 $result = mysql_query($query, $active_db);
155 if (variable_get('dev_query', 0)) {
156 $bt = debug_backtrace();
157 $query = $bt[2]['function'] . "\n" . $query;
158 list($usec, $sec) = explode(' ', microtime());
159 $stop = (float)$usec + (float)$sec;
160 $diff = $stop - $timer;
161 $queries[] = array($query, $diff);
165 print '<p>query: '. $query .'<br />error:'. mysql_error($active_db) .'</p>';
168 if (!mysql_errno($active_db)) {
172 trigger_error(check_plain(mysql_error($active_db) ."\nquery: ". $query), E_USER_WARNING);
178 * Fetch one result row from the previous query as an object.
181 * A database query result resource, as returned from db_query().
183 * An object representing the next row of the result. The attributes of this
184 * object are the table fields selected by the query.
186 function db_fetch_object($result) {
188 return mysql_fetch_object($result);
193 * Fetch one result row from the previous query as an array.
196 * A database query result resource, as returned from db_query().
198 * An associative array representing the next row of the result. The keys of
199 * this object are the names of the table fields selected by the query, and
200 * the values are the field values for this result row.
202 function db_fetch_array($result) {
204 return mysql_fetch_array($result, MYSQL_ASSOC);
209 * Determine how many result rows were found by the preceding query.
212 * A database query result resource, as returned from db_query().
214 * The number of result rows.
216 function db_num_rows($result) {
218 return mysql_num_rows($result);
223 * Return an individual result field from the previous query.
225 * Only use this function if exactly one field is being selected; otherwise,
226 * use db_fetch_object() or db_fetch_array().
229 * A database query result resource, as returned from db_query().
231 * The index of the row whose result is needed.
233 * The resulting field or FALSE.
235 function db_result($result, $row = 0) {
236 if ($result && mysql_num_rows($result) > $row) {
237 return mysql_result($result, $row);
243 * Determine whether the previous query caused an error.
245 function db_error() {
247 return mysql_errno($active_db);
251 * Return a new unique ID in the given sequence.
253 * For compatibility reasons, Drupal does not use auto-numbered fields in its
254 * database tables. Instead, this function is used to return a new unique ID
255 * of the type requested. If necessary, a new sequence with the given name
258 * Note that the table name should be in curly brackets to preserve compatibility
259 * with table prefixes. For example, db_next_id('{node}_nid');
261 function db_next_id($name) {
262 $name = db_prefix_tables($name);
263 db_query('LOCK TABLES {sequences} WRITE');
264 $id = db_result(db_query("SELECT id FROM {sequences} WHERE name = '%s'", $name)) + 1;
265 db_query("REPLACE INTO {sequences} VALUES ('%s', %d)", $name, $id);
266 db_query('UNLOCK TABLES');
272 * Determine the number of rows changed by the preceding query.
274 function db_affected_rows() {
276 return mysql_affected_rows($active_db);
280 * Runs a limited-range query in the active database.
282 * Use this as a substitute for db_query() when a subset of the query is to be
284 * User-supplied arguments to the query should be passed in as separate parameters
285 * so that they can be properly escaped to avoid SQL injection attacks.
288 * A string containing an SQL query.
290 * A variable number of arguments which are substituted into the query
291 * using printf() syntax. The query arguments can be enclosed in one
293 * Valid %-modifiers are: %s, %d, %f, %b (binary data, do not enclose
296 * NOTE: using this syntax will cast NULL and FALSE values to decimal 0,
297 * and TRUE values to decimal 1.
300 * The first result row to return.
302 * The maximum number of result rows to return.
304 * A database query result resource, or FALSE if the query was not executed
307 function db_query_range($query) {
308 $args = func_get_args();
309 $count = array_pop($args);
310 $from = array_pop($args);
313 $query = db_prefix_tables($query);
314 if (isset($args[0]) and is_array($args[0])) { // 'All arguments in one array' syntax
317 _db_query_callback($args, TRUE);
318 $query = preg_replace_callback(DB_QUERY_REGEXP, '_db_query_callback', $query);
319 $query .= ' LIMIT '. (int)$from .', '. (int)$count;
320 return _db_query($query);
324 * Runs a SELECT query and stores its results in a temporary table.
326 * Use this as a substitute for db_query() when the results need to stored
327 * in a temporary table. Temporary tables exist for the duration of the page
329 * User-supplied arguments to the query should be passed in as separate parameters
330 * so that they can be properly escaped to avoid SQL injection attacks.
332 * Note that if you need to know how many results were returned, you should do
333 * a SELECT COUNT(*) on the temporary table afterwards. db_num_rows() and
334 * db_affected_rows() do not give consistent result across different database
335 * types in this case.
338 * A string containing a normal SELECT SQL query.
340 * A variable number of arguments which are substituted into the query
341 * using printf() syntax. The query arguments can be enclosed in one
343 * Valid %-modifiers are: %s, %d, %f, %b (binary data, do not enclose
346 * NOTE: using this syntax will cast NULL and FALSE values to decimal 0,
347 * and TRUE values to decimal 1.
350 * The name of the temporary table to select into. This name will not be
351 * prefixed as there is no risk of collision.
353 * A database query result resource, or FALSE if the query was not executed
356 function db_query_temporary($query) {
357 $args = func_get_args();
358 $tablename = array_pop($args);
361 $query = preg_replace('/^SELECT/i', 'CREATE TEMPORARY TABLE '. $tablename .' SELECT', db_prefix_tables($query));
362 if (isset($args[0]) and is_array($args[0])) { // 'All arguments in one array' syntax
365 _db_query_callback($args, TRUE);
366 $query = preg_replace_callback(DB_QUERY_REGEXP, '_db_query_callback', $query);
367 return _db_query($query);
371 * Returns a properly formatted Binary Large OBject value.
378 function db_encode_blob($data) {
380 return "'" . mysql_real_escape_string($data, $active_db) . "'";
384 * Returns text from a Binary Large Object value.
391 function db_decode_blob($data) {
396 * Prepare user input for use in a database query, preventing SQL injection attacks.
398 function db_escape_string($text) {
400 return mysql_real_escape_string($text, $active_db);
406 function db_lock_table($table) {
407 db_query('LOCK TABLES {'. db_escape_table($table) .'} WRITE');
411 * Unlock all locked tables.
413 function db_unlock_tables() {
414 db_query('UNLOCK TABLES');
418 * Check if a table exists.
420 function db_table_exists($table) {
421 return db_num_rows(db_query("SHOW TABLES LIKE '{" . db_escape_table($table) . "}'"));
425 * Wraps the given table.field entry with a DISTINCT(). The wrapper is added to
426 * the SELECT list entry of the given query and the resulting query is returned.
427 * This function only applies the wrapper if a DISTINCT doesn't already exist in
430 * @param $table Table containing the field to set as DISTINCT
431 * @param $field Field to set as DISTINCT
432 * @param $query Query to apply the wrapper to
433 * @return SQL query with the DISTINCT wrapper surrounding the given table.field.
435 function db_distinct_field($table, $field, $query) {
436 $field_to_select = 'DISTINCT('. $table .'.'. $field .')';
437 // (?<!text) is a negative look-behind (no need to rewrite queries that already use DISTINCT).
438 return preg_replace('/(SELECT.*)(?:'. $table .'\.|\s)(?<!DISTINCT\()(?<!DISTINCT\('. $table .'\.)'. $field .'(.*FROM )/AUsi', '\1 '. $field_to_select .'\2', $query);
442 * @} End of "ingroup database".