Support displaying in UTC (RFE #1440386).
[phpmyadmin/last10db.git] / libraries / database_interface.lib.php
blob157c917aaa1704dcbb24b277e5f3fb99dfcb3d5a
1 <?php
2 /* $Id$ */
3 // vim: expandtab sw=4 ts=4 sts=4:
5 /**
6 * Common Option Constants For DBI Functions
7 */
8 // PMA_DBI_try_query()
9 define('PMA_DBI_QUERY_STORE', 1); // Force STORE_RESULT method, ignored by classic MySQL.
10 define('PMA_DBI_QUERY_UNBUFFERED', 2); // Do not read whole query
11 // PMA_DBI_get_variable()
12 define('PMA_DBI_GETVAR_SESSION', 1);
13 define('PMA_DBI_GETVAR_GLOBAL', 2);
15 /**
16 * Loads the mysql extensions if it is not loaded yet
18 * @param string $extension mysql extension to load
20 function PMA_DBI_checkAndLoadMysqlExtension( $extension = 'mysql' ) {
21 if ( ! function_exists( $extension . '_connect' ) ) {
22 PMA_dl( $extension );
23 // check whether mysql is available
24 if ( ! function_exists( $extension . '_connect' ) ) {
25 return false;
29 return true;
33 /**
34 * check for requested extension
36 if ( ! PMA_DBI_checkAndLoadMysqlExtension( $GLOBALS['cfg']['Server']['extension'] ) ) {
38 // if it fails try alternative extension ...
39 // and display an error ...
41 /**
42 * @todo 2.7.1: add different messages for alternativ extension
43 * and complete fail (no alternativ extension too)
45 $GLOBALS['PMA_errors'][] =
46 sprintf( PMA_sanitize( $GLOBALS['strCantLoad'] ),
47 $GLOBALS['cfg']['Server']['extension'] )
48 .' - <a href="./Documentation.html#faqmysql" target="documentation">'
49 .$GLOBALS['strDocu'] . '</a>';
51 if ( $GLOBALS['cfg']['Server']['extension'] === 'mysql' ) {
52 $alternativ_extension = 'mysqli';
53 } else {
54 $alternativ_extension = 'mysql';
57 if ( ! PMA_DBI_checkAndLoadMysqlExtension( $alternativ_extension ) ) {
58 // if alternativ fails too ...
59 header( 'Location: error.php'
60 . '?lang=' . urlencode( $available_languages[$lang][2] )
61 . '&char=' . urlencode( $charset )
62 . '&dir=' . urlencode( $text_dir )
63 . '&type=' . urlencode( $strError )
64 . '&error=' . urlencode(
65 sprintf( $GLOBALS['strCantLoad'],
66 $GLOBALS['cfg']['Server']['extension'] )
67 .' - [a@./Documentation.html#faqmysql@documentation]'
68 .$GLOBALS['strDocu'] . '[/a]' )
69 . '&' . SID
71 exit();
74 $GLOBALS['cfg']['Server']['extension'] = $alternativ_extension;
75 unset( $alternativ_extension );
78 /**
79 * Including The DBI Plugin
81 require_once('./libraries/dbi/' . $GLOBALS['cfg']['Server']['extension'] . '.dbi.lib.php');
83 /**
84 * Common Functions
86 function PMA_DBI_query($query, $link = null, $options = 0) {
87 $res = PMA_DBI_try_query($query, $link, $options)
88 or PMA_mysqlDie(PMA_DBI_getError($link), $query);
89 return $res;
92 /**
93 * converts charset of a mysql message, usally coming from mysql_error(),
94 * into PMA charset, usally UTF-8
95 * uses language to charset mapping from mysql/share/errmsg.txt
96 * and charset names to ISO charset from information_schema.CHARACTER_SETS
98 * @uses $GLOBALS['cfg']['IconvExtraParams']
99 * @uses $GLOBALS['charset'] as target charset
100 * @uses PMA_DBI_fetch_value() to get server_language
101 * @uses preg_match() to filter server_language
102 * @uses in_array()
103 * @uses function_exists() to check for a convert function
104 * @uses iconv() to convert message
105 * @uses libiconv() to convert message
106 * @uses recode_string() to convert message
107 * @uses mb_convert_encoding() to convert message
108 * @param string $message
109 * @return string $message
111 function PMA_DBI_convert_message( $message ) {
112 // latin always last!
113 $encodings = array(
114 'japanese' => 'EUC-JP', //'ujis',
115 'japanese-sjis' => 'Shift-JIS', //'sjis',
116 'korean' => 'EUC-KR', //'euckr',
117 'russian' => 'KOI8-R', //'koi8r',
118 'ukrainian' => 'KOI8-U', //'koi8u',
119 'greek' => 'ISO-8859-7', //'greek',
120 'serbian' => 'CP1250', //'cp1250',
121 'estonian' => 'ISO-8859-13', //'latin7',
122 'slovak' => 'ISO-8859-2', //'latin2',
123 'czech' => 'ISO-8859-2', //'latin2',
124 'hungarian' => 'ISO-8859-2', //'latin2',
125 'polish' => 'ISO-8859-2', //'latin2',
126 'romanian' => 'ISO-8859-2', //'latin2',
127 'spanish' => 'CP1252', //'latin1',
128 'swedish' => 'CP1252', //'latin1',
129 'italian' => 'CP1252', //'latin1',
130 'norwegian-ny' => 'CP1252', //'latin1',
131 'norwegian' => 'CP1252', //'latin1',
132 'portuguese' => 'CP1252', //'latin1',
133 'danish' => 'CP1252', //'latin1',
134 'dutch' => 'CP1252', //'latin1',
135 'english' => 'CP1252', //'latin1',
136 'french' => 'CP1252', //'latin1',
137 'german' => 'CP1252', //'latin1',
140 if ( $server_language = PMA_DBI_fetch_value( 'SHOW VARIABLES LIKE \'language\';', 0, 1 ) ) {
141 $found = array();
142 if ( preg_match( '&(?:\\\|\\/)([^\\\\\/]*)(?:\\\|\\/)$&i', $server_language, $found )) {
143 $server_language = $found[1];
147 if ( ! empty( $server_language ) && isset( $encodings[$server_language] ) ) {
148 if ( function_exists( 'iconv' ) ) {
149 if ((@stristr(PHP_OS, 'AIX')) && (@strcasecmp(ICONV_IMPL, 'unknown') == 0) && (@strcasecmp(ICONV_VERSION, 'unknown') == 0)) {
150 require_once('./libraries/iconv_wrapper.lib.php');
151 $message = PMA_aix_iconv_wrapper( $encodings[$server_language],
152 $GLOBALS['charset'] . $GLOBALS['cfg']['IconvExtraParams'], $message);
153 } else {
154 $message = iconv( $encodings[$server_language],
155 $GLOBALS['charset'] . $GLOBALS['cfg']['IconvExtraParams'], $message);
157 } elseif ( function_exists( 'recode_string' ) ) {
158 $message = recode_string( $encodings[$server_language] . '..' . $GLOBALS['charset'],
159 $message );
160 } elseif ( function_exists( 'libiconv' ) ) {
161 $message = libiconv( $encodings[$server_language], $GLOBALS['charset'], $message );
162 } elseif ( function_exists( 'mb_convert_encoding' ) ) {
163 // do not try unsupported charsets
164 if ( ! in_array( $server_language, array( 'ukrainian', 'greek', 'serbian' ) ) ) {
165 $message = mb_convert_encoding( $message, $GLOBALS['charset'],
166 $encodings[$server_language] );
169 } else {
171 * @todo lang not found, try all, what TODO ?
175 return $message;
179 * returns array with table names for given db
181 * @param string $database name of database
182 * @param mixed $link mysql link resource|object
183 * @return array tables names
185 function PMA_DBI_get_tables($database, $link = null)
187 return PMA_DBI_fetch_result('SHOW TABLES FROM ' . PMA_backquote($database) . ';',
188 null, 0, $link, PMA_DBI_QUERY_STORE);
192 * returns array of all tables in given db or dbs
193 * this function expects unqoted names:
194 * RIGHT: my_database
195 * WRONG: `my_database`
196 * WRONG: my\_database
197 * if $tbl_is_group is true, $table is used as filter for table names
198 * if $tbl_is_group is 'comment, $table is used as filter for table comments
200 * <code>
201 * PMA_DBI_get_tables_full( 'my_database' );
202 * PMA_DBI_get_tables_full( 'my_database', 'my_table' ) );
203 * PMA_DBI_get_tables_full( 'my_database', 'my_tables_', true ) );
204 * PMA_DBI_get_tables_full( 'my_database', 'my_tables_', 'comment' ) );
205 * </code>
207 * @uses PMA_MYSQL_INT_VERSION
208 * @uses PMA_DBI_fetch_result()
209 * @uses PMA_escape_mysql_wildcards()
210 * @uses PMA_backquote()
211 * @uses is_array()
212 * @uses addslashes()
213 * @uses strpos()
214 * @uses strtoupper()
215 * @param string $databases database
216 * @param string $table table
217 * @param boolean|string $tbl_is_group $table is a table group
218 * @param resource $link mysql link
219 * @return array list of tbales in given db(s)
221 function PMA_DBI_get_tables_full($database, $table = false,
222 $tbl_is_group = false, $link = null)
224 // prepare and check parameters
225 if ( ! is_array($database) ) {
226 $databases = array(addslashes($database));
227 } else {
228 $databases = array_map('addslashes', $database);
231 $tables = array();
233 if ( PMA_MYSQL_INT_VERSION >= 50002 ) {
234 // get table information from information_schema
235 if ( $table ) {
236 if ( true === $tbl_is_group ) {
237 $sql_where_table = 'AND `TABLE_NAME` LIKE \''
238 . PMA_escape_mysql_wildcards(addslashes($table)) . '%\'';
239 } elseif ( 'comment' === $tbl_is_group ) {
240 $sql_where_table = 'AND `TABLE_COMMENT` LIKE \''
241 . PMA_escape_mysql_wildcards(addslashes($table)) . '%\'';
242 } else {
243 $sql_where_table = 'AND `TABLE_NAME` = \'' . addslashes($table) . '\'';
245 } else {
246 $sql_where_table = '';
249 // for PMA bc:
250 // `SCHEMA_FIELD_NAME` AS `SHOW_TABLE_STATUS_FIELD_NAME`
252 // on non-Windows servers,
253 // added BINARY in the WHERE clause to force a case sensitive
254 // comparison (if we are looking for the db Aa we don't want
255 // to find the db aa)
256 $sql = '
257 SELECT *,
258 `TABLE_SCHEMA` AS `Db`,
259 `TABLE_NAME` AS `Name`,
260 `ENGINE` AS `Engine`,
261 `ENGINE` AS `Type`,
262 `VERSION` AS `Version`,
263 `ROW_FORMAT` AS `Row_format`,
264 `TABLE_ROWS` AS `Rows`,
265 `AVG_ROW_LENGTH` AS `Avg_row_length`,
266 `DATA_LENGTH` AS `Data_length`,
267 `MAX_DATA_LENGTH` AS `Max_data_length`,
268 `INDEX_LENGTH` AS `Index_length`,
269 `DATA_FREE` AS `Data_free`,
270 `AUTO_INCREMENT` AS `Auto_increment`,
271 `CREATE_TIME` AS `Create_time`,
272 `UPDATE_TIME` AS `Update_time`,
273 `CHECK_TIME` AS `Check_time`,
274 `TABLE_COLLATION` AS `Collation`,
275 `CHECKSUM` AS `Checksum`,
276 `CREATE_OPTIONS` AS `Create_options`,
277 `TABLE_COMMENT` AS `Comment`
278 FROM `information_schema`.`TABLES`
279 WHERE ' . (PMA_IS_WINDOWS ? '' : 'BINARY') . ' `TABLE_SCHEMA` IN (\'' . implode("', '", $databases) . '\')
280 ' . $sql_where_table;
282 $tables = PMA_DBI_fetch_result($sql, array('TABLE_SCHEMA', 'TABLE_NAME'),
283 null, $link);
284 unset( $sql_where_table, $sql );
286 // If permissions are wrong on even one database directory,
287 // information_schema does not return any table info for any database
288 // this is why we fall back to SHOW TABLE STATUS even for MySQL >= 50002
289 if ( PMA_MYSQL_INT_VERSION < 50002 || empty($tables)) {
290 foreach ( $databases as $each_database ) {
291 if ( true === $tbl_is_group ) {
292 $sql = 'SHOW TABLE STATUS FROM '
293 . PMA_backquote($each_database)
294 .' LIKE \'' . PMA_escape_mysql_wildcards(addslashes($table)) . '%\'';
295 } else {
296 $sql = 'SHOW TABLE STATUS FROM '
297 . PMA_backquote($each_database) . ';';
299 $each_tables = PMA_DBI_fetch_result($sql, 'Name', null, $link);
300 foreach ( $each_tables as $table_name => $each_table ) {
301 if ( 'comment' === $tbl_is_group
302 && 0 === strpos($each_table['Comment'], $table) )
304 // remove table from list
305 unset( $each_tables[$table_name] );
306 continue;
309 if ( ! isset( $each_tables[$table_name]['Type'] )
310 && isset( $each_tables[$table_name]['Engine'] ) ) {
311 // pma BC, same parts of PMA still uses 'Type'
312 $each_tables[$table_name]['Type']
313 =& $each_tables[$table_name]['Engine'];
314 } elseif ( ! isset( $each_tables[$table_name]['Engine'] )
315 && isset( $each_tables[$table_name]['Type'] ) ) {
316 // old MySQL reports Type, newer MySQL reports Engine
317 $each_tables[$table_name]['Engine']
318 =& $each_tables[$table_name]['Type'];
321 // MySQL forward compatibility
322 // so pma could use this array as if every server is of version >5.0
323 $each_tables[$table_name]['TABLE_SCHEMA'] = $each_database;
324 $each_tables[$table_name]['TABLE_NAME'] =& $each_tables[$table_name]['Name'];
325 $each_tables[$table_name]['ENGINE'] =& $each_tables[$table_name]['Engine'];
326 $each_tables[$table_name]['VERSION'] =& $each_tables[$table_name]['Version'];
327 $each_tables[$table_name]['ROW_FORMAT'] =& $each_tables[$table_name]['Row_format'];
328 $each_tables[$table_name]['TABLE_ROWS'] =& $each_tables[$table_name]['Rows'];
329 $each_tables[$table_name]['AVG_ROW_LENGTH'] =& $each_tables[$table_name]['Avg_row_length'];
330 $each_tables[$table_name]['DATA_LENGTH'] =& $each_tables[$table_name]['Data_length'];
331 $each_tables[$table_name]['MAX_DATA_LENGTH'] =& $each_tables[$table_name]['Max_data_length'];
332 $each_tables[$table_name]['INDEX_LENGTH'] =& $each_tables[$table_name]['Index_length'];
333 $each_tables[$table_name]['DATA_FREE'] =& $each_tables[$table_name]['Data_free'];
334 $each_tables[$table_name]['AUTO_INCREMENT'] =& $each_tables[$table_name]['Auto_increment'];
335 $each_tables[$table_name]['CREATE_TIME'] =& $each_tables[$table_name]['Create_time'];
336 $each_tables[$table_name]['UPDATE_TIME'] =& $each_tables[$table_name]['Update_time'];
337 $each_tables[$table_name]['CHECK_TIME'] =& $each_tables[$table_name]['Check_time'];
338 $each_tables[$table_name]['TABLE_COLLATION'] =& $each_tables[$table_name]['Collation'];
339 $each_tables[$table_name]['CHECKSUM'] =& $each_tables[$table_name]['Checksum'];
340 $each_tables[$table_name]['CREATE_OPTIONS'] =& $each_tables[$table_name]['Create_options'];
341 $each_tables[$table_name]['TABLE_COMMENT'] =& $each_tables[$table_name]['Comment'];
343 if ( strtoupper( $each_tables[$table_name]['Comment'] ) === 'VIEW' ) {
344 $each_tables[$table_name]['TABLE_TYPE'] = 'VIEW';
345 } else {
347 * @todo difference between 'TEMPORARY' and 'BASE TABLE' but how to detect?
349 $each_tables[$table_name]['TABLE_TYPE'] = 'BASE TABLE';
353 $tables[$each_database] = $each_tables;
357 if ( $GLOBALS['cfg']['NaturalOrder'] ) {
358 foreach ( $tables as $key => $val ) {
359 uksort($tables[$key], 'strnatcasecmp');
363 if (! is_array($database)) {
364 if (isset($tables[$database])) {
365 return $tables[$database];
366 } elseif (isset($tables[strtolower($database)])) {
367 // on windows with lower_case_table_names = 1
368 // MySQL returns
369 // with SHOW DATABASES or information_schema.SCHEMATA: `Test`
370 // but information_schema.TABLES gives `test`
371 // bug #1436171
372 // sf.net/tracker/?func=detail&aid=1436171&group_id=23067&atid=377408
373 return $tables[strtolower($database)];
374 } else {
375 return $tables;
377 } else {
378 return $tables;
383 * returns array with databases containing extended infos about them
385 * @todo move into PMA_List_Database?
386 * @param string $databases database
387 * @param boolean $force_stats retrieve stats also for MySQL < 5
388 * @param resource $link mysql link
389 * @param string $sort_by collumn to order by
390 * @param string $sort_order ASC or DESC
391 * @param integer $limit_offset starting offset for LIMIT
392 * @param bool|int $limit_count row count for LIMIT or true for $GLOBALS['cfg']['MaxDbList']
393 * @return array $databases
395 function PMA_DBI_get_databases_full($database = null, $force_stats = false,
396 $link = null, $sort_by = 'SCHEMA_NAME', $sort_order = 'ASC',
397 $limit_offset = 0, $limit_count = false)
399 $sort_order = strtoupper($sort_order);
401 if (true === $limit_count) {
402 $limit_count = $GLOBALS['cfg']['MaxDbList'];
405 // initialize to avoid errors when there are no databases
406 $databases = array();
408 $apply_limit_and_order_manual = true;
410 if (PMA_MYSQL_INT_VERSION >= 50002) {
412 * if $GLOBALS['cfg']['NaturalOrder'] is enabled, we cannot use LIMIT
413 * cause MySQL does not support natural ordering, we have to do it afterward
415 if ($GLOBALS['cfg']['NaturalOrder']) {
416 $limit = '';
417 } else {
418 if ($limit_count) {
419 $limit = ' LIMIT ' . $limit_count . ' OFFSET ' . $limit_offset;
422 $apply_limit_and_order_manual = false;
425 // get table information from information_schema
426 if ( $database ) {
427 $sql_where_schema = 'WHERE `SCHEMA_NAME` LIKE \''
428 . addslashes( $database ) . '\'';
429 } else {
430 $sql_where_schema = '';
433 // for PMA bc:
434 // `SCHEMA_FIELD_NAME` AS `SHOW_TABLE_STATUS_FIELD_NAME`
435 $sql = '
436 SELECT `information_schema`.`SCHEMATA`.*';
437 if ($force_stats) {
438 $sql .= ',
439 COUNT(`information_schema`.`TABLES`.`TABLE_SCHEMA`)
440 AS `SCHEMA_TABLES`,
441 SUM(`information_schema`.`TABLES`.`TABLE_ROWS`)
442 AS `SCHEMA_TABLE_ROWS`,
443 SUM(`information_schema`.`TABLES`.`DATA_LENGTH`)
444 AS `SCHEMA_DATA_LENGTH`,
445 SUM(`information_schema`.`TABLES`.`MAX_DATA_LENGTH`)
446 AS `SCHEMA_MAX_DATA_LENGTH`,
447 SUM(`information_schema`.`TABLES`.`INDEX_LENGTH`)
448 AS `SCHEMA_INDEX_LENGTH`,
449 SUM(`information_schema`.`TABLES`.`DATA_LENGTH`
450 + `information_schema`.`TABLES`.`INDEX_LENGTH`)
451 AS `SCHEMA_LENGTH`,
452 SUM(`information_schema`.`TABLES`.`DATA_FREE`)
453 AS `SCHEMA_DATA_FREE`';
455 $sql .= '
456 FROM `information_schema`.`SCHEMATA`';
457 if ($force_stats) {
458 $sql .= '
459 LEFT JOIN `information_schema`.`TABLES`
460 ON `information_schema`.`TABLES`.`TABLE_SCHEMA`
461 = `information_schema`.`SCHEMATA`.`SCHEMA_NAME`';
463 $sql .= '
464 ' . $sql_where_schema . '
465 GROUP BY `information_schema`.`SCHEMATA`.`SCHEMA_NAME`
466 ORDER BY ' . PMA_backquote($sort_by) . ' ' . $sort_order
467 . $limit;
468 $databases = PMA_DBI_fetch_result($sql, 'SCHEMA_NAME', null, $link);
470 $mysql_error = PMA_DBI_getError($link);
471 if (! count($databases) && $GLOBALS['errno']) {
472 PMA_mysqlDie($mysql_error, $sql);
475 // display only databases also in official database list
476 // f.e. to apply hide_db and only_db
477 $drops = array_diff(array_keys($databases), $GLOBALS['PMA_List_Database']->items);
478 if (count($drops)) {
479 foreach ($drops as $drop) {
480 unset($databases[$drop]);
482 unset($drop);
484 unset($sql_where_schema, $sql, $drops);
485 } else {
486 foreach ($GLOBALS['PMA_List_Database']->items as $database_name) {
487 // MySQL forward compatibility
488 // so pma could use this array as if every server is of version >5.0
489 $databases[$database_name]['SCHEMA_NAME'] = $database_name;
491 if ( $force_stats ) {
492 require_once 'mysql_charsets.lib.php';
494 $databases[$database_name]['DEFAULT_COLLATION_NAME']
495 = PMA_getDbCollation( $database_name );
497 // get additonal info about tables
498 $databases[$database_name]['SCHEMA_TABLES'] = 0;
499 $databases[$database_name]['SCHEMA_TABLE_ROWS'] = 0;
500 $databases[$database_name]['SCHEMA_DATA_LENGTH'] = 0;
501 $databases[$database_name]['SCHEMA_MAX_DATA_LENGTH'] = 0;
502 $databases[$database_name]['SCHEMA_INDEX_LENGTH'] = 0;
503 $databases[$database_name]['SCHEMA_LENGTH'] = 0;
504 $databases[$database_name]['SCHEMA_DATA_FREE'] = 0;
506 $res = PMA_DBI_query('SHOW TABLE STATUS FROM ' . PMA_backquote( $database_name ) . ';');
507 while ( $row = PMA_DBI_fetch_assoc( $res ) ) {
508 $databases[$database_name]['SCHEMA_TABLES']++;
509 $databases[$database_name]['SCHEMA_TABLE_ROWS']
510 += $row['Rows'];
511 $databases[$database_name]['SCHEMA_DATA_LENGTH']
512 += $row['Data_length'];
513 $databases[$database_name]['SCHEMA_MAX_DATA_LENGTH']
514 += $row['Max_data_length'];
515 $databases[$database_name]['SCHEMA_INDEX_LENGTH']
516 += $row['Index_length'];
517 $databases[$database_name]['SCHEMA_DATA_FREE']
518 += $row['Data_free'];
519 $databases[$database_name]['SCHEMA_LENGTH']
520 += $row['Data_length'] + $row['Index_length'];
522 PMA_DBI_free_result( $res );
523 unset( $res );
529 * apply limit and order manually now
530 * (caused by older MySQL < 5 or $GLOBALS['cfg']['NaturalOrder'])
532 if ($apply_limit_and_order_manual) {
535 * first apply ordering
537 if ($GLOBALS['cfg']['NaturalOrder']) {
538 $sorter = 'strnatcasecmp';
539 } else {
540 $sorter = 'strcasecmp';
543 // produces f.e.:
544 // return -1 * strnatcasecmp($a["SCHEMA_TABLES"], $b["SCHEMA_TABLES"])
545 $sort_function = '
546 return ' . ($sort_order == 'ASC' ? 1 : -1) . ' * ' . $sorter . '($a["' . $sort_by . '"], $b["' . $sort_by . '"]);
549 usort($databases, create_function('$a, $b', $sort_function));
552 * now apply limit
554 if ($limit_count) {
555 $databases = array_slice($databases, $limit_offset, $limit_count);
559 return $databases;
563 * returns detailed array with all columns for given table in database,
564 * or all tables/databases
566 * @param string $database name of database
567 * @param string $table name of table to retrieve columns from
568 * @param string $column name of specific column
569 * @param mixed $link mysql link resource
571 function PMA_DBI_get_columns_full($database = null, $table = null,
572 $column = null, $link = null)
574 $columns = array();
576 if ( PMA_MYSQL_INT_VERSION >= 50002 ) {
577 $sql_wheres = array();
578 $array_keys = array();
580 // get columns information from information_schema
581 if ( null !== $database ) {
582 $sql_wheres[] = '`TABLE_SCHEMA` = \'' . addslashes($database) . '\' ';
583 } else {
584 $array_keys[] = 'TABLE_SCHEMA';
586 if ( null !== $table ) {
587 $sql_wheres[] = '`TABLE_NAME` = \'' . addslashes($table) . '\' ';
588 } else {
589 $array_keys[] = 'TABLE_NAME';
591 if ( null !== $column ) {
592 $sql_wheres[] = '`COLUMN_NAME` = \'' . addslashes($column) . '\' ';
593 } else {
594 $array_keys[] = 'COLUMN_NAME';
597 // for PMA bc:
598 // `[SCHEMA_FIELD_NAME]` AS `[SHOW_FULL_COLUMNS_FIELD_NAME]`
599 $sql = '
600 SELECT *,
601 `COLUMN_NAME` AS `Field`,
602 `COLUMN_TYPE` AS `Type`,
603 `COLLATION_NAME` AS `Collation`,
604 `IS_NULLABLE` AS `Null`,
605 `COLUMN_KEY` AS `Key`,
606 `COLUMN_DEFAULT` AS `Default`,
607 `EXTRA` AS `Extra`,
608 `PRIVILEGES` AS `Privileges`,
609 `COLUMN_COMMENT` AS `Comment`
610 FROM `information_schema`.`COLUMNS`';
611 if ( count($sql_wheres) ) {
612 $sql .= "\n" . ' WHERE ' . implode(' AND ', $sql_wheres);
615 $columns = PMA_DBI_fetch_result($sql, $array_keys, null, $link);
616 unset( $sql_wheres, $sql );
617 } else {
618 if ( null === $database ) {
619 foreach ($GLOBALS['PMA_List_Database']->items as $database) {
620 $columns[$database] = PMA_DBI_get_columns_full($database, null,
621 null, $link);
623 return $columns;
624 } elseif ( null === $table ) {
625 $tables = PMA_DBI_get_tables($database);
626 foreach ( $tables as $table ) {
627 $columns[$table] = PMA_DBI_get_columns_full(
628 $database, $table, null, $link);
630 return $columns;
633 $sql = 'SHOW FULL COLUMNS FROM '
634 . PMA_backquote($database) . '.' . PMA_backquote($table);
635 if ( null !== $column ) {
636 $sql .= " LIKE '" . $column . "'";
639 $columns = PMA_DBI_fetch_result( $sql, 'Field', null, $link );
641 $ordinal_position = 1;
642 foreach ( $columns as $column_name => $each_column ) {
644 // MySQL forward compatibility
645 // so pma could use this array as if every server is of version >5.0
646 $columns[$column_name]['COLUMN_NAME'] =& $columns[$column_name]['Field'];
647 $columns[$column_name]['COLUMN_TYPE'] =& $columns[$column_name]['Type'];
648 $columns[$column_name]['COLLATION_NAME'] =& $columns[$column_name]['Collation'];
649 $columns[$column_name]['IS_NULLABLE'] =& $columns[$column_name]['Null'];
650 $columns[$column_name]['COLUMN_KEY'] =& $columns[$column_name]['Key'];
651 $columns[$column_name]['COLUMN_DEFAULT'] =& $columns[$column_name]['Default'];
652 $columns[$column_name]['EXTRA'] =& $columns[$column_name]['Extra'];
653 $columns[$column_name]['PRIVILEGES'] =& $columns[$column_name]['Privileges'];
654 $columns[$column_name]['COLUMN_COMMENT'] =& $columns[$column_name]['Comment'];
656 $columns[$column_name]['TABLE_CATALOG'] = null;
657 $columns[$column_name]['TABLE_SCHEMA'] = $database;
658 $columns[$column_name]['TABLE_NAME'] = $table;
659 $columns[$column_name]['ORDINAL_POSITION'] = $ordinal_position;
660 $columns[$column_name]['DATA_TYPE'] =
661 substr($columns[$column_name]['COLUMN_TYPE'], 0,
662 strpos($columns[$column_name]['COLUMN_TYPE'], '('));
664 * @todo guess CHARACTER_MAXIMUM_LENGTH from COLUMN_TYPE
666 $columns[$column_name]['CHARACTER_MAXIMUM_LENGTH'] = null;
668 * @todo guess CHARACTER_OCTET_LENGTH from CHARACTER_MAXIMUM_LENGTH
670 $columns[$column_name]['CHARACTER_OCTET_LENGTH'] = null;
671 $columns[$column_name]['NUMERIC_PRECISION'] = null;
672 $columns[$column_name]['NUMERIC_SCALE'] = null;
673 $columns[$column_name]['CHARACTER_SET_NAME'] =
674 substr($columns[$column_name]['COLLATION_NAME'], 0,
675 strpos($columns[$column_name]['COLLATION_NAME'], '_'));
677 $ordinal_position++;
680 if ( null !== $column ) {
681 reset($columns);
682 $columns = current($columns);
686 return $columns;
690 * @todo should only return columns names, for more info use PMA_DBI_get_columns_full()
692 * @deprecated by PMA_DBI_get_columns() or PMA_DBI_get_columns_full()
693 * @param string $database name of database
694 * @param string $table name of table to retrieve columns from
695 * @param mixed $link mysql link resource
696 * @return array column info
698 function PMA_DBI_get_fields($database, $table, $link = null)
700 // here we use a try_query because when coming from
701 // tbl_create + tbl_properties.inc.php, the table does not exist
702 $fields = PMA_DBI_fetch_result(
703 'SHOW FULL COLUMNS
704 FROM ' . PMA_backquote($database) . '.' . PMA_backquote($table),
705 null, null, $link);
706 if ( ! is_array($fields) || count($fields) < 1 ) {
707 return false;
709 return $fields;
713 * array PMA_DBI_get_columns(string $database, string $table, bool $full = false, mysql db link $link = null)
715 * @param string $database name of database
716 * @param string $table name of table to retrieve columns from
717 * @param boolean $full wether to return full info or only column names
718 * @param mixed $link mysql link resource
719 * @return array column names
721 function PMA_DBI_get_columns($database, $table, $full = false, $link = null)
723 $fields = PMA_DBI_fetch_result(
724 'SHOW ' . ($full ? 'FULL' : '') . ' COLUMNS
725 FROM ' . PMA_backquote($database) . '.' . PMA_backquote($table),
726 'Fields', ($full ? null : 'Fields'), $link);
727 if ( ! is_array($fields) || count($fields) < 1 ) {
728 return false;
730 return $fields;
734 * returns value of given mysql server variable
736 * @param string $var mysql server variable name
737 * @param int $type PMA_DBI_GETVAR_SESSION|PMA_DBI_GETVAR_GLOBAL
738 * @param mixed $link mysql link resource|object
739 * @return mixed value for mysql server variable
741 function PMA_DBI_get_variable($var, $type = PMA_DBI_GETVAR_SESSION, $link = null)
743 if ($link === null) {
744 if (isset($GLOBALS['userlink'])) {
745 $link = $GLOBALS['userlink'];
746 } else {
747 return false;
750 if (PMA_MYSQL_INT_VERSION < 40002) {
751 $type = 0;
753 switch ($type) {
754 case PMA_DBI_GETVAR_SESSION:
755 $modifier = ' SESSION';
756 break;
757 case PMA_DBI_GETVAR_GLOBAL:
758 $modifier = ' GLOBAL';
759 break;
760 default:
761 $modifier = '';
763 return PMA_DBI_fetch_value(
764 'SHOW' . $modifier . ' VARIABLES LIKE \'' . $var . '\';', 0, 1, $link);
768 * @uses ./libraries/charset_conversion.lib.php
769 * @uses PMA_DBI_QUERY_STORE
770 * @uses PMA_REMOVED_NON_UTF_8
771 * @uses PMA_MYSQL_INT_VERSION
772 * @uses PMA_MYSQL_STR_VERSION
773 * @uses PMA_DBI_GETVAR_SESSION
774 * @uses PMA_DBI_fetch_value()
775 * @uses PMA_DBI_query()
776 * @uses PMA_DBI_get_variable()
777 * @uses $GLOBALS['collation_connection']
778 * @uses $GLOBALS['charset_connection']
779 * @uses $GLOBALS['available_languages']
780 * @uses $GLOBALS['mysql_charset_map']
781 * @uses $GLOBALS['charset']
782 * @uses $GLOBALS['lang']
783 * @uses $GLOBALS['cfg']['Lang']
784 * @uses $GLOBALS['cfg']['ColumnTypes']
785 * @uses defined()
786 * @uses explode()
787 * @uses sprintf()
788 * @uses intval()
789 * @uses define()
790 * @uses defined()
791 * @uses substr()
792 * @uses count()
793 * @param mixed $link mysql link resource|object
794 * @param boolean $is_controluser
796 function PMA_DBI_postConnect($link, $is_controluser = false)
798 if (!defined('PMA_MYSQL_INT_VERSION')) {
799 $mysql_version = PMA_DBI_fetch_value(
800 'SELECT VERSION()', 0, 0, $link, PMA_DBI_QUERY_STORE);
801 if ( $mysql_version ) {
802 $match = explode('.', $mysql_version);
803 define('PMA_MYSQL_INT_VERSION',
804 (int) sprintf('%d%02d%02d', $match[0], $match[1],
805 intval($match[2])));
806 define('PMA_MYSQL_STR_VERSION', $mysql_version);
807 unset($mysql_version, $match);
808 } else {
809 define('PMA_MYSQL_INT_VERSION', 32332);
810 define('PMA_MYSQL_STR_VERSION', '3.23.32');
814 if (!defined('PMA_ENGINE_KEYWORD')) {
815 if (PMA_MYSQL_INT_VERSION >= 40102) {
816 define('PMA_ENGINE_KEYWORD','ENGINE');
817 } else {
818 define('PMA_ENGINE_KEYWORD','TYPE');
822 if (PMA_MYSQL_INT_VERSION >= 40100) {
824 // If $lang is defined and we are on MySQL >= 4.1.x,
825 // we auto-switch the lang to its UTF-8 version (if it exists and user
826 // didn't force language)
827 if ( !empty($GLOBALS['lang'])
828 && (substr($GLOBALS['lang'], -5) != 'utf-8')
829 && !isset($GLOBALS['cfg']['Lang']) ) {
830 $lang_utf_8_version =
831 substr($GLOBALS['lang'], 0, strpos($GLOBALS['lang'], '-'))
832 . '-utf-8';
833 if (!empty($GLOBALS['available_languages'][$lang_utf_8_version])) {
834 $GLOBALS['lang'] = $lang_utf_8_version;
835 $GLOBALS['charset'] = 'utf-8';
836 define('PMA_LANG_RELOAD', 1);
840 // and we remove the non-UTF-8 choices to avoid confusion
841 if (!defined('PMA_REMOVED_NON_UTF_8')) {
842 foreach ( $GLOBALS['available_languages'] as $each_lang => $dummy ) {
843 if ( substr($each_lang, -5) != 'utf-8' ) {
844 unset( $GLOBALS['available_languages'][$each_lang] );
847 define('PMA_REMOVED_NON_UTF_8', 1);
850 $mysql_charset = $GLOBALS['mysql_charset_map'][$GLOBALS['charset']];
851 if ( $is_controluser
852 || empty($GLOBALS['collation_connection'])
853 || (strpos($GLOBALS['collation_connection'], '_')
854 ? substr($GLOBALS['collation_connection'], 0, strpos($GLOBALS['collation_connection'], '_'))
855 : $GLOBALS['collation_connection']) == $mysql_charset) {
857 PMA_DBI_query('SET NAMES ' . $mysql_charset . ';', $link,
858 PMA_DBI_QUERY_STORE);
859 } else {
860 PMA_DBI_query('SET CHARACTER SET ' . $mysql_charset . ';', $link,
861 PMA_DBI_QUERY_STORE);
863 if (!empty($GLOBALS['collation_connection'])) {
864 PMA_DBI_query('SET collation_connection = \'' . $GLOBALS['collation_connection'] . '\';',
865 $link, PMA_DBI_QUERY_STORE);
867 if (!$is_controluser) {
868 $GLOBALS['collation_connection'] = PMA_DBI_get_variable('collation_connection',
869 PMA_DBI_GETVAR_SESSION, $link);
870 $GLOBALS['charset_connection'] = PMA_DBI_get_variable('character_set_connection',
871 PMA_DBI_GETVAR_SESSION, $link);
874 // Add some field types to the list, this needs to be done once per session!
875 if ($GLOBALS['cfg']['ColumnTypes'][count($GLOBALS['cfg']['ColumnTypes']) - 1] != 'VARBINARY') {
876 $GLOBALS['cfg']['ColumnTypes'][] = 'BINARY';
877 $GLOBALS['cfg']['ColumnTypes'][] = 'VARBINARY';
880 } else {
881 require_once('./libraries/charset_conversion.lib.php');
886 * returns a single value from the given result or query,
887 * if the query or the result has more than one row or field
888 * the first field of the first row is returned
890 * <code>
891 * $sql = 'SELECT `name` FROM `user` WHERE `id` = 123';
892 * $user_name = PMA_DBI_fetch_value( $sql );
893 * // produces
894 * // $user_name = 'John Doe'
895 * </code>
897 * @uses is_string()
898 * @uses is_int()
899 * @uses PMA_DBI_try_query()
900 * @uses PMA_DBI_num_rows()
901 * @uses PMA_DBI_fetch_row()
902 * @uses PMA_DBI_fetch_assoc()
903 * @uses PMA_DBI_free_result()
904 * @param string|mysql_result $result query or mysql result
905 * @param integer $row_number row to fetch the value from,
906 * starting at 0, with 0 beeing default
907 * @param integer|string $field field to fetch the value from,
908 * starting at 0, with 0 beeing default
909 * @param resource $link mysql link
910 * @param mixed $options
911 * @return mixed value of first field in first row from result
912 * or false if not found
914 function PMA_DBI_fetch_value( $result, $row_number = 0, $field = 0, $link = null, $options = 0 ) {
915 $value = false;
917 if ( is_string( $result ) ) {
918 $result = PMA_DBI_try_query( $result, $link, $options | PMA_DBI_QUERY_STORE );
921 // return false if result is empty or false
922 // or requested row is larger than rows in result
923 if ( PMA_DBI_num_rows( $result ) < ( $row_number + 1 ) ) {
924 return $value;
927 // if $field is an integer use non associative mysql fetch function
928 if ( is_int( $field ) ) {
929 $fetch_function = 'PMA_DBI_fetch_row';
930 } else {
931 $fetch_function = 'PMA_DBI_fetch_assoc';
934 // get requested row
935 for ( $i = 0; $i <= $row_number; $i++ ) {
936 $row = $fetch_function( $result );
938 PMA_DBI_free_result( $result );
940 // return requested field
941 if ( isset( $row[$field] ) ) {
942 $value = $row[$field];
944 unset( $row );
946 return $value;
950 * returns only the first row from the result
952 * <code>
953 * $sql = 'SELECT * FROM `user` WHERE `id` = 123';
954 * $user = PMA_DBI_fetch_single_row( $sql );
955 * // produces
956 * // $user = array( 'id' => 123, 'name' => 'John Doe' )
957 * </code>
959 * @uses is_string()
960 * @uses PMA_DBI_try_query()
961 * @uses PMA_DBI_num_rows()
962 * @uses PMA_DBI_fetch_row()
963 * @uses PMA_DBI_fetch_assoc()
964 * @uses PMA_DBI_fetch_array()
965 * @uses PMA_DBI_free_result()
966 * @param string|mysql_result $result query or mysql result
967 * @param string $type NUM|ASSOC|BOTH
968 * returned array should either numeric
969 * associativ or booth
970 * @param resource $link mysql link
971 * @param mixed $options
972 * @return array|boolean first row from result
973 * or false if result is empty
975 function PMA_DBI_fetch_single_row( $result, $type = 'ASSOC', $link = null, $options = 0 ) {
976 if ( is_string( $result ) ) {
977 $result = PMA_DBI_try_query( $result, $link, $options | PMA_DBI_QUERY_STORE );
980 // return null if result is empty or false
981 if ( ! PMA_DBI_num_rows( $result ) ) {
982 return false;
985 switch ( $type ) {
986 case 'NUM' :
987 $fetch_function = 'PMA_DBI_fetch_row';
988 break;
989 case 'ASSOC' :
990 $fetch_function = 'PMA_DBI_fetch_assoc';
991 break;
992 case 'BOTH' :
993 default :
994 $fetch_function = 'PMA_DBI_fetch_array';
995 break;
998 $row = $fetch_function( $result );
999 PMA_DBI_free_result( $result );
1000 return $row;
1004 * returns all rows in the resultset in one array
1006 * <code>
1007 * $sql = 'SELECT * FROM `user`';
1008 * $users = PMA_DBI_fetch_result( $sql );
1009 * // produces
1010 * // $users[] = array( 'id' => 123, 'name' => 'John Doe' )
1012 * $sql = 'SELECT `id`, `name` FROM `user`';
1013 * $users = PMA_DBI_fetch_result( $sql, 'id' );
1014 * // produces
1015 * // $users['123'] = array( 'id' => 123, 'name' => 'John Doe' )
1017 * $sql = 'SELECT `id`, `name` FROM `user`';
1018 * $users = PMA_DBI_fetch_result( $sql, 0 );
1019 * // produces
1020 * // $users['123'] = array( 0 => 123, 1 => 'John Doe' )
1022 * $sql = 'SELECT `id`, `name` FROM `user`';
1023 * $users = PMA_DBI_fetch_result( $sql, 'id', 'name' );
1024 * // or
1025 * $users = PMA_DBI_fetch_result( $sql, 0, 1 );
1026 * // produces
1027 * // $users['123'] = 'John Doe'
1029 * $sql = 'SELECT `name` FROM `user`';
1030 * $users = PMA_DBI_fetch_result( $sql );
1031 * // produces
1032 * // $users[] = 'John Doe'
1033 * </code>
1035 * @uses is_string()
1036 * @uses is_int()
1037 * @uses PMA_DBI_try_query()
1038 * @uses PMA_DBI_num_rows()
1039 * @uses PMA_DBI_num_fields()
1040 * @uses PMA_DBI_fetch_row()
1041 * @uses PMA_DBI_fetch_assoc()
1042 * @uses PMA_DBI_free_result()
1043 * @param string|mysql_result $result query or mysql result
1044 * @param string|integer $key field-name or offset
1045 * used as key for array
1046 * @param string|integer $value value-name or offset
1047 * used as value for array
1048 * @param resource $link mysql link
1049 * @param mixed $options
1050 * @return array resultrows or values indexed by $key
1052 function PMA_DBI_fetch_result( $result, $key = null, $value = null,
1053 $link = null, $options = 0 )
1055 $resultrows = array();
1057 if ( is_string($result) ) {
1058 $result = PMA_DBI_try_query($result, $link, $options);
1061 // return empty array if result is empty or false
1062 if ( ! $result ) {
1063 return $resultrows;
1066 $fetch_function = 'PMA_DBI_fetch_assoc';
1068 // no nested array if only one field is in result
1069 if ( null === $key && 1 === PMA_DBI_num_fields($result) ) {
1070 $value = 0;
1071 $fetch_function = 'PMA_DBI_fetch_row';
1074 // if $key is an integer use non associative mysql fetch function
1075 if ( is_int($key) ) {
1076 $fetch_function = 'PMA_DBI_fetch_row';
1079 if ( null === $key && null === $value ) {
1080 while ( $row = $fetch_function($result) ) {
1081 $resultrows[] = $row;
1083 } elseif ( null === $key ) {
1084 while ( $row = $fetch_function($result) ) {
1085 $resultrows[] = $row[$value];
1087 } elseif ( null === $value ) {
1088 if ( is_array($key) ) {
1089 while ( $row = $fetch_function($result) ) {
1090 $result_target =& $resultrows;
1091 foreach ( $key as $key_index ) {
1092 if ( ! isset( $result_target[$row[$key_index]] ) ) {
1093 $result_target[$row[$key_index]] = array();
1095 $result_target =& $result_target[$row[$key_index]];
1097 $result_target = $row;
1099 } else {
1100 while ( $row = $fetch_function($result) ) {
1101 $resultrows[$row[$key]] = $row;
1104 } else {
1105 if ( is_array($key) ) {
1106 while ( $row = $fetch_function($result) ) {
1107 $result_target =& $resultrows;
1108 foreach ( $key as $key_index ) {
1109 if ( ! isset( $result_target[$row[$key_index]] ) ) {
1110 $result_target[$row[$key_index]] = array();
1112 $result_target =& $result_target[$row[$key_index]];
1114 $result_target = $row[$value];
1116 } else {
1117 while ( $row = $fetch_function($result) ) {
1118 $resultrows[$row[$key]] = $row[$value];
1123 PMA_DBI_free_result($result);
1124 return $resultrows;
1128 * return default table engine for given database
1130 * @return string default table engine
1132 function PMA_DBI_get_default_engine()
1134 if ( PMA_MYSQL_INT_VERSION > 50002 ) {
1135 return PMA_DBI_fetch_value( 'SHOW VARIABLES LIKE \'storage_engine\';', 0, 1 );
1136 } else {
1137 return PMA_DBI_fetch_value( 'SHOW VARIABLES LIKE \'table_type\';', 0, 1 );
1142 * Get supported SQL compatibility modes
1144 * @return array supported SQL compatibility modes
1146 function PMA_DBI_getCompatibilities()
1148 if (PMA_MYSQL_INT_VERSION < 40100) {
1149 return array();
1151 $compats = array('NONE');
1152 if (PMA_MYSQL_INT_VERSION >= 40101) {
1153 $compats[] = 'ANSI';
1154 $compats[] = 'DB2';
1155 $compats[] = 'MAXDB';
1156 $compats[] = 'MYSQL323';
1157 $compats[] = 'MYSQL40';
1158 $compats[] = 'MSSQL';
1159 $compats[] = 'ORACLE';
1160 $compats[] = 'POSTGRESQL';
1161 if (PMA_MYSQL_INT_VERSION >= 50002) {
1162 $compats[] = 'TRADITIONAL';
1165 return $compats;
1170 * returns true (int > 0) if current user is superuser
1171 * otherwise 0
1173 * @return integer $is_superuser
1175 function PMA_isSuperuser() {
1176 return PMA_DBI_try_query( 'SELECT COUNT(*) FROM mysql.user',
1177 $GLOBALS['userlink'], PMA_DBI_QUERY_STORE );
1182 * returns an array of PROCEDURE or FUNCTION names for a db
1184 * @uses PMA_DBI_free_result()
1185 * @param string $db db name
1186 * @param string $which PROCEDURE | FUNCTION
1187 * @param resource $link mysql link
1189 * @return array the procedure names or function names
1191 function PMA_DBI_get_procedures_or_functions($db, $which, $link = null) {
1193 $shows = PMA_DBI_fetch_result('SHOW ' . $which . ' STATUS;', null, null, $link);
1194 $result = array();
1195 foreach ($shows as $one_show) {
1196 if ($one_show['Db'] == $db && $one_show['Type'] == $which) {
1197 $result[] = $one_show['Name'];
1200 return($result);
1204 * returns the definition of a specific PROCEDURE or FUNCTION
1206 * @uses PMA_DBI_fetch_value()
1207 * @param string $db db name
1208 * @param string $which PROCEDURE | FUNCTION
1209 * @param string $proc_or_function_name the procedure name or function name
1210 * @param resource $link mysql link
1212 * @return string the procedure's or function's definition
1214 function PMA_DBI_get_procedure_or_function_def($db, $which, $proc_or_function_name, $link = null) {
1216 $returned_field = array('PROCEDURE' => 'Create Procedure', 'FUNCTION' => 'Create Function');
1217 $query = 'SHOW CREATE ' . $which . ' ' . PMA_backquote($db) . '.' . PMA_backquote($proc_or_function_name);
1218 return(PMA_DBI_fetch_value( $query, 0, $returned_field[$which]));