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