[ Index ]
 

Code source de Serendipity 1.2

Accédez au Source d'autres logiciels libres

title

Body

[fermer]

/include/db/ -> mysqli.inc.php (source)

   1  <?php # $Id: mysqli.inc.php 1659 2007-03-30 10:02:05Z garvinhicking $
   2  # Copyright (c) 2003-2005, Jannis Hermanns (on behalf the Serendipity Developer Team)
   3  # All rights reserved.  See LICENSE file for licensing details
   4  
   5  /**
   6   * Tells the DB Layer to start a DB transaction.
   7   *
   8   * @access public
   9   */
  10  function serendipity_db_begin_transaction(){
  11      serendipity_db_query('start transaction');
  12  }
  13  
  14  /**
  15   * Tells the DB Layer to end a DB transaction.
  16   *
  17   * @access public
  18   * @param  boolean  If true, perform the query. If false, rollback.
  19   */
  20  function serendipity_db_end_transaction($commit){
  21      if ($commit){
  22          serendipity_db_query('commit');
  23      }else{
  24          serendipity_db_query('rollback');
  25      }
  26  }
  27  
  28  /**
  29   * Assemble and return SQL condition for a "IN (...)" clause
  30   *
  31   * @access public
  32   * @param  string   table column name
  33   * @param  array    referenced array of values to search for in the "IN (...)" clause
  34   * @param  string   condition of how to associate the different input values of the $search_ids parameter
  35   * @return string   resulting SQL string
  36   */
  37  function serendipity_db_in_sql($col, &$search_ids, $type = ' OR ') {
  38      return $col . " IN (" . implode(', ', $search_ids) . ")";
  39  }
  40  
  41  /**
  42   * Perform a DB Layer SQL query.
  43   *
  44   * This function returns values dependin on the input parameters and the result of the query.
  45   * It can return:
  46   *   false if there was an error,
  47   *   true if the query succeeded but did not generate any rows
  48   *   array of field values if it returned a single row and $single is true
  49   *   array of array of field values if it returned row(s) [stacked array]
  50   *
  51   * @access public
  52   * @param   string      SQL query to execute
  53   * @param   boolean     Toggle whether the expected result is a single row (TRUE) or multiple rows (FALSE). This affects whether the returned array is 1 or 2 dimensional!
  54   * @param   string      Result type of the array indexing. Can be one of "assoc" (associative), "num" (numerical), "both" (numerical and associative, default)
  55   * @param   boolean     If true, errors will be reported. If false, errors will be ignored.
  56   * @param   string      A possible array key name, so that you can control the multi-dimensional mapping of an array by the key column
  57   * @param   string      A possible array field name, so that you can control the multi-dimensional mapping of an array by the key column and the field value.
  58   * @param   boolean     If true, the executed SQL error is known to fail, and should be disregarded (errors can be ignroed on DUPLICATE INDEX queries and the likes)
  59   * @return  mixed       Returns the result of the SQL query, depending on the input parameters
  60   */
  61  function &serendipity_db_query($sql, $single = false, $result_type = "both", $reportErr = false, $assocKey = false, $assocVal = false, $expectError = false) {
  62      global $serendipity;
  63      static $type_map = array('assoc' => MYSQLI_ASSOC, 'num' => MYSQLI_NUM, 'both' => MYSQLI_BOTH, 'true' => true, 'false' => false);
  64  
  65      if ($expectError) {
  66          $c = @mysqli_query($serendipity['dbConn'], $sql);
  67      } else {
  68          $c = mysqli_query($serendipity['dbConn'], $sql);
  69      }
  70  
  71      if (!$expectError && mysqli_error($serendipity['dbConn']) != '') {
  72          $msg = mysqli_error($serendipity['dbConn']);
  73          return $msg;
  74      }
  75  
  76      if (!$c) {
  77          if (!$expectError && !$serendipity['production']) {
  78              print mysqli_error($serendipity['dbConn']);
  79              if (function_exists('debug_backtrace') && $reportErr == true) {
  80                  highlight_string(var_export(debug_backtrace(), 1));
  81              }
  82          }
  83  
  84          return $type_map['false'];
  85      }
  86  
  87      if ($c === true) {
  88          return $type_map['true'];
  89      }
  90  
  91      $result_type = $type_map[$result_type];
  92  
  93      switch(mysqli_num_rows($c)) {
  94          case 0:
  95              if ($single) {
  96                  return $type_map['false'];
  97              }
  98              return $type_map['true'];
  99          case 1:
 100              if ($single) {
 101                  return mysqli_fetch_array($c, $result_type);
 102              }
 103          default:
 104              if ($single) {
 105                  return mysqli_fetch_array($c, $result_type);
 106              }
 107  
 108              $rows = array();
 109              while ($row = mysqli_fetch_array($c, $result_type)) {
 110                  if (!empty($assocKey)) {
 111                      // You can fetch a key-associated array via the two function parameters assocKey and assocVal
 112                      if (empty($assocVal)) {
 113                          $rows[$row[$assocKey]] = $row;
 114                      } else {
 115                          $rows[$row[$assocKey]] = $row[$assocVal];
 116                      }
 117                  } else {
 118                      $rows[] = $row;
 119                  }
 120              }
 121              return $rows;
 122      }
 123  }
 124  
 125  /**
 126   * Returns the latest INSERT_ID of an SQL INSERT INTO command, for auto-increment columns
 127   *
 128   * @access public
 129   * @return int      Value of the auto-increment column
 130   */
 131  function serendipity_db_insert_id() {
 132      global $serendipity;
 133      return mysqli_insert_id($serendipity['dbConn']);
 134  }
 135  
 136  /**
 137   * Returns the number of affected rows of a SQL query
 138   *
 139   * @access public
 140   * @return int      Number of affected rows
 141   */
 142  function serendipity_db_affected_rows() {
 143      global $serendipity;
 144      return mysqli_affected_rows($serendipity['dbConn']);
 145  }
 146  
 147  /**
 148   * Returns the number of updated rows in a SQL query
 149   *
 150   * @access public
 151   * @return int  Number of updated rows
 152   */
 153  function serendipity_db_updated_rows() {
 154      global $serendipity;
 155  
 156      preg_match(
 157          "/^[^0-9]+([0-9]+)[^0-9]+([0-9]+)[^0-9]+([0-9]+)/",
 158          mysqli_info($serendipity['dbConn']),
 159          $arr);
 160          // mysqli_affected_rows returns 0 if rows were matched but not changed.
 161          // mysqli_info returns rows matched
 162          return $arr[1];
 163  }
 164  
 165  /**
 166   * Returns the number of matched rows in a SQL query
 167   *
 168   * @access public
 169   * @return int  Number of matched rows
 170   */
 171  function serendipity_db_matched_rows() {
 172      global $serendipity;
 173  
 174      preg_match(
 175          "/^[^0-9]+([0-9]+)[^0-9]+([0-9]+)[^0-9]+([0-9]+)/",
 176          mysqli_info($serendipity['dbConn']),
 177          $arr);
 178          // mysqli_affected_rows returns 0 if rows were matched but not changed.
 179          // mysqli_info returns rows matched
 180          return $arr[0];
 181  }
 182  
 183  /**
 184   * Returns a escaped string, so that it can be safely included in a SQL string encapsulated within quotes, without allowing SQL injection.
 185   *
 186   * @access  public
 187   * @param   string   input string
 188   * @return  string   output string
 189   */
 190  function serendipity_db_escape_string($string) {
 191      global $serendipity;
 192      return mysqli_escape_string($serendipity['dbConn'], $string);
 193  }
 194  
 195  /**
 196   * Returns the option to a LIMIT SQL statement, because it varies accross DB systems
 197   *
 198   * @access public
 199   * @param  int      Number of the first row to return data from
 200   * @param  int      Number of rows to return
 201   * @return string   SQL string to pass to a LIMIT statement
 202   */
 203  function serendipity_db_limit($start, $offset) {
 204      return $start . ', ' . $offset;
 205  }
 206  
 207  /**
 208   * Return a LIMIT SQL option to the DB Layer as a full LIMIT statement
 209   *
 210   * @access public
 211   * @param   SQL string of a LIMIT option
 212   * @return  SQL string containing a full LIMIT statement
 213   */
 214  function serendipity_db_limit_sql($limitstring) {
 215      return ' LIMIT ' . $limitstring;
 216  }
 217  
 218  /**
 219   * Connect to the configured Database
 220   *
 221   * @access public
 222   * @return  ressource   connection handle
 223   */
 224  function serendipity_db_connect() {
 225      global $serendipity;
 226  
 227      if (isset($serendipity['dbConn'])) {
 228          return $serendipity['dbConn'];
 229      }
 230  
 231      $function = 'mysqli_connect';
 232  
 233      $connparts = explode(':', $serendipity['dbHost']);
 234      if (!empty($connparts[1])) {
 235          // A "hostname:port" connection was specified
 236          $serendipity['dbConn'] = $function($connparts[0], $serendipity['dbUser'], $serendipity['dbPass'], $serendipity['dbName'], $connparts[1]);
 237      } else {
 238          // Connect with default ports
 239          $serendipity['dbConn'] = $function($connparts[0], $serendipity['dbUser'], $serendipity['dbPass']);
 240      }
 241      mysqli_select_db($serendipity['dbConn'], $serendipity['dbName']);
 242      serendipity_db_reconnect();
 243  
 244      return $serendipity['dbConn'];
 245  }
 246  
 247  function serendipity_db_reconnect() {
 248      global $serendipity;
 249  
 250      if (isset($serendipity['dbCharset'])) {
 251          mysqli_query($serendipity['dbConn'], "SET NAMES " . $serendipity['dbCharset']);
 252          define('SQL_CHARSET_INIT', true);
 253      } elseif (defined('SQL_CHARSET') && $serendipity['dbNames'] && !defined('SQL_CHARSET_INIT')) {
 254          mysqli_query($serendipity['dbConn'], "SET NAMES " . SQL_CHARSET, $serendipity['dbConn']);
 255      }
 256  }
 257  
 258  /**
 259   * Prepares a Serendipty query input to fully valid SQL. Replaces certain "template" variables.
 260   *
 261   * @access public
 262   * @param  string   SQL query with template variables to convert
 263   * @return ressource    SQL ressource handle of the executed query
 264   */
 265  function serendipity_db_schema_import($query) {
 266      static $search  = array('{AUTOINCREMENT}', '{PRIMARY}',
 267          '{UNSIGNED}', '{FULLTEXT}', '{FULLTEXT_MYSQL}', '{BOOLEAN}');
 268      static $replace = array('int(11) not null auto_increment', 'primary key',
 269          'unsigned'  , 'FULLTEXT', 'FULLTEXT', 'enum (\'true\', \'false\') NOT NULL default \'true\'');
 270      static $is_utf8 = null;
 271      global $serendipity;
 272  
 273      if ($is_utf8 === null) {
 274          $search[] = '{UTF_8}';
 275          if (  $_POST['charset'] == 'UTF-8/' ||
 276                $serendipity['charset'] == 'UTF-8/' ||
 277                $serendipity['POST']['charset'] == 'UTF-8/' ||
 278                LANG_CHARSET == 'UTF-8' ) {
 279              $replace[] = '/*!40100 CHARACTER SET utf8 COLLATE utf8_unicode_ci */';
 280          } else {
 281              $replace[] = '';
 282          }
 283      }
 284  
 285      $query = trim(str_replace($search, $replace, $query));
 286      if ($query{0} == '@') {
 287          // Errors are expected to happen (like duplicate index creation)
 288          return serendipity_db_query(substr($query, 1), false, 'both', false, false, false, true);
 289      } else {
 290          return serendipity_db_query($query);
 291      }
 292  }
 293  
 294  /**
 295   * Try to connect to the configured Database (during installation)
 296   *
 297   * @access public
 298   * @param  array     input configuration array, holding the connection info
 299   * @param  array     referenced array which holds the errors that might be encountered
 300   * @return boolean   return true on success, false on error
 301   */
 302  function serendipity_db_probe($hash, &$errs) {
 303      global $serendipity;
 304  
 305      if (!function_exists('mysqli_connect')) {
 306          $errs[] = 'No mySQLi extension found. Please check your webserver installation or contact your systems administrator regarding this problem.';
 307          return false;
 308      }
 309  
 310      $function = 'mysqli_connect';
 311      $connparts = explode(':', $hash['dbHost']);
 312      if (!empty($connparts[1])) {
 313          // A "hostname:port" connection was specified
 314          $c = @$function($connparts[0], $hash['dbUser'], $hash['dbPass'], $hash['dbName'], $connparts[1]);
 315      } else {
 316          // Connect with default ports
 317          $c = @$function($connparts[0], $hash['dbUser'], $hash['dbPass']);
 318      }
 319  
 320      if (!$c) {
 321          $errs[] = 'Could not connect to database; check your settings.';
 322          $errs[] = 'The mySQL error was: ' . mysqli_connect_error();
 323          return false;
 324      }
 325  
 326      $serendipity['dbConn'] = $c;
 327  
 328      if ( !@mysqli_select_db($c, $hash['dbName']) ) {
 329          $errs[] = 'The database you specified does not exist.';
 330          $errs[] = 'The mySQL error was: ' . mysqli_error($c);
 331          return false;
 332      }
 333  
 334      return true;
 335  }
 336  
 337  /**
 338   * Returns the SQL code used for concatenating strings
 339   *
 340   * @access public
 341   * @param  string   Input string/column to concatenate
 342   * @return string   SQL parameter
 343   */
 344  function serendipity_db_concat($string) {
 345      return 'concat(' . $string . ')';
 346  }
 347  
 348  /* vim: set sts=4 ts=4 expandtab : */


Généré le : Sat Nov 24 09:00:37 2007 par Balluche grâce à PHPXref 0.7
  Clicky Web Analytics