[ Index ]
 

Code source de GeekLog 1.4.1

Accédez au Source d'autres logiciels libres

title

Body

[fermer]

/system/databases/ -> mysql.class.php (source)

   1  <?php
   2  
   3  /* Reminder: always indent with 4 spaces (no tabs). */
   4  // +---------------------------------------------------------------------------+
   5  // | Geeklog 1.4                                                               |
   6  // +---------------------------------------------------------------------------+
   7  // | mysql.class.php                                                           |
   8  // |                                                                           |
   9  // | mysql database class                                                      |
  10  // +---------------------------------------------------------------------------+
  11  // | Copyright (C) 2000-2006 by the following authors:                         |
  12  // |                                                                           |
  13  // | Authors: Tony Bibbs, tony AT tonybibbs DOT com                            |
  14  // +---------------------------------------------------------------------------+
  15  // |                                                                           |
  16  // | This program is free software; you can redistribute it and/or             |
  17  // | modify it under the terms of the GNU General Public License               |
  18  // | as published by the Free Software Foundation; either version 2            |
  19  // | of the License, or (at your option) any later version.                    |
  20  // |                                                                           |
  21  // | This program is distributed in the hope that it will be useful,           |
  22  // | but WITHOUT ANY WARRANTY; without even the implied warranty of            |
  23  // | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the             |
  24  // | GNU General Public License for more details.                              |
  25  // |                                                                           |
  26  // | You should have received a copy of the GNU General Public License         |
  27  // | along with this program; if not, write to the Free Software Foundation,   |
  28  // | Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.           |
  29  // |                                                                           |
  30  // +---------------------------------------------------------------------------+
  31  //
  32  // $Id: mysql.class.php,v 1.26 2006/10/03 19:44:40 dhaun Exp $
  33  
  34  /**
  35  * This file is the mysql implementation of the Geeklog abstraction layer.
  36  * Unfortunately the Geeklog abstraction layer isn't 100% abstract because a few
  37  * key functions use MySQL's REPLACE INTO syntax which is not a SQL standard.
  38  * This issue will need to be resolved some time ...
  39  *
  40  */
  41  class database {
  42  
  43      // PRIVATE PROPERTIES
  44      
  45      /**
  46      * @access private
  47      */
  48      var $_host = '';
  49      /**
  50      * @access private
  51      */
  52      var $_name = '';
  53      /**
  54      * @access private
  55      */
  56      var $_user = '';
  57      /**
  58      * @access private
  59      */
  60      var $_pass = '';
  61      /**
  62      * @access private
  63      */
  64      var $_db = '';
  65      /**
  66      * @access private
  67      */
  68      var $_verbose = false;
  69      /**
  70      * @access private
  71      */
  72      var $_display_error = false;
  73      /**
  74      * @access private
  75      */
  76      var $_errorlog_fn = '';
  77      /**
  78      * @access private
  79      */
  80      var $_charset = '';
  81      /**
  82      * @access private
  83      */
  84      var $_mysql_version = 0;
  85  
  86      // PRIVATE METHODS
  87  
  88      /**
  89      * Logs messages
  90      *
  91      * Logs messages by calling the function held in $_errorlog_fn
  92      *
  93      * @param    string      $msg        Message to log
  94      * @access   private
  95      */
  96      function _errorlog($msg)
  97      {
  98          $function = $this->_errorlog_fn;
  99          if (function_exists($function)) {
 100              $function($msg);
 101          }
 102      }
 103  
 104      /**
 105      * Connects to the MySQL database server
 106      *
 107      * This function connects to the MySQL server and returns the connection object
 108      *
 109      * @return   object      Returns connection object
 110      * @access   private
 111      *
 112      */
 113      function _connect()
 114      {
 115          if ($this->isVerbose()) {
 116              $this->_errorlog("\n*** Inside database->_connect ***");
 117          }
 118  
 119          // Connect to MySQL server
 120          $this->_db = mysql_connect($this->_host,$this->_user,$this->_pass) or die('Cannot connect to DB server');
 121  
 122          if ($this->_mysql_version == 0) {
 123              $v = mysql_get_server_info ();
 124              preg_match ('/^([0-9]+).([0-9]+).([0-9]+)/', $v, $match);
 125              $v = (intval ($match[1]) * 10000) + (intval ($match[2]) * 100)
 126                 + intval ($match[3]);
 127              $this->_mysql_version = $v;
 128          }
 129  
 130          // Set the database
 131          @mysql_select_db($this->_name) or die('error selecting database');
 132  
 133          if (!($this->_db)) {
 134              if ($this->isVerbose()) {
 135                  $this->_errorlog("\n*** Error in database->_connect ***");
 136              }
 137  
 138              // damn, got an error.
 139              $this->dbError();
 140          }
 141  
 142          if ($this->_mysql_version >= 40100) {
 143              if ($this->_charset == 'utf-8') {
 144                  @mysql_query ("SET NAMES 'utf8'", $this->_db);
 145              }
 146          }
 147  
 148          if ($this->isVerbose()) {
 149              $this->_errorlog("\n***leaving database->_connect***");
 150          }
 151      }
 152  
 153      // PUBLIC METHODS
 154  
 155      /**
 156      * constructor for database
 157      *
 158      * This initializes an instance of the database object
 159      *
 160      * @param        string      $dbhost     Database host
 161      * @param        string      $dbname     Name of database
 162      * @param        sring       $dbuser     User to make connection as
 163      * @param        string      $pass       Password for dbuser
 164      * @param        string      $errorlogfn Name of the errorlog function
 165      * @param        string      $charset    character set to use
 166      *
 167      */
 168      function database($dbhost,$dbname,$dbuser,$dbpass,$errorlogfn='',$charset='')
 169      {
 170          $this->_host = $dbhost;
 171          $this->_name = $dbname;
 172          $this->_user = $dbuser;
 173          $this->_pass = $dbpass;
 174          $this->_verbose = false;
 175          $this->_errorlog_fn = $errorlogfn;
 176          $this->_charset = $charset;
 177          $this->_mysql_version = 0;
 178  
 179          $this->_connect();
 180      }
 181  
 182      /**
 183      * Turns debug mode on
 184      *
 185      * Set this to true to see debug messages
 186      *
 187      * @param    boolean     $flag   true or false
 188      *
 189      */
 190      function setVerbose($flag)
 191      {
 192          $this->_verbose = $flag;
 193      }
 194  
 195      /**
 196      * Turns detailed error reporting on
 197      *
 198      * If set to true, this will display detailed error messages on the site.
 199      * Otherwise, it will only that state an error occurred without going into
 200      * details. The complete error message (including the offending SQL request)
 201      * is always available from error.log.
 202      *
 203      * @param    boolean     $flag   true or false
 204      *
 205      */
 206      function setDisplayError($flag)
 207      {
 208          $this->_display_error = $flag;
 209      }
 210  
 211      /**
 212      * Checks to see if debug mode is on
 213      *
 214      * Returns value of $_verbose
 215      *
 216      * @return   boolean     true if in verbose mode otherwise false
 217      *
 218      */
 219      function isVerbose()
 220      {
 221          if ($this->_verbose && (empty($this->_errorlog_fn) || !function_exists($this->_errorlog_fn))) {
 222              print "\n<br><b>Can't run mysql.class.php verbosely because the errorlog "
 223                  . "function wasn't set or doesn't exist</b><br>\n";
 224              return false;
 225          }
 226  
 227          return $this->_verbose;
 228      }
 229  
 230      /**
 231      * Sets the function this class should call to log debug messages
 232      *
 233      * @param        string      $functionname   Function name
 234      *
 235      */
 236      function setErrorFunction($functionname)
 237      {
 238          $this->_errorlog_fn = $functionname;
 239      }
 240  
 241      /**
 242      * Executes a query on the MySQL server
 243      *
 244      * This executes the passed SQL and returns the recordset or errors out
 245      *
 246      * @param    string      $sql            SQL to be executed
 247      * @param    boolean     $ignore_error   If 1 this function supresses any error messages
 248      * @return   object      Returns results of query
 249      *
 250      */
 251      function dbQuery($sql,$ignore_errors=0)
 252      {
 253          if ($this->isVerbose()) {
 254              $this->_errorlog("\n***inside database->dbQuery***");
 255              $this->_errorlog("\n*** sql to execute is $sql ***");
 256          }
 257  
 258          // Run query
 259          if ($ignore_errors == 1) {
 260              $result = @mysql_query($sql,$this->_db);
 261          } else {
 262              $result = @mysql_query($sql,$this->_db) or die($this->dbError($sql));
 263          }
 264  
 265          // If OK, return otherwise echo error
 266          if (mysql_errno() == 0 && !empty($result)) {
 267              if ($this->isVerbose()) {
 268                  $this->_errorlog("\n***sql ran just fine***");
 269                  $this->_errorlog("\n*** Leaving database->dbQuery ***");
 270              }
 271              return $result;
 272  
 273          } else {
 274              // callee may want to supress printing of errors
 275              if ($ignore_errors == 1) return false;
 276  
 277              if ($this->isVerbose()) {
 278                  $this->_errorlog("\n***sql caused an error***");
 279                  $this->_errorlog("\n*** Leaving database->dbQuery ***");
 280              }
 281          }
 282      }
 283  
 284      /**
 285      * Saves information to the database
 286      *
 287      * This will use a REPLACE INTO to save a record into the
 288      * database
 289      *
 290      * @param    string      $table      The table to save to
 291      * @param    string      $fields     string  Comma demlimited list of fields to save
 292      * @param    string      $values     Values to save to the database table
 293      *
 294      */
 295      function dbSave($table,$fields,$values)
 296      {
 297          if ($this->isVerbose()) {
 298              $this->_errorlog("\n*** Inside database->dbSave ***");
 299          }
 300  
 301          $sql = "REPLACE INTO $table ($fields) VALUES ($values)";
 302  
 303          $this->dbQuery($sql);
 304  
 305          if ($this->isVerbose()) {
 306              $this->_errorlog("\n*** Leaving database->dbSave ***");
 307          }
 308      }
 309  
 310      /**
 311      * Deletes data from the database
 312      *
 313      * This will delete some data from the given table where id = value.  If
 314      * id and value are arrays then it will traverse the arrays setting
 315      * $id[curval] = $value[curval].
 316      *
 317      * @param    string          $table      Table to delete data from
 318      * @param    array|string    $id         field name(s) to include in where clause
 319      * @param    array|string    $value      field value(s) corresponding to field names
 320      * @return   boolean     Returns true on success otherwise false
 321      *
 322      */
 323      function dbDelete($table,$id,$value)
 324      {
 325          if ($this->isVerbose()) {
 326              $this->_errorlog("\n*** inside database->dbDelete ***");
 327          }
 328  
 329          $sql = "DELETE FROM $table";
 330  
 331          if (is_array($id) || is_array($value)) {
 332              if (is_array($id) && is_array($value) && count($id) == count($value)) {
 333                  // they are arrays, traverse them and build sql
 334                  $sql .= ' WHERE ';
 335                  for ($i = 1; $i <= count($id); $i++) {
 336                      if ($i == count($id)) {
 337                          $sql .= current($id) . " = '" . current($value) . "'";
 338                      } else {
 339                          $sql .= current($id) . " = '" . current($value) . "' AND ";
 340                      }
 341                      next($id);
 342                      next($value);
 343                  }
 344              } else {
 345                  // error, they both have to be arrays and of the
 346                  // same size
 347                  return false;
 348              }
 349          } else {
 350              // just regular string values, build sql
 351              if (!empty($id) && ( isset($value) || $value != "")) { 
 352                  $sql .= " WHERE $id = '$value'";
 353              }
 354          }
 355  
 356          $this->dbQuery($sql);
 357  
 358          if ($this->isVerbose()) {
 359              $this->_errorlog("\n*** inside database->dbDelete ***");
 360          }
 361  
 362          return true;
 363      }
 364  
 365      /**
 366      * Changes records in a table
 367      *
 368      * This will change the data in the given table that meet the given criteria and will
 369      * redirect user to another page if told to do so
 370      *
 371      * @param    string          $table          Table to perform change on
 372      * @param    string          $item_to_set    field name of unique ID field for table
 373      * @param    string          $value_to_set   Value for id
 374      * @param    array|string    $id             additional field name used in where clause
 375      * @param    array|string    $value          additional values used in where clause
 376      * @param    boolean         $supress_quotes if false it will not use '<value>' in where clause
 377      * @return   boolean     Returns true on success otherwise false
 378      *
 379      */
 380      function dbChange($table,$item_to_set,$value_to_set,$id,$value, $supress_quotes=false)
 381      {
 382          if ($this->isVerbose()) {
 383              $this->_errorlog("\n*** Inside dbChange ***");
 384          }
 385  
 386          if ($supress_quotes) {
 387              $sql = "UPDATE $table SET $item_to_set = $value_to_set";
 388          } else {
 389              $sql = "UPDATE $table SET $item_to_set = '$value_to_set'";
 390          } 
 391  
 392          if (is_array($id) || is_array($value)) {
 393              if (is_array($id) && is_array($value) && count($id) == count($value)) {
 394                  // they are arrays, traverse them and build sql
 395                  $sql .= ' WHERE ';
 396                  for ($i = 1; $i <= count($id); $i++) {
 397                      if ($i == count($id)) {
 398                          $sql .= current($id) . " = '" . current($value) . "'";
 399                      } else {
 400                          $sql .= current($id) . " = '" . current($value) . "' AND ";
 401                      }
 402                      next($id);
 403                      next($value);
 404                  }
 405              } else {
 406                  // error, they both have to be arrays and of the
 407                  // same size
 408                  return false;
 409              }
 410          } else {
 411              // These are regular strings, build sql
 412              if (!empty($id) && ( isset($value) || $value != "")) { 
 413                  $sql .= " WHERE $id = '$value'";
 414              }
 415          }
 416  
 417          if ($this->isVerbose()) {
 418              $this->_errorlog("dbChange sql = $sql");
 419          }
 420  
 421          $this->dbQuery($sql);
 422  
 423          if ($this->isVerbose()) {
 424              $this->_errorlog("\n*** Leaving database->dbChange ***");
 425          }
 426  
 427      }
 428  
 429      /**
 430      * Returns the number of records for a query that meets the given criteria
 431      *
 432      * This will build a SELECT count(*) statement with the given criteria and
 433      * return the result
 434      *
 435      * @param    string          $table  Table to perform count on
 436      * @param    array|string    $id     field name(s) of fields to use in where clause
 437      * @param    array|string    $value  Value(s) to use in where clause
 438      * @return   boolean     returns count on success otherwise false
 439      *
 440      */
 441      function dbCount($table,$id='',$value='')
 442      {
 443          if ($this->isVerbose()) {
 444              $this->_errorlog("\n*** Inside database->dbCount ***");
 445          }
 446  
 447          $sql = "SELECT COUNT(*) FROM $table";
 448  
 449          if (is_array($id) || is_array($value)) {
 450              if (is_array($id) && is_array($value) && count($id) == count($value)) {
 451                  // they are arrays, traverse them and build sql
 452                  $sql .= ' WHERE ';
 453                  for ($i = 1; $i <= count($id); $i++) {
 454                      if ($i == count($id)) {
 455                          $sql .= current($id) . " = '" . current($value) . "'";
 456                      } else {
 457                          $sql .= current($id) . " = '" . current($value) . "' AND ";
 458                      }
 459                      next($id);
 460                      next($value);
 461                  }
 462              } else {
 463                  // error, they both have to be arrays and of the
 464                  // same size
 465                  return false;
 466              }
 467          } else {
 468              if (!empty($id) && ( isset($value) || $value != "")) { 
 469                  $sql .= " WHERE $id = '$value'";
 470              }
 471          }
 472  
 473          if ($this->isVerbose()) {
 474              $this->_errorlog("\n*** sql = $sql ***");
 475          }
 476  
 477          $result = $this->dbQuery($sql);
 478  
 479          if ($this->isVerbose()) {
 480              $this->_errorlog("\n*** Leaving database->dbCount ***");
 481          }
 482  
 483          return ($this->dbResult($result,0));
 484  
 485      }
 486  
 487      /**
 488      * Copies a record from one table to another (can be the same table)
 489      *
 490      * This will use a REPLACE INTO...SELECT FROM to copy a record from one table
 491      * to another table.  They can be the same table.
 492      *
 493      * @param    string          $table      Table to insert record into
 494      * @param    string          $fields     Comma delmited list of fields to copy over
 495      * @param    string          $values     Values to store in database fields
 496      * @param    string          $tablefrom  Table to get record from
 497      * @param    array|string    $id         field name(s) to use in where clause
 498      * @param    array|string    $value      Value(s) to use in where clause
 499      * @return   boolean     Returns true on success otherwise false
 500      *
 501      */
 502      function dbCopy($table,$fields,$values,$tablefrom,$id,$value)
 503      {
 504          if ($this->isVerbose()) {
 505              $this->_errorlog("\n*** Inside database->dbCopy ***");
 506          }
 507  
 508          $sql = "REPLACE INTO $table ($fields) SELECT $values FROM $tablefrom";
 509  
 510          if (is_array($id) || is_array($value)) {
 511              if (is_array($id) && is_array($value) && count($id) == count($value)) {
 512                  // they are arrays, traverse them and build sql
 513                  $sql .= ' WHERE ';
 514                  for ($i = 1; $i <= count($id); $i++) {
 515                      if ($i == count($id)) {
 516                          $sql .= current($id) . " = '" . current($value) . "'";
 517                      } else {
 518                          $sql .= current($id) . " = '" . current($value) . "' AND ";
 519                      }
 520                      next($id);
 521                      next($value);
 522                  }
 523              } else {
 524                  // error, they both have to be arrays and of the
 525                  // same size
 526                  return false;
 527              }
 528          } else {
 529              if (!empty($id) && ( isset($value) || $value != "")) { 
 530                  $sql .= " WHERE $id = '$value'";
 531              }
 532          }
 533  
 534          $this->dbQuery($sql);
 535          $this->dbDelete($tablefrom,$id,$value);
 536  
 537          if ($this->isVerbose()) {
 538              $this->_errorlog("\n*** Leaving database->dbCopy ***");
 539          }
 540  
 541      }
 542  
 543      /**
 544      * Retrieves the number of rows in a recordset
 545      *
 546      * This returns the number of rows in a recordset
 547      *
 548      * @param    object      $recordset      The recordset to operate one
 549      * @return   int         Returns number of rows otherwise false (0)
 550      *
 551      */
 552      function dbNumRows($recordset)
 553      {
 554          if ($this->isVerbose()) {
 555              $this->_errorlog("\n*** Inside database->dbNumRows ***");
 556          }
 557  
 558          // return only if recordset exists, otherwise 0
 559          if ($recordset) {
 560              if ($this->isVerbose()) {
 561                  $this->_errorlog('got ' . @mysql_numrows($recordset) . ' rows');
 562                  $this->_errorlog("\n*** Inside database->dbNumRows ***");
 563              }
 564              return @mysql_numrows($recordset);
 565          } else {
 566              if ($this->isVerbose()) {
 567                  $this->_errorlog("got no rows");
 568                  $this->_errorlog("\n*** Inside database->dbNumRows ***");
 569              }
 570              return 0;
 571          }
 572      }
 573  
 574      /**
 575      * Returns the contents of one cell from a MySQL result set
 576      *
 577      * @param    object      $recordset      The recordset to operate on
 578      * @param    int         $row            row to get data from
 579      * @param    string      $field          field to return
 580      * @return   (depends on field content)
 581      *
 582      */
 583      function dbResult($recordset,$row,$field=0)
 584      {
 585          if ($this->isVerbose()) {
 586              $this->_errorlog("\n*** Inside database->dbResult ***");
 587              if (empty($recordset)) {
 588                  $this->_errorlog("\n*** Passed recordset isn't valid ***");
 589              } else {
 590                  $this->_errorlog("\n*** Everything looks good ***");
 591              }
 592              $this->_errorlog("\n*** Leaving database->dbResult ***");
 593          }
 594          return @mysql_result($recordset,$row,$field);
 595      }
 596  
 597      /**
 598      * Retrieves the number of fields in a recordset
 599      *
 600      * This returns the number of fields in a recordset
 601      *
 602      * @param    object      $recordset      The recordset to operate on
 603      * @return   int     Returns number of rows from query
 604      *
 605      */
 606      function dbNumFields($recordset)
 607      {
 608          return @mysql_numfields($recordset);
 609      }
 610  
 611      /**
 612      * Retrieves returns the field name for a field
 613      *
 614      * Returns the field name for a given field number
 615      *
 616      * @param    object      $recordset      The recordset to operate on
 617      * @param    int         $fnumber        field number to return the name of
 618      * @return   string      Returns name of specified field
 619      *
 620      */
 621      function dbFieldName($recordset,$fnumber)
 622      {
 623          return @mysql_fieldname($recordset,$fnumber);
 624      }
 625  
 626      /**
 627      * Retrieves returns the number of effected rows for last query
 628      *
 629      * Retrieves returns the number of effected rows for last query
 630      *
 631      * @param    object      $recordset      The recordset to operate on
 632      * @return   int     Number of rows affected by last query
 633      *
 634      */
 635      function dbAffectedRows($recordset)
 636      {
 637          return @mysql_affected_rows();
 638      }
 639  
 640      /**
 641      * Retrieves record from a recordset
 642      *
 643      * Gets the next record in a recordset and returns in array
 644      *
 645      * @param    object      $recordset  The recordset to operate on
 646      * @param    boolean     $both       get both assoc and numeric indices
 647      * @return   array       Returns data array of current row from recordset
 648      *
 649      */
 650      function dbFetchArray($recordset, $both = false)
 651      {
 652          if ($both) {
 653              $result_type = MYSQL_BOTH;
 654          } else {
 655              $result_type = MYSQL_ASSOC;
 656          }
 657          return @mysql_fetch_array($recordset, $result_type);
 658      }
 659  
 660      /**
 661      * Returns the last ID inserted
 662      *
 663      * Returns the last auto_increment ID generated
 664      *
 665      * @param    resource    $link_identifier    identifier for opened link
 666      * @return   int                             Returns last auto-generated ID
 667      *
 668      */
 669      function dbInsertId($link_identifier = '')
 670      {
 671          if (empty($link_identifier)) {
 672              return @mysql_insert_id();
 673          } else {
 674              return @mysql_insert_id($link_identifier);
 675          }
 676      }
 677  
 678      /**
 679      * returns a database error string
 680      *
 681      * Returns an database error message
 682      *
 683      * @param    string      $sql    SQL that may have caused the error
 684      * @return   string      Text for error message
 685      *
 686      */
 687      function dbError($sql='')
 688      {
 689          if (mysql_errno()) {
 690              $this->_errorlog(@mysql_errno() . ': ' . @mysql_error() . ". SQL in question: $sql");        
 691              if ($this->_display_error) {
 692                  return  @mysql_errno() . ': ' . @mysql_error();
 693              } else {
 694                  return 'An SQL error has occurred. Please see error.log for details.';
 695              }
 696          }
 697  
 698          return;
 699      }
 700  
 701      /**
 702      * Lock a table
 703      *
 704      * Locks a table for write operations
 705      *
 706      * @param    string      $table      Table to lock
 707      * @return   void
 708      * @see dbUnlockTable
 709      *
 710      */
 711      function dbLockTable($table)
 712      {
 713          if ($this->isVerbose()) {
 714              $this->_errorlog("\n*** Inside database->dbLockTable ***");
 715          }
 716  
 717          $sql = "LOCK TABLES $table WRITE";
 718  
 719          $this->dbQuery($sql);
 720  
 721          if ($this->isVerbose()) {
 722              $this->_errorlog("\n*** Leaving database->dbLockTable ***");
 723          }
 724      }
 725  
 726      /**
 727      * Unlock a table
 728      *
 729      * Unlocks a table after a dbLockTable (actually, unlocks all tables)
 730      *
 731      * @param    string      $table      Table to unlock (ignored)
 732      * @return   void
 733      * @see dbLockTable
 734      *
 735      */
 736      function dbUnlockTable($table)
 737      {
 738          if ($this->isVerbose()) {
 739              $this->_errorlog("\n*** Inside database->dbUnlockTable ***");
 740          }
 741  
 742          $sql = 'UNLOCK TABLES';
 743  
 744          $this->dbQuery($sql);
 745  
 746          if ($this->isVerbose()) {
 747              $this->_errorlog("\n*** Leaving database->dbUnlockTable ***");
 748          }
 749      }
 750  }
 751  
 752  ?>


Généré le : Wed Nov 21 12:27:40 2007 par Balluche grâce à PHPXref 0.7
  Clicky Web Analytics