* Added Karsten D.s patches for DBAL.
[Packages/TYPO3.CMS.git] / t3lib / class.t3lib_db.php
1 <?php
2 /***************************************************************
3 * Copyright notice
4 *
5 * (c) 2004 Kasper Skaarhoj (kasperYYYY@typo3.com)
6 * All rights reserved
7 *
8 * This script is part of the TYPO3 project. The TYPO3 project is
9 * free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
13 *
14 * The GNU General Public License can be found at
15 * http://www.gnu.org/copyleft/gpl.html.
16 * A copy is found in the textfile GPL.txt and important notices to the license
17 * from the author is found in LICENSE.txt distributed with these scripts.
18 *
19 *
20 * This script is distributed in the hope that it will be useful,
21 * but WITHOUT ANY WARRANTY; without even the implied warranty of
22 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
23 * GNU General Public License for more details.
24 *
25 * This copyright notice MUST APPEAR in all copies of the script!
26 ***************************************************************/
27 /**
28 * Contains the class "t3lib_db" containing functions for building SQL queries and mysql wrappers, thus providing a foundational API to all database interaction.
29 * This class is instantiated globally as $TYPO3_DB in TYPO3 scripts.
30 *
31 * $Id$
32 *
33 * @author Kasper Skaarhoj <kasperYYYY@typo3.com>
34 */
35 /**
36 * [CLASS/FUNCTION INDEX of SCRIPT]
37 *
38 *
39 *
40 * 132: class t3lib_DB
41 *
42 * SECTION: Query execution
43 * 167: function exec_INSERTquery($table,$fields_values)
44 * 183: function exec_UPDATEquery($table,$where,$fields_values)
45 * 197: function exec_DELETEquery($table,$where)
46 * 216: function exec_SELECTquery($select_fields,$from_table,$where_clause,$groupBy='',$orderBy='',$limit='')
47 * 241: function exec_SELECT_mm_query($select,$local_table,$mm_table,$foreign_table,$whereClause='',$groupBy='',$orderBy='',$limit='')
48 * 264: function exec_SELECT_queryArray($queryParts)
49 * 287: function exec_SELECTgetRows($select_fields,$from_table,$where_clause,$groupBy='',$orderBy='',$limit='',$uidIndexField='')
50 *
51 * SECTION: Query building
52 * 332: function INSERTquery($table,$fields_values)
53 * 368: function UPDATEquery($table,$where,$fields_values)
54 * 407: function DELETEquery($table,$where)
55 * 436: function SELECTquery($select_fields,$from_table,$where_clause,$groupBy='',$orderBy='',$limit='')
56 * 477: function listQuery($field, $value, $table)
57 * 491: function searchQuery($searchWords,$fields,$table)
58 *
59 * SECTION: Various helper functions
60 * 537: function quoteStr($str, $table)
61 * 550: function cleanIntArray($arr)
62 * 566: function cleanIntList($list)
63 * 580: function stripOrderBy($str)
64 * 594: function stripGroupBy($str)
65 * 606: function splitGroupOrderLimit($str)
66 *
67 * SECTION: MySQL wrapper functions
68 * 671: function sql($db,$query)
69 * 685: function sql_query($query)
70 * 698: function sql_error()
71 * 710: function sql_num_rows($res)
72 * 722: function sql_fetch_assoc($res)
73 * 735: function sql_fetch_row($res)
74 * 747: function sql_free_result($res)
75 * 758: function sql_insert_id()
76 * 769: function sql_affected_rows()
77 * 782: function sql_data_seek($res,$seek)
78 * 795: function sql_field_type($res,$pointer)
79 * 809: function sql_pconnect($TYPO3_db_host, $TYPO3_db_username, $TYPO3_db_password)
80 * 826: function sql_select_db($TYPO3_db)
81 *
82 * SECTION: SQL admin functions
83 * 854: function admin_get_dbs()
84 * 872: function admin_get_tables()
85 * 891: function admin_get_fields($tableName)
86 * 909: function admin_get_keys($tableName)
87 * 927: function admin_query($query)
88 *
89 * SECTION: Debugging
90 * 954: function debug($func)
91 *
92 * TOTAL FUNCTIONS: 38
93 * (This index is automatically created/updated by the extension "extdeveval")
94 *
95 */
96
97
98
99
100
101
102
103
104
105
106
107
108 /**
109 * TYPO3 "database wrapper" class (new in 3.6.0)
110 * This class contains
111 * - abstraction functions for executing INSERT/UPDATE/DELETE/SELECT queries ("Query execution"; These are REQUIRED for all future connectivity to the database, thus ensuring DBAL compliance!)
112 * - functions for building SQL queries (INSERT/UPDATE/DELETE/SELECT) ("Query building"); These are transitional functions for building SQL queries in a more automated way. Use these to build queries instead of doing it manually in your code!
113 * - mysql() wrapper functions; These are transitional functions. By a simple search/replace you should be able to substitute all mysql*() calls with $GLOBALS['TYPO3_DB']->sql*() and your application will work out of the box. YOU CANNOT (legally) use any mysql functions not found as wrapper functions in this class!
114 * See the Project Coding Guidelines (doc_core_cgl) for more instructions on best-practise
115 *
116 * This class is not in itself a complete database abstraction layer but can be extended to be a DBAL (by extensions, see "dbal" for example)
117 * ALL connectivity to the database in TYPO3 must be done through this class!
118 * The points of this class are:
119 * - To direct all database calls through this class so it becomes possible to implement DBAL with extensions.
120 * - To keep it very easy to use for developers used to MySQL in PHP - and preserve as much performance as possible when TYPO3 is used with MySQL directly...
121 * - To create an interface for DBAL implemented by extensions; (Eg. making possible escaping characters, clob/blob handling, reserved words handling)
122 * - Benchmarking the DB bottleneck queries will become much easier; Will make it easier to find optimization possibilities.
123 *
124 * USE:
125 * In all TYPO3 scripts the global variable $TYPO3_DB is an instance of this class. Use that.
126 * Eg. $GLOBALS['TYPO3_DB']->sql_fetch_assoc()
127 *
128 * @author Kasper Skaarhoj <kasperYYYY@typo3.com>
129 * @package TYPO3
130 * @subpackage t3lib
131 */
132 class t3lib_DB {
133
134
135 // Debug:
136 var $debugOutput = FALSE; // Set "TRUE" if you want database errors outputted.
137 var $debug_lastBuiltQuery = ''; // Internally: Set to last built query (not necessarily executed...)
138
139 // Default link identifier:
140 var $link;
141
142
143
144
145 /************************************
146 *
147 * Query execution
148 *
149 * These functions are the RECOMMENDED DBAL functions for use in your applications
150 * Using these functions will allow the DBAL to use alternative ways of accessing data (contrary to if a query is returned!)
151 * They compile a query AND execute it immediately and then return the result
152 * This principle heightens our ability to create various forms of DBAL of the functions.
153 * Generally: We want to return a result pointer/object, never queries.
154 * Also, having the table name together with the actual query execution allows us to direct the request to other databases.
155 *
156 **************************************/
157
158 /**
159 * Creates and executes an INSERT SQL-statement for $table from the array with field/value pairs $fields_values.
160 * Using this function specifically allows us to handle BLOB and CLOB fields depending on DB
161 * Usage count/core: 47
162 *
163 * @param string Table name
164 * @param array Field values as key=>value pairs. Values will be escaped internally. Typically you would fill an array like "$insertFields" with 'fieldname'=>'value' and pass it to this function as argument.
165 * @return pointer MySQL result pointer / DBAL object
166 */
167 function exec_INSERTquery($table,$fields_values) {
168 $res = mysql_query($this->INSERTquery($table,$fields_values), $this->link);
169 if ($this->debugOutput) $this->debug('exec_INSERTquery');
170 return $res;
171 }
172
173 /**
174 * Creates and executes an UPDATE SQL-statement for $table where $where-clause (typ. 'uid=...') from the array with field/value pairs $fields_values.
175 * Using this function specifically allow us to handle BLOB and CLOB fields depending on DB
176 * Usage count/core: 50
177 *
178 * @param string Database tablename
179 * @param string WHERE clause, eg. "uid=1". NOTICE: You must escape values in this argument with $this->fullQuoteStr() yourself!
180 * @param array Field values as key=>value pairs. Values will be escaped internally. Typically you would fill an array like "$updateFields" with 'fieldname'=>'value' and pass it to this function as argument.
181 * @return pointer MySQL result pointer / DBAL object
182 */
183 function exec_UPDATEquery($table,$where,$fields_values) {
184 $res = mysql_query($this->UPDATEquery($table,$where,$fields_values), $this->link);
185 if ($this->debugOutput) $this->debug('exec_UPDATEquery');
186 return $res;
187 }
188
189 /**
190 * Creates and executes a DELETE SQL-statement for $table where $where-clause
191 * Usage count/core: 40
192 *
193 * @param string Database tablename
194 * @param string WHERE clause, eg. "uid=1". NOTICE: You must escape values in this argument with $this->fullQuoteStr() yourself!
195 * @return pointer MySQL result pointer / DBAL object
196 */
197 function exec_DELETEquery($table,$where) {
198 $res = mysql_query($this->DELETEquery($table,$where), $this->link);
199 if ($this->debugOutput) $this->debug('exec_DELETEquery');
200 return $res;
201 }
202
203 /**
204 * Creates and executes a SELECT SQL-statement
205 * Using this function specifically allow us to handle the LIMIT feature independently of DB.
206 * Usage count/core: 340
207 *
208 * @param string List of fields to select from the table. This is what comes right after "SELECT ...". Required value.
209 * @param string Table(s) from which to select. This is what comes right after "FROM ...". Required value.
210 * @param string Optional additional WHERE clauses put in the end of the query. NOTICE: You must escape values in this argument with $this->fullQuoteStr() yourself! DO NOT PUT IN GROUP BY, ORDER BY or LIMIT!
211 * @param string Optional GROUP BY field(s), if none, supply blank string.
212 * @param string Optional ORDER BY field(s), if none, supply blank string.
213 * @param string Optional LIMIT value ([begin,]max), if none, supply blank string.
214 * @return pointer MySQL result pointer / DBAL object
215 */
216 function exec_SELECTquery($select_fields,$from_table,$where_clause,$groupBy='',$orderBy='',$limit='') {
217 $res = mysql_query($this->SELECTquery($select_fields,$from_table,$where_clause,$groupBy,$orderBy,$limit), $this->link);
218 if ($this->debugOutput) $this->debug('exec_SELECTquery');
219 return $res;
220 }
221
222 /**
223 * Creates and executes a SELECT query, selecting fields ($select) from two/three tables joined
224 * Use $mm_table together with $local_table or $foreign_table to select over two tables. Or use all three tables to select the full MM-relation.
225 * The JOIN is done with [$local_table].uid <--> [$mm_table].uid_local / [$mm_table].uid_foreign <--> [$foreign_table].uid
226 * The function is very useful for selecting MM-relations between tables adhering to the MM-format used by TCE (TYPO3 Core Engine). See the section on $TCA in Inside TYPO3 for more details.
227 *
228 * Usage: 12 (spec. ext. sys_action, sys_messages, sys_todos)
229 *
230 * @param string Field list for SELECT
231 * @param string Tablename, local table
232 * @param string Tablename, relation table
233 * @param string Tablename, foreign table
234 * @param string Optional additional WHERE clauses put in the end of the query. NOTICE: You must escape values in this argument with $this->fullQuoteStr() yourself! DO NOT PUT IN GROUP BY, ORDER BY or LIMIT!
235 * @param string Optional GROUP BY field(s), if none, supply blank string.
236 * @param string Optional ORDER BY field(s), if none, supply blank string.
237 * @param string Optional LIMIT value ([begin,]max), if none, supply blank string.
238 * @return pointer MySQL result pointer / DBAL object
239 * @see exec_SELECTquery()
240 */
241 function exec_SELECT_mm_query($select,$local_table,$mm_table,$foreign_table,$whereClause='',$groupBy='',$orderBy='',$limit='') {
242 $mmWhere = $local_table ? $local_table.'.uid='.$mm_table.'.uid_local' : '';
243 $mmWhere.= ($local_table AND $foreign_table) ? ' AND ' : '';
244 $mmWhere.= $foreign_table ? $foreign_table.'.uid='.$mm_table.'.uid_foreign' : '';
245 return $GLOBALS['TYPO3_DB']->exec_SELECTquery(
246 $select,
247 ($local_table ? $local_table.',' : '').$mm_table.($foreign_table ? ','.$foreign_table : ''),
248 $mmWhere.' '.$whereClause, // whereClauseMightContainGroupOrderBy
249 $groupBy,
250 $orderBy,
251 $limit
252 );
253 }
254
255 /**
256 * Executes a select based on input query parts array
257 *
258 * Usage: 9
259 *
260 * @param array Query parts array
261 * @return pointer MySQL select result pointer / DBAL object
262 * @see exec_SELECTquery()
263 */
264 function exec_SELECT_queryArray($queryParts) {
265 return $this->exec_SELECTquery(
266 $queryParts['SELECT'],
267 $queryParts['FROM'],
268 $queryParts['WHERE'],
269 $queryParts['GROUPBY'],
270 $queryParts['ORDERBY'],
271 $queryParts['LIMIT']
272 );
273 }
274
275 /**
276 * Creates and executes a SELECT SQL-statement AND traverse result set and returns array with records in.
277 *
278 * @param string See exec_SELECTquery()
279 * @param string See exec_SELECTquery()
280 * @param string See exec_SELECTquery()
281 * @param string See exec_SELECTquery()
282 * @param string See exec_SELECTquery()
283 * @param string See exec_SELECTquery()
284 * @param string If set, the result array will carry this field names value as index. Requires that field to be selected of course!
285 * @return array Array of rows.
286 */
287 function exec_SELECTgetRows($select_fields,$from_table,$where_clause,$groupBy='',$orderBy='',$limit='',$uidIndexField='') {
288 $res = mysql_query($this->SELECTquery($select_fields,$from_table,$where_clause,$groupBy,$orderBy,$limit), $this->link);
289 if ($this->debugOutput) $this->debug('exec_SELECTquery');
290
291 unset($output);
292 if (!$this->sql_error()) {
293 $output = array();
294
295 if ($uidIndexField) {
296 while($tempRow = $this->sql_fetch_assoc($res)) {
297 $output[$tempRow[$uidIndexField]] = $tempRow;
298 }
299 } else {
300 while($output[] = $this->sql_fetch_assoc($res));
301 array_pop($output);
302 }
303 }
304 return $output;
305 }
306
307
308
309
310
311
312
313
314
315
316
317 /**************************************
318 *
319 * Query building
320 *
321 **************************************/
322
323 /**
324 * Creates an INSERT SQL-statement for $table from the array with field/value pairs $fields_values.
325 * Usage count/core: 4
326 *
327 * @param string See exec_INSERTquery()
328 * @param array See exec_INSERTquery()
329 * @return string Full SQL query for INSERT (unless $fields_values does not contain any elements in which case it will be false)
330 * @depreciated use exec_INSERTquery() instead if possible!
331 */
332 function INSERTquery($table,$fields_values) {
333
334 // Table and fieldnames should be "SQL-injection-safe" when supplied to this function (contrary to values in the arrays which may be insecure).
335 if (is_array($fields_values) && count($fields_values)) {
336
337 // Add slashes old-school:
338 foreach($fields_values as $k => $v) {
339 $fields_values[$k] = $this->fullQuoteStr($fields_values[$k], $table);
340 }
341
342 // Build query:
343 $query = 'INSERT INTO '.$table.'
344 (
345 '.implode(',
346 ',array_keys($fields_values)).'
347 ) VALUES (
348 '.implode(',
349 ',$fields_values).'
350 )';
351
352 // Return query:
353 if ($this->debugOutput) $this->debug_lastBuiltQuery = $query;
354 return $query;
355 }
356 }
357
358 /**
359 * Creates an UPDATE SQL-statement for $table where $where-clause (typ. 'uid=...') from the array with field/value pairs $fields_values.
360 * Usage count/core: 6
361 *
362 * @param string See exec_UPDATEquery()
363 * @param string See exec_UPDATEquery()
364 * @param array See exec_UPDATEquery()
365 * @return string Full SQL query for UPDATE (unless $fields_values does not contain any elements in which case it will be false)
366 * @depreciated use exec_UPDATEquery() instead if possible!
367 */
368 function UPDATEquery($table,$where,$fields_values) {
369
370 // Table and fieldnames should be "SQL-injection-safe" when supplied to this function (contrary to values in the arrays which may be insecure).
371 if (is_string($where)) {
372 if (is_array($fields_values) && count($fields_values)) {
373
374 // Add slashes old-school:
375 $nArr = array();
376 foreach($fields_values as $k => $v) {
377 $nArr[] = $k.'='.$this->fullQuoteStr($v, $table);
378 }
379
380 // Build query:
381 $query = 'UPDATE '.$table.'
382 SET
383 '.implode(',
384 ',$nArr).
385 (strlen($where)>0 ? '
386 WHERE
387 '.$where : '');
388
389 // Return query:
390 if ($this->debugOutput) $this->debug_lastBuiltQuery = $query;
391 return $query;
392 }
393 } else {
394 die('<strong>TYPO3 Fatal Error:</strong> "Where" clause argument for UPDATE query was not a string in $this->UPDATEquery() !');
395 }
396 }
397
398 /**
399 * Creates a DELETE SQL-statement for $table where $where-clause
400 * Usage count/core: 3
401 *
402 * @param string See exec_DELETEquery()
403 * @param string See exec_DELETEquery()
404 * @return string Full SQL query for DELETE
405 * @depreciated use exec_DELETEquery() instead if possible!
406 */
407 function DELETEquery($table,$where) {
408 if (is_string($where)) {
409
410 // Table and fieldnames should be "SQL-injection-safe" when supplied to this function
411 $query = 'DELETE FROM '.$table.
412 (strlen($where)>0 ? '
413 WHERE
414 '.$where : '');
415
416 if ($this->debugOutput) $this->debug_lastBuiltQuery = $query;
417 return $query;
418 } else {
419 die('<strong>TYPO3 Fatal Error:</strong> "Where" clause argument for DELETE query was not a string in $this->DELETEquery() !');
420 }
421 }
422
423 /**
424 * Creates a SELECT SQL-statement
425 * Usage count/core: 11
426 *
427 * @param string See exec_SELECTquery()
428 * @param string See exec_SELECTquery()
429 * @param string See exec_SELECTquery()
430 * @param string See exec_SELECTquery()
431 * @param string See exec_SELECTquery()
432 * @param string See exec_SELECTquery()
433 * @return string Full SQL query for SELECT
434 * @depreciated use exec_SELECTquery() instead if possible!
435 */
436 function SELECTquery($select_fields,$from_table,$where_clause,$groupBy='',$orderBy='',$limit='') {
437
438 // Table and fieldnames should be "SQL-injection-safe" when supplied to this function
439 // Build basic query:
440 $query = 'SELECT '.$select_fields.'
441 FROM '.$from_table.
442 (strlen($where_clause)>0 ? '
443 WHERE
444 '.$where_clause : '');
445
446 // Group by:
447 if (strlen($groupBy)>0) {
448 $query.= '
449 GROUP BY '.$groupBy;
450 }
451 // Order by:
452 if (strlen($orderBy)>0) {
453 $query.= '
454 ORDER BY '.$orderBy;
455 }
456 // Group by:
457 if (strlen($limit)>0) {
458 $query.= '
459 LIMIT '.$limit;
460 }
461
462 // Return query:
463 if ($this->debugOutput) $this->debug_lastBuiltQuery = $query;
464 return $query;
465 }
466
467 /**
468 * Returns a WHERE clause that can find a value ($value) in a list field ($field)
469 * For instance a record in the database might contain a list of numbers, "34,234,5" (with no spaces between). This query would be able to select that record based on the value "34", "234" or "5" regardless of their positioni in the list (left, middle or right).
470 * Is nice to look up list-relations to records or files in TYPO3 database tables.
471 *
472 * @param string Field name
473 * @param string Value to find in list
474 * @param string Table in which we are searching (for DBAL detection of quoteStr() method)
475 * @return string WHERE clause for a query
476 */
477 function listQuery($field, $value, $table) {
478 $command = $this->quoteStr($value, $table);
479 $where = '('.$field.' LIKE \'%,'.$command.',%\' OR '.$field.' LIKE \''.$command.',%\' OR '.$field.' LIKE \'%,'.$command.'\' OR '.$field.'=\''.$command.'\')';
480 return $where;
481 }
482
483 /**
484 * Returns a WHERE clause which will make an AND search for the words in the $searchWords array in any of the fields in array $fields.
485 *
486 * @param array Array of search words
487 * @param array Array of fields
488 * @param string Table in which we are searching (for DBAL detection of quoteStr() method)
489 * @return string WHERE clause for search
490 */
491 function searchQuery($searchWords,$fields,$table) {
492 $queryParts = array();
493
494 foreach($searchWords as $sw) {
495 $like=' LIKE \'%'.$this->quoteStr($sw, $table).'%\'';
496 $queryParts[] = $table.'.'.implode($like.' OR '.$table.'.',$fields).$like;
497 }
498 $query = '('.implode(') AND (',$queryParts).')';
499 return $query ;
500 }
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517 /**************************************
518 *
519 * Various helper functions
520 *
521 * Functions recommended to be used for
522 * - escaping values,
523 * - cleaning lists of values,
524 * - stripping of excess ORDER BY/GROUP BY keywords
525 *
526 **************************************/
527
528 /**
529 * Escaping and quoting values for SQL statements.
530 * Usage count/core: 100
531 *
532 * @param string Input string
533 * @param string Table name for which to quote string. Just enter the table that the field-value is selected from (and any DBAL will look up which handler to use and then how to quote the string!).
534 * @return string Output string; Wrapped in single quotes and quotes in the string (" / ') and \ will be backslashed (or otherwise based on DBAL handler)
535 * @see quoteStr()
536 */
537 function fullQuoteStr($str, $table) {
538 return '\''.addslashes($str).'\'';
539 }
540
541 /**
542 * Substitution for PHP function "addslashes()"
543 * Use this function instead of the PHP addslashes() function when you build queries - this will prepare your code for DBAL.
544 * NOTICE: You must wrap the output of this function in SINGLE QUOTES to be DBAL compatible. Unless you have to apply the single quotes yourself you should rather use ->fullQuoteStr()!
545 *
546 * Usage count/core: 20
547 *
548 * @param string Input string
549 * @param string Table name for which to quote string. Just enter the table that the field-value is selected from (and any DBAL will look up which handler to use and then how to quote the string!).
550 * @return string Output string; Quotes (" / ') and \ will be backslashed (or otherwise based on DBAL handler)
551 * @see quoteStr()
552 */
553 function quoteStr($str, $table) {
554 return addslashes($str);
555 }
556
557 /**
558 * Will convert all values in the one-dimentional array to integers.
559 * Useful when you want to make sure an array contains only integers before imploding them in a select-list.
560 * Usage count/core: 7
561 *
562 * @param array Array with values
563 * @return array The input array with all values passed through intval()
564 * @see cleanIntList()
565 */
566 function cleanIntArray($arr) {
567 foreach($arr as $k => $v) {
568 $arr[$k] = intval($arr[$k]);
569 }
570 return $arr;
571 }
572
573 /**
574 * Will force all entries in the input comma list to integers
575 * Useful when you want to make sure a commalist of supposed integers really contain only integers; You want to know that when you don't trust content that could go into an SQL statement.
576 * Usage count/core: 6
577 *
578 * @param string List of comma-separated values which should be integers
579 * @return string The input list but with every value passed through intval()
580 * @see cleanIntArray()
581 */
582 function cleanIntList($list) {
583 return implode(',',t3lib_div::intExplode(',',$list));
584 }
585
586 /**
587 * Removes the prefix "ORDER BY" from the input string.
588 * This function is used when you call the exec_SELECTquery() function and want to pass the ORDER BY parameter by can't guarantee that "ORDER BY" is not prefixed.
589 * Generally; This function provides a work-around to the situation where you cannot pass only the fields by which to order the result.
590 * Usage count/core: 11
591 *
592 * @param string eg. "ORDER BY title, uid"
593 * @return string eg. "title, uid"
594 * @see exec_SELECTquery(), stripGroupBy()
595 */
596 function stripOrderBy($str) {
597 return preg_replace('/^ORDER[[:space:]]+BY[[:space:]]+/i','',trim($str));
598 }
599
600 /**
601 * Removes the prefix "GROUP BY" from the input string.
602 * This function is used when you call the SELECTquery() function and want to pass the GROUP BY parameter by can't guarantee that "GROUP BY" is not prefixed.
603 * Generally; This function provides a work-around to the situation where you cannot pass only the fields by which to order the result.
604 * Usage count/core: 1
605 *
606 * @param string eg. "GROUP BY title, uid"
607 * @return string eg. "title, uid"
608 * @see exec_SELECTquery(), stripOrderBy()
609 */
610 function stripGroupBy($str) {
611 return preg_replace('/^GROUP[[:space:]]+BY[[:space:]]+/i','',trim($str));
612 }
613
614 /**
615 * Takes the last part of a query, eg. "... uid=123 GROUP BY title ORDER BY title LIMIT 5,2" and splits each part into a table (WHERE, GROUPBY, ORDERBY, LIMIT)
616 * Work-around function for use where you know some userdefined end to an SQL clause is supplied and you need to separate these factors.
617 * Usage count/core: 13
618 *
619 * @param string Input string
620 * @return array
621 */
622 function splitGroupOrderLimit($str) {
623 $str = ' '.$str; // Prepending a space to make sure "[[:space:]]+" will find a space there for the first element.
624 // Init output array:
625 $wgolParts = array(
626 'WHERE' => '',
627 'GROUPBY' => '',
628 'ORDERBY' => '',
629 'LIMIT' => ''
630 );
631
632 // Find LIMIT:
633 if (preg_match('/^(.*)[[:space:]]+LIMIT[[:space:]]+([[:alnum:][:space:],._]+)$/i',$str,$reg)) {
634 $wgolParts['LIMIT'] = trim($reg[2]);
635 $str = $reg[1];
636 }
637
638 // Find ORDER BY:
639 if (preg_match('/^(.*)[[:space:]]+ORDER[[:space:]]+BY[[:space:]]+([[:alnum:][:space:],._]+)$/i',$str,$reg)) {
640 $wgolParts['ORDERBY'] = trim($reg[2]);
641 $str = $reg[1];
642 }
643
644 // Find GROUP BY:
645 if (preg_match('/^(.*)[[:space:]]+GROUP[[:space:]]+BY[[:space:]]+([[:alnum:][:space:],._]+)$/i',$str,$reg)) {
646 $wgolParts['GROUPBY'] = trim($reg[2]);
647 $str = $reg[1];
648 }
649
650 // Rest is assumed to be "WHERE" clause:
651 $wgolParts['WHERE'] = $str;
652
653 return $wgolParts;
654 }
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670 /**************************************
671 *
672 * MySQL wrapper functions
673 * (For use in your applications)
674 *
675 **************************************/
676
677 /**
678 * Executes query
679 * mysql() wrapper function
680 * DEPRECIATED - use exec_* functions from this class instead!
681 * Usage count/core: 9
682 *
683 * @param string Database name
684 * @param string Query to execute
685 * @return pointer Result pointer / DBAL object
686 */
687 function sql($db,$query) {
688 $res = mysql_query($query, $this->link);
689 if ($this->debugOutput) $this->debug('sql');
690 return $res;
691 }
692
693 /**
694 * Executes query
695 * mysql_query() wrapper function
696 * Usage count/core: 1
697 *
698 * @param string Query to execute
699 * @return pointer Result pointer / DBAL object
700 */
701 function sql_query($query) {
702 $res = mysql_query($query, $this->link);
703 if ($this->debugOutput) $this->debug('sql_query');
704 return $res;
705 }
706
707 /**
708 * Returns the error status on the last sql() execution
709 * mysql_error() wrapper function
710 * Usage count/core: 32
711 *
712 * @return string MySQL error string.
713 */
714 function sql_error() {
715 return mysql_error($this->link);
716 }
717
718 /**
719 * Returns the number of selected rows.
720 * mysql_num_rows() wrapper function
721 * Usage count/core: 85
722 *
723 * @param pointer MySQL result pointer (of SELECT query) / DBAL object
724 * @return integer Number of resulting rows.
725 */
726 function sql_num_rows($res) {
727 return mysql_num_rows($res);
728 }
729
730 /**
731 * Returns an associative array that corresponds to the fetched row, or FALSE if there are no more rows.
732 * mysql_fetch_assoc() wrapper function
733 * Usage count/core: 307
734 *
735 * @param pointer MySQL result pointer (of SELECT query) / DBAL object
736 * @return array Associative array of result row.
737 */
738 function sql_fetch_assoc($res) {
739 return mysql_fetch_assoc($res);
740 }
741
742 /**
743 * Returns an array that corresponds to the fetched row, or FALSE if there are no more rows.
744 * The array contains the values in numerical indices.
745 * mysql_fetch_row() wrapper function
746 * Usage count/core: 56
747 *
748 * @param pointer MySQL result pointer (of SELECT query) / DBAL object
749 * @return array Array with result rows.
750 */
751 function sql_fetch_row($res) {
752 return mysql_fetch_row($res);
753 }
754
755 /**
756 * Free result memory
757 * mysql_free_result() wrapper function
758 * Usage count/core: 3
759 *
760 * @param pointer MySQL result pointer to free / DBAL object
761 * @return boolean Returns TRUE on success or FALSE on failure.
762 */
763 function sql_free_result($res) {
764 return mysql_free_result($res);
765 }
766
767 /**
768 * Get the ID generated from the previous INSERT operation
769 * mysql_insert_id() wrapper function
770 * Usage count/core: 13
771 *
772 * @return integer The uid of the last inserted record.
773 */
774 function sql_insert_id() {
775 return mysql_insert_id($this->link);
776 }
777
778 /**
779 * Returns the number of rows affected by the last INSERT, UPDATE or DELETE query
780 * mysql_affected_rows() wrapper function
781 * Usage count/core: 1
782 *
783 * @return integer Number of rows affected by last query
784 */
785 function sql_affected_rows() {
786 return mysql_affected_rows($this->link);
787 }
788
789 /**
790 * Move internal result pointer
791 * mysql_data_seek() wrapper function
792 * Usage count/core: 3
793 *
794 * @param pointer MySQL result pointer (of SELECT query) / DBAL object
795 * @param integer Seek result number.
796 * @return boolean Returns TRUE on success or FALSE on failure.
797 */
798 function sql_data_seek($res,$seek) {
799 return mysql_data_seek($res,$seek);
800 }
801
802 /**
803 * Get the type of the specified field in a result
804 * mysql_field_type() wrapper function
805 * Usage count/core: 2
806 *
807 * @param pointer MySQL result pointer (of SELECT query) / DBAL object
808 * @param integer Field index.
809 * @return string Returns the name of the specified field index
810 */
811 function sql_field_type($res,$pointer) {
812 return mysql_field_type($res,$pointer);
813 }
814
815 /**
816 * Open a (persistent) connection to a MySQL server
817 * mysql_pconnect() wrapper function
818 * Usage count/core: 12
819 *
820 * @param string Database host IP/domain
821 * @param string Username to connect with.
822 * @param string Password to connect with.
823 * @return pointer Returns a positive MySQL persistent link identifier on success, or FALSE on error.
824 */
825 function sql_pconnect($TYPO3_db_host, $TYPO3_db_username, $TYPO3_db_password) {
826 if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['no_pconnect']) {
827 $this->link = mysql_connect($TYPO3_db_host, $TYPO3_db_username, $TYPO3_db_password);
828 } else {
829 $this->link = mysql_pconnect($TYPO3_db_host, $TYPO3_db_username, $TYPO3_db_password);
830 }
831 return $this->link;
832 }
833
834 /**
835 * Select a MySQL database
836 * mysql_select_db() wrapper function
837 * Usage count/core: 8
838 *
839 * @param string Database to connect to.
840 * @return boolean Returns TRUE on success or FALSE on failure.
841 */
842 function sql_select_db($TYPO3_db) {
843 return mysql_select_db($TYPO3_db, $this->link);
844 }
845
846
847
848
849
850
851
852
853
854
855 /**************************************
856 *
857 * SQL admin functions
858 * (For use in the Install Tool and Extension Manager)
859 *
860 **************************************/
861
862 /**
863 * Listing databases from current MySQL connection. NOTICE: It WILL try to select those databases and thus break selection of current database.
864 * This is only used as a service function in the (1-2-3 process) of the Install Tool. In any case a lookup should be done in the _DEFAULT handler DBMS then.
865 * Use in Install Tool only!
866 * Usage count/core: 1
867 *
868 * @return array Each entry represents a database name
869 */
870 function admin_get_dbs() {
871 $dbArr = array();
872 $db_list = mysql_list_dbs($this->link);
873 while ($row = mysql_fetch_object($db_list)) {
874 if ($this->sql_select_db($row->Database)) {
875 $dbArr[] = $row->Database;
876 }
877 }
878 return $dbArr;
879 }
880
881 /**
882 * Returns the list of tables from the default database, TYPO3_db (quering the DBMS)
883 * In a DBAL this method should 1) look up all tables from the DBMS of the _DEFAULT handler and then 2) add all tables *configured* to be managed by other handlers
884 * Usage count/core: 2
885 *
886 * @return array Tables in an array (tablename is in both key and value)
887 */
888 function admin_get_tables() {
889 $whichTables = array();
890 $tables_result = mysql_list_tables(TYPO3_db, $this->link);
891 if (!mysql_error()) {
892 while ($theTable = mysql_fetch_assoc($tables_result)) {
893 $whichTables[current($theTable)] = current($theTable);
894 }
895 }
896 return $whichTables;
897 }
898
899 /**
900 * Returns information about each field in the $table (quering the DBMS)
901 * In a DBAL this should look up the right handler for the table and return compatible information
902 * This function is important not only for the Install Tool but probably for DBALs as well since they might need to look up table specific information in order to construct correct queries. In such cases this information should probably be cached for quick delivery
903 *
904 * @param string Table name
905 * @return array Field information in an associative array with fieldname => field row
906 */
907 function admin_get_fields($tableName) {
908 $output = array();
909
910 $columns_res = mysql_query('SHOW columns FROM '.$tableName, $this->link);
911 while($fieldRow = mysql_fetch_assoc($columns_res)) {
912 $output[$fieldRow["Field"]] = $fieldRow;
913 }
914
915 return $output;
916 }
917
918 /**
919 * Returns information about each index key in the $table (quering the DBMS)
920 * In a DBAL this should look up the right handler for the table and return compatible information
921 *
922 * @param string Table name
923 * @return array Key information in a numeric array
924 */
925 function admin_get_keys($tableName) {
926 $output = array();
927
928 $keyRes = mysql_query('SHOW keys FROM '.$tableName, $this->link);
929 while($keyRow = mysql_fetch_assoc($keyRes)) {
930 $output[] = $keyRow;
931 }
932
933 return $output;
934 }
935
936 /**
937 * mysql() wrapper function, used by the Install Tool and EM for all queries regarding management of the database!
938 * Usage count/core: 10
939 *
940 * @param string Query to execute
941 * @return pointer Result pointer
942 */
943 function admin_query($query) {
944 $res = mysql_query($query, $this->link);
945 if ($this->debugOutput) $this->debug('admin_query');
946 return $res;
947 }
948
949
950
951
952
953
954
955
956
957
958 /******************************
959 *
960 * Debugging
961 *
962 ******************************/
963
964 /**
965 * Debug function: Outputs error if any
966 *
967 * @param string Function calling debug()
968 * @return void
969 */
970 function debug($func) {
971
972 $error = $this->sql_error();
973 if ($error) {
974 echo t3lib_div::view_array(array(
975 'caller' => 't3lib_DB::'.$func,
976 'ERROR' => $error,
977 'lastBuiltQuery' => $this->debug_lastBuiltQuery,
978 'debug_backtrace' => function_exists('debug_backtrace') ? next(debug_backtrace()) : 'N/A'
979 ));
980 }
981 }
982 }
983
984
985 if (defined('TYPO3_MODE') && $TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['t3lib/class.t3lib_db.php']) {
986 include_once($TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['t3lib/class.t3lib_db.php']);
987 }
988 ?>