[ Index ]

PHP Cross Reference of Drupal 6 (yi-drupal)

title

Body

[close]

/includes/ -> database.mysql.inc (source)

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


Generated: Mon Jul 9 18:01:44 2012 Cross-referenced by PHPXref 0.7