[ Index ]

PHP Cross Reference of Drupal 6 (gatewave)

title

Body

[close]

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

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


Generated: Thu Mar 24 11:18:33 2011 Cross-referenced by PHPXref 0.7