Documentation TYPO3 par Ameos

class.t3lib_db.php

00001 <?php
00002 /***************************************************************
00003 *  Copyright notice
00004 *
00005 *  (c) 2004 Kasper Skaarhoj (kasperYYYY@typo3.com)
00006 *  All rights reserved
00007 *
00008 *  This script is part of the TYPO3 project. The TYPO3 project is
00009 *  free software; you can redistribute it and/or modify
00010 *  it under the terms of the GNU General Public License as published by
00011 *  the Free Software Foundation; either version 2 of the License, or
00012 *  (at your option) any later version.
00013 *
00014 *  The GNU General Public License can be found at
00015 *  http://www.gnu.org/copyleft/gpl.html.
00016 *  A copy is found in the textfile GPL.txt and important notices to the license
00017 *  from the author is found in LICENSE.txt distributed with these scripts.
00018 *
00019 *
00020 *  This script is distributed in the hope that it will be useful,
00021 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
00022 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00023 *  GNU General Public License for more details.
00024 *
00025 *  This copyright notice MUST APPEAR in all copies of the script!
00026 ***************************************************************/
00132 class t3lib_DB {
00133 
00134 
00135                 // Debug:
00136         var $debugOutput = FALSE;                       // Set "TRUE" if you want database errors outputted.
00137         var $debug_lastBuiltQuery = '';         // Internally: Set to last built query (not necessarily executed...)
00138 
00139                 // Default link identifier:
00140         var $link;
00141 
00142 
00143 
00144 
00145         /************************************
00146          *
00147          * Query execution
00148          *
00149          * These functions are the RECOMMENDED DBAL functions for use in your applications
00150          * Using these functions will allow the DBAL to use alternative ways of accessing data (contrary to if a query is returned!)
00151          * They compile a query AND execute it immediately and then return the result
00152          * This principle heightens our ability to create various forms of DBAL of the functions.
00153          * Generally: We want to return a result pointer/object, never queries.
00154          * Also, having the table name together with the actual query execution allows us to direct the request to other databases.
00155          *
00156          **************************************/
00157 
00167         function exec_INSERTquery($table,$fields_values)        {
00168                 $res = mysql_query($this->INSERTquery($table,$fields_values), $this->link);
00169                 if ($this->debugOutput) $this->debug('exec_INSERTquery');
00170                 return $res;
00171         }
00172 
00183         function exec_UPDATEquery($table,$where,$fields_values) {
00184                 $res = mysql_query($this->UPDATEquery($table,$where,$fields_values), $this->link);
00185                 if ($this->debugOutput) $this->debug('exec_UPDATEquery');
00186                 return $res;
00187         }
00188 
00197         function exec_DELETEquery($table,$where)        {
00198                 $res = mysql_query($this->DELETEquery($table,$where), $this->link);
00199                 if ($this->debugOutput) $this->debug('exec_DELETEquery');
00200                 return $res;
00201         }
00202 
00216         function exec_SELECTquery($select_fields,$from_table,$where_clause,$groupBy='',$orderBy='',$limit='')   {
00217                 $res = mysql_query($this->SELECTquery($select_fields,$from_table,$where_clause,$groupBy,$orderBy,$limit), $this->link);
00218                 if ($this->debugOutput) $this->debug('exec_SELECTquery');
00219                 return $res;
00220         }
00221 
00241         function exec_SELECT_mm_query($select,$local_table,$mm_table,$foreign_table,$whereClause='',$groupBy='',$orderBy='',$limit='')  {
00242                 $mmWhere = $local_table ? $local_table.'.uid='.$mm_table.'.uid_local' : '';
00243                 $mmWhere.= ($local_table AND $foreign_table) ? ' AND ' : '';
00244                 $mmWhere.= $foreign_table ? $foreign_table.'.uid='.$mm_table.'.uid_foreign' : '';
00245                 return $GLOBALS['TYPO3_DB']->exec_SELECTquery(
00246                                         $select,
00247                                         ($local_table ? $local_table.',' : '').$mm_table.($foreign_table ? ','.$foreign_table : ''),
00248                                         $mmWhere.' '.$whereClause,              // whereClauseMightContainGroupOrderBy
00249                                         $groupBy,
00250                                         $orderBy,
00251                                         $limit
00252                                 );
00253         }
00254 
00264         function exec_SELECT_queryArray($queryParts)    {
00265                 return $this->exec_SELECTquery(
00266                                         $queryParts['SELECT'],
00267                                         $queryParts['FROM'],
00268                                         $queryParts['WHERE'],
00269                                         $queryParts['GROUPBY'],
00270                                         $queryParts['ORDERBY'],
00271                                         $queryParts['LIMIT']
00272                                 );
00273         }
00274 
00287         function exec_SELECTgetRows($select_fields,$from_table,$where_clause,$groupBy='',$orderBy='',$limit='',$uidIndexField='')       {
00288                 $res = mysql_query($this->SELECTquery($select_fields,$from_table,$where_clause,$groupBy,$orderBy,$limit), $this->link);
00289                 if ($this->debugOutput) $this->debug('exec_SELECTquery');
00290 
00291                 unset($output);
00292                 if (!$this->sql_error())        {
00293                         $output = array();
00294 
00295                         if ($uidIndexField)     {
00296                                 while($tempRow = $this->sql_fetch_assoc($res))  {
00297                                         $output[$tempRow[$uidIndexField]] = $tempRow;
00298                                 }
00299                         } else {
00300                                 while($output[] = $this->sql_fetch_assoc($res));
00301                                 array_pop($output);
00302                         }
00303                 }
00304                 return $output;
00305         }
00306 
00307 
00308 
00309 
00310 
00311 
00312 
00313 
00314 
00315 
00316 
00317         /**************************************
00318          *
00319          * Query building
00320          *
00321          **************************************/
00322 
00332         function INSERTquery($table,$fields_values)     {
00333 
00334                         // Table and fieldnames should be "SQL-injection-safe" when supplied to this function (contrary to values in the arrays which may be insecure).
00335                 if (is_array($fields_values) && count($fields_values))  {
00336 
00337                                 // Add slashes old-school:
00338                         foreach($fields_values as $k => $v)     {
00339                                 $fields_values[$k] = $this->quoteStr($fields_values[$k], $table);
00340                         }
00341 
00342                                 // Build query:
00343                         $query = 'INSERT INTO '.$table.'
00344                                 (
00345                                         '.implode(',
00346                                         ',array_keys($fields_values)).'
00347                                 ) VALUES (
00348                                         "'.implode('",
00349                                         "',$fields_values).'"
00350                                 )';
00351 
00352                                 // Return query:
00353                         if ($this->debugOutput) $this->debug_lastBuiltQuery = $query;
00354                         return $query;
00355                 }
00356         }
00357 
00368         function UPDATEquery($table,$where,$fields_values)      {
00369 
00370                         // Table and fieldnames should be "SQL-injection-safe" when supplied to this function (contrary to values in the arrays which may be insecure).
00371                 if (is_string($where))  {
00372                         if (is_array($fields_values) && count($fields_values))  {
00373 
00374                                         // Add slashes old-school:
00375                                 $nArr = array();
00376                                 foreach($fields_values as $k => $v)     {
00377                                         $nArr[] = $k.'="'.$this->quoteStr($v, $table).'"';
00378                                 }
00379 
00380                                         // Build query:
00381                                 $query = 'UPDATE '.$table.'
00382                                         SET
00383                                                 '.implode(',
00384                                                 ',$nArr).
00385                                         (strlen($where)>0 ? '
00386                                         WHERE
00387                                                 '.$where : '');
00388 
00389                                         // Return query:
00390                                 if ($this->debugOutput) $this->debug_lastBuiltQuery = $query;
00391                                 return $query;
00392                         }
00393                 } else {
00394                         die('<strong>TYPO3 Fatal Error:</strong> "Where" clause argument for UPDATE query was not a string in $this->UPDATEquery() !');
00395                 }
00396         }
00397 
00407         function DELETEquery($table,$where)     {
00408                 if (is_string($where))  {
00409 
00410                                 // Table and fieldnames should be "SQL-injection-safe" when supplied to this function
00411                         $query = 'DELETE FROM '.$table.
00412                                 (strlen($where)>0 ? '
00413                                 WHERE
00414                                         '.$where : '');
00415 
00416                         if ($this->debugOutput) $this->debug_lastBuiltQuery = $query;
00417                         return $query;
00418                 } else {
00419                         die('<strong>TYPO3 Fatal Error:</strong> "Where" clause argument for DELETE query was not a string in $this->DELETEquery() !');
00420                 }
00421         }
00422 
00436         function SELECTquery($select_fields,$from_table,$where_clause,$groupBy='',$orderBy='',$limit='')        {
00437 
00438                         // Table and fieldnames should be "SQL-injection-safe" when supplied to this function
00439                         // Build basic query:
00440                 $query = 'SELECT '.$select_fields.'
00441                         FROM '.$from_table.
00442                         (strlen($where_clause)>0 ? '
00443                         WHERE
00444                                 '.$where_clause : '');
00445 
00446                         // Group by:
00447                 if (strlen($groupBy)>0) {
00448                         $query.= '
00449                         GROUP BY '.$groupBy;
00450                 }
00451                         // Order by:
00452                 if (strlen($orderBy)>0) {
00453                         $query.= '
00454                         ORDER BY '.$orderBy;
00455                 }
00456                         // Group by:
00457                 if (strlen($limit)>0)   {
00458                         $query.= '
00459                         LIMIT '.$limit;
00460                 }
00461 
00462                         // Return query:
00463                 if ($this->debugOutput) $this->debug_lastBuiltQuery = $query;
00464                 return $query;
00465         }
00466 
00477         function listQuery($field, $value, $table)      {
00478                 $command = $this->quoteStr($value, $table);
00479                 $where = '('.$field.' LIKE "%,'.$command.',%" OR '.$field.' LIKE "'.$command.',%" OR '.$field.' LIKE "%,'.$command.'" OR '.$field.'="'.$command.'")';
00480                 return $where;
00481         }
00482 
00491         function searchQuery($searchWords,$fields,$table)       {
00492                 $queryParts = array();
00493 
00494                 foreach($searchWords as $sw)    {
00495                         $like=' LIKE "%'.$this->quoteStr($sw, $table).'%"';
00496                         $queryParts[] = $table.'.'.implode($like.' OR '.$table.'.',$fields).$like;
00497                 }
00498                 $query = '('.implode(') AND (',$queryParts).')';
00499                 return $query ;
00500         }
00501 
00502 
00503 
00504 
00505 
00506 
00507 
00508 
00509 
00510 
00511 
00512 
00513 
00514 
00515 
00516 
00517         /**************************************
00518          *
00519          * Various helper functions
00520          *
00521          * Functions recommended to be used for
00522          * - escaping values,
00523          * - cleaning lists of values,
00524          * - stripping of excess ORDER BY/GROUP BY keywords
00525          *
00526          **************************************/
00527 
00537         function quoteStr($str, $table) {
00538                 return addslashes($str);
00539         }
00540 
00550         function cleanIntArray($arr)    {
00551                 foreach($arr as $k => $v)       {
00552                         $arr[$k] = intval($arr[$k]);
00553                 }
00554                 return $arr;
00555         }
00556 
00566         function cleanIntList($list)    {
00567                 return implode(',',t3lib_div::intExplode(',',$list));
00568         }
00569 
00580         function stripOrderBy($str)     {
00581                 return eregi_replace('^ORDER[[:space:]]+BY[[:space:]]+','',trim($str));
00582         }
00583 
00594         function stripGroupBy($str)     {
00595                 return eregi_replace('^GROUP[[:space:]]+BY[[:space:]]+','',trim($str));
00596         }
00597 
00606         function splitGroupOrderLimit($str)     {
00607                 $str = ' '.$str;        // Prepending a space to make sure "[[:space:]]+" will find a space there for the first element.
00608                         // Init output array:
00609                 $wgolParts = array(
00610                         'WHERE' => '',
00611                         'GROUPBY' => '',
00612                         'ORDERBY' => '',
00613                         'LIMIT' => ''
00614                 );
00615 
00616                         // Find LIMIT:
00617                 if (eregi('^(.*)[[:space:]]+LIMIT[[:space:]]+([[:alnum:][:space:],._]+)$',$str,$reg))   {
00618                         $wgolParts['LIMIT'] = trim($reg[2]);
00619                         $str = $reg[1];
00620                 }
00621 
00622                         // Find ORDER BY:
00623                 if (eregi('^(.*)[[:space:]]+ORDER[[:space:]]+BY[[:space:]]+([[:alnum:][:space:],._]+)$',$str,$reg))     {
00624                         $wgolParts['ORDERBY'] = trim($reg[2]);
00625                         $str = $reg[1];
00626                 }
00627 
00628                         // Find GROUP BY:
00629                 if (eregi('^(.*)[[:space:]]+GROUP[[:space:]]+BY[[:space:]]+([[:alnum:][:space:],._]+)$',$str,$reg))     {
00630                         $wgolParts['GROUPBY'] = trim($reg[2]);
00631                         $str = $reg[1];
00632                 }
00633 
00634                         // Rest is assumed to be "WHERE" clause:
00635                 $wgolParts['WHERE'] = $str;
00636 
00637                 return $wgolParts;
00638         }
00639 
00640 
00641 
00642 
00643 
00644 
00645 
00646 
00647 
00648 
00649 
00650 
00651 
00652 
00653 
00654         /**************************************
00655          *
00656          * MySQL wrapper functions
00657          * (For use in your applications)
00658          *
00659          **************************************/
00660 
00671         function sql($db,$query)        {
00672                 $res = mysql_query($query, $this->link);
00673                 if ($this->debugOutput) $this->debug('sql');
00674                 return $res;
00675         }
00676 
00685         function sql_query($query)      {
00686                 $res = mysql_query($query, $this->link);
00687                 if ($this->debugOutput) $this->debug('sql_query');
00688                 return $res;
00689         }
00690 
00698         function sql_error()    {
00699                 return mysql_error($this->link);
00700         }
00701 
00710         function sql_num_rows($res)     {
00711                 return mysql_num_rows($res);
00712         }
00713 
00722         function sql_fetch_assoc($res)  {
00723                 return mysql_fetch_assoc($res);
00724         }
00725 
00735         function sql_fetch_row($res)    {
00736                 return mysql_fetch_row($res);
00737         }
00738 
00747         function sql_free_result($res)  {
00748                 return mysql_free_result($res);
00749         }
00750 
00758         function sql_insert_id()        {
00759                 return mysql_insert_id($this->link);
00760         }
00761 
00769         function sql_affected_rows()    {
00770                 return mysql_affected_rows($this->link);
00771         }
00772 
00782         function sql_data_seek($res,$seek)      {
00783                 return mysql_data_seek($res,$seek);
00784         }
00785 
00795         function sql_field_type($res,$pointer)  {
00796                 return mysql_field_type($res,$pointer);
00797         }
00798 
00809         function sql_pconnect($TYPO3_db_host, $TYPO3_db_username, $TYPO3_db_password)   {
00810                 if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['no_pconnect'])  {
00811                         $this->link = mysql_connect($TYPO3_db_host, $TYPO3_db_username, $TYPO3_db_password);
00812                 } else {
00813                         $this->link = mysql_pconnect($TYPO3_db_host, $TYPO3_db_username, $TYPO3_db_password);
00814                 }
00815                 return $this->link;
00816         }
00817 
00826         function sql_select_db($TYPO3_db)       {
00827                 return mysql_select_db($TYPO3_db, $this->link);
00828         }
00829 
00830 
00831 
00832 
00833 
00834 
00835 
00836 
00837 
00838 
00839         /**************************************
00840          *
00841          * SQL admin functions
00842          * (For use in the Install Tool and Extension Manager)
00843          *
00844          **************************************/
00845 
00854         function admin_get_dbs()        {
00855                 $dbArr = array();
00856                 $db_list = mysql_list_dbs($this->link);
00857                 while ($row = mysql_fetch_object($db_list)) {
00858                         if ($this->sql_select_db($row->Database))       {
00859                                 $dbArr[] = $row->Database;
00860                         }
00861                 }
00862                 return $dbArr;
00863         }
00864 
00872         function admin_get_tables()     {
00873                 $whichTables = array();
00874                 $tables_result = mysql_list_tables(TYPO3_db, $this->link);
00875                 if (!mysql_error())     {
00876                         while ($theTable = mysql_fetch_assoc($tables_result)) {
00877                                 $whichTables[current($theTable)] = current($theTable);
00878                         }
00879                 }
00880                 return $whichTables;
00881         }
00882 
00891         function admin_get_fields($tableName)   {
00892                 $output = array();
00893 
00894                 $columns_res = mysql_query('SHOW columns FROM '.$tableName, $this->link);
00895                 while($fieldRow = mysql_fetch_assoc($columns_res))      {
00896                         $output[$fieldRow["Field"]] = $fieldRow;
00897                 }
00898 
00899                 return $output;
00900         }
00901 
00909         function admin_get_keys($tableName)     {
00910                 $output = array();
00911 
00912                 $keyRes = mysql_query('SHOW keys FROM '.$tableName, $this->link);
00913                 while($keyRow = mysql_fetch_assoc($keyRes))     {
00914                         $output[] = $keyRow;
00915                 }
00916 
00917                 return $output;
00918         }
00919 
00927         function admin_query($query)    {
00928                 $res = mysql_query($query, $this->link);
00929                 if ($this->debugOutput) $this->debug('admin_query');
00930                 return $res;
00931         }
00932 
00933 
00934 
00935 
00936 
00937 
00938 
00939 
00940 
00941 
00942         /******************************
00943          *
00944          * Debugging
00945          *
00946          ******************************/
00947 
00954         function debug($func)   {
00955 
00956                 $error = $this->sql_error();
00957                 if ($error)             {
00958                         echo t3lib_div::view_array(array(
00959                                 'caller' => 't3lib_DB::'.$func,
00960                                 'ERROR' => $error,
00961                                 'lastBuiltQuery' => $this->debug_lastBuiltQuery,
00962                                 'debug_backtrace' => function_exists('debug_backtrace') ? next(debug_backtrace()) : 'N/A'
00963                         ));
00964                 }
00965         }
00966 }
00967 
00968 
00969 if (defined('TYPO3_MODE') && $TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['t3lib/class.t3lib_db.php'])        {
00970         include_once($TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['t3lib/class.t3lib_db.php']);
00971 }
00972 ?>


Généré par Le spécialiste TYPO3 avec  doxygen 1.4.6