translation update
[phpmyadmin/last10db.git] / libraries / database_interface.lib.php
blob4c74d1bd034542b831b92b29292128d99f278c83
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 // TODO 2.7.1: add different messages for alternativ extension
42 // and complete fail (no alternativ extension too)
43 $GLOBALS['PMA_errors'][] =
44 sprintf( PMA_sanitize( $GLOBALS['strCantLoad'] ),
45 $GLOBALS['cfg']['Server']['extension'] )
46 .' - <a href="./Documentation.html#faqmysql" target="documentation">'
47 .$GLOBALS['strDocu'] . '</a>';
49 if ( $GLOBALS['cfg']['Server']['extension'] === 'mysql' ) {
50 $alternativ_extension = 'mysqli';
51 } else {
52 $alternativ_extension = 'mysql';
55 if ( ! PMA_DBI_checkAndLoadMysqlExtension( $alternativ_extension ) ) {
56 // if alternativ fails too ...
57 header( 'Location: error.php'
58 . '?lang=' . urlencode( $available_languages[$lang][2] )
59 . '&char=' . urlencode( $charset )
60 . '&dir=' . urlencode( $text_dir )
61 . '&type=' . urlencode( $strError )
62 . '&error=' . urlencode(
63 sprintf( $GLOBALS['strCantLoad'],
64 $GLOBALS['cfg']['Server']['extension'] )
65 .' - [a@./Documentation.html#faqmysql@documentation]'
66 .$GLOBALS['strDocu'] . '[/a]' )
67 . '&' . SID
69 exit();
72 $GLOBALS['cfg']['Server']['extension'] = $alternativ_extension;
73 unset( $alternativ_extension );
76 /**
77 * Including The DBI Plugin
79 require_once('./libraries/dbi/' . $GLOBALS['cfg']['Server']['extension'] . '.dbi.lib.php');
81 /**
82 * Common Functions
84 function PMA_DBI_query($query, $link = null, $options = 0) {
85 $res = PMA_DBI_try_query($query, $link, $options)
86 or PMA_mysqlDie(PMA_DBI_getError($link), $query);
87 return $res;
90 /**
91 * converts charset of a mysql message, usally coming from mysql_error(),
92 * into PMA charset, usally UTF-8
93 * uses language to charset mapping from mysql/share/errmsg.txt
94 * and charset names to ISO charset from information_schema.CHARACTER_SETS
96 * @uses $GLOBALS['cfg']['IconvExtraParams']
97 * @uses $GLOBALS['charset'] as target charset
98 * @uses PMA_DBI_fetch_value() to get server_language
99 * @uses preg_match() to filter server_language
100 * @uses in_array()
101 * @uses function_exists() to check for a convert function
102 * @uses iconv() to convert message
103 * @uses libiconv() to convert message
104 * @uses recode_string() to convert message
105 * @uses mb_convert_encoding() to convert message
106 * @param string $message
107 * @return string $message
109 function PMA_DBI_convert_message( $message ) {
110 // latin always last!
111 $encodings = array(
112 'japanese' => 'EUC-JP', //'ujis',
113 'japanese-sjis' => 'Shift-JIS', //'sjis',
114 'korean' => 'EUC-KR', //'euckr',
115 'russian' => 'KOI8-R', //'koi8r',
116 'ukrainian' => 'KOI8-U', //'koi8u',
117 'greek' => 'ISO-8859-7', //'greek',
118 'serbian' => 'CP1250', //'cp1250',
119 'estonian' => 'ISO-8859-13', //'latin7',
120 'slovak' => 'ISO-8859-2', //'latin2',
121 'czech' => 'ISO-8859-2', //'latin2',
122 'hungarian' => 'ISO-8859-2', //'latin2',
123 'polish' => 'ISO-8859-2', //'latin2',
124 'romanian' => 'ISO-8859-2', //'latin2',
125 'spanish' => 'CP1252', //'latin1',
126 'swedish' => 'CP1252', //'latin1',
127 'italian' => 'CP1252', //'latin1',
128 'norwegian-ny' => 'CP1252', //'latin1',
129 'norwegian' => 'CP1252', //'latin1',
130 'portuguese' => 'CP1252', //'latin1',
131 'danish' => 'CP1252', //'latin1',
132 'dutch' => 'CP1252', //'latin1',
133 'english' => 'CP1252', //'latin1',
134 'french' => 'CP1252', //'latin1',
135 'german' => 'CP1252', //'latin1',
138 if ( $server_language = PMA_DBI_fetch_value( 'SHOW VARIABLES LIKE \'language\';', 0, 1 ) ) {
139 $found = array();
140 if ( preg_match( '&(?:\\\|\\/)([^\\\\\/]*)(?:\\\|\\/)$&i', $server_language, $found )) {
141 $server_language = $found[1];
145 if ( ! empty( $server_language ) && isset( $encodings[$server_language] ) ) {
146 if ( function_exists( 'iconv' ) ) {
147 if ((@stristr(PHP_OS, 'AIX')) && (@strcasecmp(ICONV_IMPL, 'unknown') == 0) && (@strcasecmp(ICONV_VERSION, 'unknown') == 0)) {
148 require_once('./liraries/iconv_wrapper.lib.php');
149 $message = PMA_aix_iconv_wrapper( $encodings[$server_language],
150 $GLOBALS['charset'] . $GLOBALS['cfg']['IconvExtraParams'], $message);
151 } else {
152 $message = iconv( $encodings[$server_language],
153 $GLOBALS['charset'] . $GLOBALS['cfg']['IconvExtraParams'], $message);
155 } elseif ( function_exists( 'recode_string' ) ) {
156 $message = recode_string( $encodings[$server_language] . '..' . $GLOBALS['charset'],
157 $message );
158 } elseif ( function_exists( 'libiconv' ) ) {
159 $message = libiconv( $encodings[$server_language], $GLOBALS['charset'], $message );
160 } elseif ( function_exists( 'mb_convert_encoding' ) ) {
161 // do not try unsupported charsets
162 if ( ! in_array( $server_language, array( 'ukrainian', 'greek', 'serbian' ) ) ) {
163 $message = mb_convert_encoding( $message, $GLOBALS['charset'],
164 $encodings[$server_language] );
167 } else {
168 // lang not found, try all
169 // what TODO ?
172 return $message;
176 * returns array with database names
178 * @return array $databases
180 function PMA_DBI_get_dblist($link = null)
182 $dbs_array = PMA_DBI_fetch_result('SHOW DATABASES;', $link);
184 // Before MySQL 4.0.2, SHOW DATABASES could send the
185 // whole list, so check if we really have access:
186 if (PMA_MYSQL_INT_VERSION < 40002 || !empty($GLOBALS['cfg']['Server']['hide_db'])) {
187 foreach ($dbs_array as $key => $db) {
188 if (!@PMA_DBI_select_db($db, $link) || (!empty($GLOBALS['cfg']['Server']['hide_db']) && preg_match('/' . $GLOBALS['cfg']['Server']['hide_db'] . '/', $db))) {
189 unset( $dbs_array[$key] );
192 // re-index values
193 $dbs_array = array_values( $dbs_array );
196 return $dbs_array;
200 * returns array with table names for given db
202 * @param string $database name of database
203 * @param mixed $link mysql link resource|object
204 * @return array tables names
206 function PMA_DBI_get_tables($database, $link = null)
208 return PMA_DBI_fetch_result('SHOW TABLES FROM ' . PMA_backquote($database) . ';',
209 null, 0, $link, PMA_DBI_QUERY_STORE);
213 * returns array of all tables in given db or dbs
214 * this function expects unqoted names:
215 * RIGHT: my_database
216 * WRONG: `my_database`
217 * WRONG: my\_database
218 * if $tbl_is_group is true, $table is used as filter for table names
219 * if $tbl_is_group is 'comment, $table is used as filter for table comments
221 * <code>
222 * PMA_DBI_get_tables_full( 'my_database' );
223 * PMA_DBI_get_tables_full( 'my_database', 'my_table' ) );
224 * PMA_DBI_get_tables_full( 'my_database', 'my_tables_', true ) );
225 * PMA_DBI_get_tables_full( 'my_database', 'my_tables_', 'comment' ) );
226 * </code>
228 * @uses PMA_MYSQL_INT_VERSION
229 * @uses PMA_DBI_fetch_result()
230 * @uses PMA_escape_mysql_wildcards()
231 * @uses PMA_backquote()
232 * @uses is_array()
233 * @uses addslashes()
234 * @uses strpos()
235 * @uses strtoupper()
236 * @param string $databases database
237 * @param string $table table
238 * @param boolean|string $tbl_is_group $table is a table group
239 * @param resource $link mysql link
240 * @return array list of tbales in given db(s)
242 function PMA_DBI_get_tables_full($database, $table = false,
243 $tbl_is_group = false, $link = null)
245 // prepare and check parameters
246 if ( ! is_array($database) ) {
247 $databases = array(addslashes($database));
248 } else {
249 $databases = array_map('addslashes', $database);
252 $tables = array();
254 if ( PMA_MYSQL_INT_VERSION >= 50002 ) {
255 // get table information from information_schema
256 if ( $table ) {
257 if ( true === $tbl_is_group ) {
258 $sql_where_table = 'AND `TABLE_NAME` LIKE \''
259 . PMA_escape_mysql_wildcards(addslashes($table)) . '%\'';
260 } elseif ( 'comment' === $tbl_is_group ) {
261 $sql_where_table = 'AND `TABLE_COMMENT` LIKE \''
262 . PMA_escape_mysql_wildcards(addslashes($table)) . '%\'';
263 } else {
264 $sql_where_table = 'AND `TABLE_NAME` = \'' . addslashes($table) . '\'';
266 } else {
267 $sql_where_table = '';
270 // for PMA bc:
271 // `SCHEMA_FIELD_NAME` AS `SHOW_TABLE_STATUS_FIELD_NAME`
272 $sql = '
273 SELECT *,
274 `TABLE_SCHEMA` AS `Db`,
275 `TABLE_NAME` AS `Name`,
276 `ENGINE` AS `Engine`,
277 `ENGINE` AS `Type`,
278 `VERSION` AS `Version`,
279 `ROW_FORMAT` AS `Row_format`,
280 `TABLE_ROWS` AS `Rows`,
281 `AVG_ROW_LENGTH` AS `Avg_row_length`,
282 `DATA_LENGTH` AS `Data_length`,
283 `MAX_DATA_LENGTH` AS `Max_data_length`,
284 `INDEX_LENGTH` AS `Index_length`,
285 `DATA_FREE` AS `Data_free`,
286 `AUTO_INCREMENT` AS `Auto_increment`,
287 `CREATE_TIME` AS `Create_time`,
288 `UPDATE_TIME` AS `Update_time`,
289 `CHECK_TIME` AS `Check_time`,
290 `TABLE_COLLATION` AS `Collation`,
291 `CHECKSUM` AS `Checksum`,
292 `CREATE_OPTIONS` AS `Create_options`,
293 `TABLE_COMMENT` AS `Comment`
294 FROM `information_schema`.`TABLES`
295 WHERE `TABLE_SCHEMA` IN (\'' . implode("', '", $databases) . '\')
296 ' . $sql_where_table;
297 $tables = PMA_DBI_fetch_result($sql, array('TABLE_SCHEMA', 'TABLE_NAME'),
298 null, $link);
299 unset( $sql_where_table, $sql );
300 } else {
301 foreach ( $databases as $each_database ) {
302 if ( true === $tbl_is_group ) {
303 $sql = 'SHOW TABLE STATUS FROM '
304 . PMA_backquote($each_database)
305 .' LIKE \'' . PMA_escape_mysql_wildcards(addslashes($table)) . '%\'';
306 } else {
307 $sql = 'SHOW TABLE STATUS FROM '
308 . PMA_backquote($each_database) . ';';
310 $each_tables = PMA_DBI_fetch_result($sql, 'Name', null, $link);
311 foreach ( $each_tables as $table_name => $each_table ) {
312 if ( 'comment' === $tbl_is_group
313 && 0 === strpos($each_table['Comment'], $table) )
315 // remove table from list
316 unset( $each_tables[$table_name] );
317 continue;
320 if ( ! isset( $each_tables[$table_name]['Type'] )
321 && isset( $each_tables[$table_name]['Engine'] ) ) {
322 // pma BC, same parts of PMA still uses 'Type'
323 $each_tables[$table_name]['Type']
324 =& $each_tables[$table_name]['Engine'];
325 } elseif ( ! isset( $each_tables[$table_name]['Engine'] )
326 && isset( $each_tables[$table_name]['Type'] ) ) {
327 // old MySQL reports Type, newer MySQL reports Engine
328 $each_tables[$table_name]['Engine']
329 =& $each_tables[$table_name]['Type'];
332 // MySQL forward compatibility
333 // so pma could use this array as if every server is of version >5.0
334 $each_tables[$table_name]['TABLE_SCHEMA'] = $each_database;
335 $each_tables[$table_name]['TABLE_NAME'] =& $each_tables[$table_name]['Name'];
336 $each_tables[$table_name]['ENGINE'] =& $each_tables[$table_name]['Engine'];
337 $each_tables[$table_name]['VERSION'] =& $each_tables[$table_name]['Version'];
338 $each_tables[$table_name]['ROW_FORMAT'] =& $each_tables[$table_name]['Row_format'];
339 $each_tables[$table_name]['TABLE_ROWS'] =& $each_tables[$table_name]['Rows'];
340 $each_tables[$table_name]['AVG_ROW_LENGTH'] =& $each_tables[$table_name]['Avg_row_length'];
341 $each_tables[$table_name]['DATA_LENGTH'] =& $each_tables[$table_name]['Data_length'];
342 $each_tables[$table_name]['MAX_DATA_LENGTH'] =& $each_tables[$table_name]['Max_data_length'];
343 $each_tables[$table_name]['INDEX_LENGTH'] =& $each_tables[$table_name]['Index_length'];
344 $each_tables[$table_name]['DATA_FREE'] =& $each_tables[$table_name]['Data_free'];
345 $each_tables[$table_name]['AUTO_INCREMENT'] =& $each_tables[$table_name]['Auto_increment'];
346 $each_tables[$table_name]['CREATE_TIME'] =& $each_tables[$table_name]['Create_time'];
347 $each_tables[$table_name]['UPDATE_TIME'] =& $each_tables[$table_name]['Update_time'];
348 $each_tables[$table_name]['CHECK_TIME'] =& $each_tables[$table_name]['Check_time'];
349 $each_tables[$table_name]['TABLE_COLLATION'] =& $each_tables[$table_name]['Collation'];
350 $each_tables[$table_name]['CHECKSUM'] =& $each_tables[$table_name]['Checksum'];
351 $each_tables[$table_name]['CREATE_OPTIONS'] =& $each_tables[$table_name]['Create_options'];
352 $each_tables[$table_name]['TABLE_COMMENT'] =& $each_tables[$table_name]['Comment'];
354 if ( strtoupper( $each_tables[$table_name]['Comment'] ) === 'VIEW' ) {
355 $each_tables[$table_name]['TABLE_TYPE'] = 'VIEW';
356 } else {
357 // TODO difference between 'TEMPORARY' and 'BASE TABLE'
358 // but how to detect?
359 $each_tables[$table_name]['TABLE_TYPE'] = 'BASE TABLE';
363 $tables[$each_database] = $each_tables;
367 if ( $GLOBALS['cfg']['NaturalOrder'] ) {
368 foreach ( $tables as $key => $val ) {
369 uksort($tables[$key], 'strnatcasecmp');
373 if (! is_array($database)) {
374 if (isset($tables[$database])) {
375 return $tables[$database];
376 } elseif (isset($tables[strtolower($database)])) {
377 // on windows with lower_case_table_names = 1
378 // MySQL returns
379 // with SHOW DATABASES or information_schema.SCHEMATA: `Test`
380 // but information_schema.TABLES gives `test`
381 // bug #1436171
382 // sf.net/tracker/?func=detail&aid=1436171&group_id=23067&atid=377408
383 return $tables[strtolower($database)];
384 } else {
385 return $tables;
387 } else {
388 return $tables;
393 * returns count of databases for current server
395 * @param string $database databases to count
396 * @param resource $link mysql db link
398 function PMA_DBI_get_databases_count($database = null, $link = null)
400 return count(PMA_DBI_get_dblist($link));
404 * returns array with databases containing extended infos about them
406 * @param string $databases database
407 * @param boolean $force_stats retrieve stats also for MySQL < 5
408 * @param resource $link mysql link
409 * @param string $sort_by collumn to order by
410 * @param string $sort_order ASC or DESC
411 * @param integer $limit_offset starting offset for LIMIT
412 * @param bool|int $limit_count row count for LIMIT or true for $GLOBALS['cfg']['MaxDbList']
413 * @return array $databases
415 function PMA_DBI_get_databases_full($database = null, $force_stats = false,
416 $link = null, $sort_by = 'SCHEMA_NAME', $sort_order = 'ASC',
417 $limit_offset = 0, $limit_count = false)
419 $sort_order = strtoupper($sort_order);
421 if (true === $limit_count) {
422 $limit_count = $GLOBALS['cfg']['MaxDbList'];
425 // initialize to avoid errors when there are no databases
426 $databases = array();
428 $apply_limit_and_order_manual = true;
430 if (PMA_MYSQL_INT_VERSION >= 50002) {
432 * if $GLOBALS['cfg']['NaturalOrder'] is enabled, we cannot use LIMIT
433 * cause MySQL does not support natural ordering, we have to do it afterward
435 if ($GLOBALS['cfg']['NaturalOrder']) {
436 $limit = '';
437 } else {
438 if ($limit_count) {
439 $limit = ' LIMIT ' . $limit_count . ' OFFSET ' . $limit_offset;
442 $apply_limit_and_order_manual = false;
445 // get table information from information_schema
446 if ( $database ) {
447 $sql_where_schema = 'WHERE `SCHEMA_NAME` LIKE \''
448 . addslashes( $database ) . '\'';
449 } else {
450 $sql_where_schema = '';
453 // for PMA bc:
454 // `SCHEMA_FIELD_NAME` AS `SHOW_TABLE_STATUS_FIELD_NAME`
455 $sql = '
456 SELECT `information_schema`.`SCHEMATA`.*';
457 if ($force_stats) {
458 $sql .= ',
459 COUNT(`information_schema`.`TABLES`.`TABLE_SCHEMA`)
460 AS `SCHEMA_TABLES`,
461 SUM(`information_schema`.`TABLES`.`TABLE_ROWS`)
462 AS `SCHEMA_TABLE_ROWS`,
463 SUM(`information_schema`.`TABLES`.`DATA_LENGTH`)
464 AS `SCHEMA_DATA_LENGTH`,
465 SUM(`information_schema`.`TABLES`.`MAX_DATA_LENGTH`)
466 AS `SCHEMA_MAX_DATA_LENGTH`,
467 SUM(`information_schema`.`TABLES`.`INDEX_LENGTH`)
468 AS `SCHEMA_INDEX_LENGTH`,
469 SUM(`information_schema`.`TABLES`.`DATA_LENGTH`
470 + `information_schema`.`TABLES`.`INDEX_LENGTH`)
471 AS `SCHEMA_LENGTH`,
472 SUM(`information_schema`.`TABLES`.`DATA_FREE`)
473 AS `SCHEMA_DATA_FREE`';
475 $sql .= '
476 FROM `information_schema`.`SCHEMATA`';
477 if ($force_stats) {
478 $sql .= '
479 LEFT JOIN `information_schema`.`TABLES`
480 ON `information_schema`.`TABLES`.`TABLE_SCHEMA`
481 = `information_schema`.`SCHEMATA`.`SCHEMA_NAME`';
483 $sql .= '
484 ' . $sql_where_schema . '
485 GROUP BY `information_schema`.`SCHEMATA`.`SCHEMA_NAME`
486 ORDER BY ' . PMA_backquote($sort_by) . ' ' . $sort_order
487 . $limit;
488 $databases = PMA_DBI_fetch_result( $sql, 'SCHEMA_NAME', null, $link );
489 unset($sql_where_schema, $sql);
490 } else {
491 foreach ( PMA_DBI_get_dblist( $link ) as $database_name ) {
492 // MySQL forward compatibility
493 // so pma could use this array as if every server is of version >5.0
494 $databases[$database_name]['SCHEMA_NAME'] = $database_name;
496 if ( $force_stats ) {
497 require_once 'mysql_charsets.lib.php';
499 $databases[$database_name]['DEFAULT_COLLATION_NAME']
500 = PMA_getDbCollation( $database_name );
502 // get additonal info about tables
503 $databases[$database_name]['SCHEMA_TABLES'] = 0;
504 $databases[$database_name]['SCHEMA_TABLE_ROWS'] = 0;
505 $databases[$database_name]['SCHEMA_DATA_LENGTH'] = 0;
506 $databases[$database_name]['SCHEMA_MAX_DATA_LENGTH'] = 0;
507 $databases[$database_name]['SCHEMA_INDEX_LENGTH'] = 0;
508 $databases[$database_name]['SCHEMA_LENGTH'] = 0;
509 $databases[$database_name]['SCHEMA_DATA_FREE'] = 0;
511 $res = PMA_DBI_query('SHOW TABLE STATUS FROM ' . PMA_backquote( $database_name ) . ';');
512 while ( $row = PMA_DBI_fetch_assoc( $res ) ) {
513 $databases[$database_name]['SCHEMA_TABLES']++;
514 $databases[$database_name]['SCHEMA_TABLE_ROWS']
515 += $row['Rows'];
516 $databases[$database_name]['SCHEMA_DATA_LENGTH']
517 += $row['Data_length'];
518 $databases[$database_name]['SCHEMA_MAX_DATA_LENGTH']
519 += $row['Max_data_length'];
520 $databases[$database_name]['SCHEMA_INDEX_LENGTH']
521 += $row['Index_length'];
522 $databases[$database_name]['SCHEMA_DATA_FREE']
523 += $row['Data_free'];
524 $databases[$database_name]['SCHEMA_LENGTH']
525 += $row['Data_length'] + $row['Index_length'];
527 PMA_DBI_free_result( $res );
528 unset( $res );
534 * apply limit and order manually now
535 * (caused by older MySQL < 5 or $GLOBALS['cfg']['NaturalOrder'])
537 if ($apply_limit_and_order_manual) {
540 * first apply ordering
542 if ($GLOBALS['cfg']['NaturalOrder']) {
543 $sorter = 'strnatcasecmp';
544 } else {
545 $sorter = 'strcasecmp';
548 // produces f.e.:
549 // return -1 * strnatcasecmp($a["SCHEMA_TABLES"], $b["SCHEMA_TABLES"])
550 $sort_function = '
551 return ' . ($sort_order == 'ASC' ? 1 : -1) . ' * ' . $sorter . '($a["' . $sort_by . '"], $b["' . $sort_by . '"]);
554 usort($databases, create_function('$a, $b', $sort_function));
557 * now apply limit
559 if ($limit_count) {
560 $databases = array_slice($databases, $limit_offset, $limit_count);
564 return $databases;
568 * returns detailed array with all columns for given table in database,
569 * or all tables/databases
571 * @param string $database name of database
572 * @param string $table name of table to retrieve columns from
573 * @param string $column name of specific column
574 * @param mixed $link mysql link resource
576 function PMA_DBI_get_columns_full($database = null, $table = null,
577 $column = null, $link = null)
579 $columns = array();
581 if ( PMA_MYSQL_INT_VERSION >= 50002 ) {
582 $sql_wheres = array();
583 $array_keys = array();
585 // get columns information from information_schema
586 if ( null !== $database ) {
587 $sql_wheres[] = '`TABLE_SCHEMA` = \'' . addslashes($database) . '\' ';
588 } else {
589 $array_keys[] = 'TABLE_SCHEMA';
591 if ( null !== $table ) {
592 $sql_wheres[] = '`TABLE_NAME` = \'' . addslashes($table) . '\' ';
593 } else {
594 $array_keys[] = 'TABLE_NAME';
596 if ( null !== $column ) {
597 $sql_wheres[] = '`COLUMN_NAME` = \'' . addslashes($column) . '\' ';
598 } else {
599 $array_keys[] = 'COLUMN_NAME';
602 // for PMA bc:
603 // `[SCHEMA_FIELD_NAME]` AS `[SHOW_FULL_COLUMNS_FIELD_NAME]`
604 $sql = '
605 SELECT *,
606 `COLUMN_NAME` AS `Field`,
607 `COLUMN_TYPE` AS `Type`,
608 `COLLATION_NAME` AS `Collation`,
609 `IS_NULLABLE` AS `Null`,
610 `COLUMN_KEY` AS `Key`,
611 `COLUMN_DEFAULT` AS `Default`,
612 `EXTRA` AS `Extra`,
613 `PRIVILEGES` AS `Privileges`,
614 `COLUMN_COMMENT` AS `Comment`
615 FROM `information_schema`.`COLUMNS`';
616 if ( count($sql_wheres) ) {
617 $sql .= "\n" . ' WHERE ' . implode(' AND ', $sql_wheres);
620 $columns = PMA_DBI_fetch_result($sql, $array_keys, null, $link);
621 unset( $sql_wheres, $sql );
622 } else {
623 if ( null === $database ) {
624 $databases = PMA_DBI_get_dblist();
625 foreach ( $databases as $database ) {
626 $columns[$database] = PMA_DBI_get_columns_full($database, null,
627 null, $link);
629 return $columns;
630 } elseif ( null === $table ) {
631 $tables = PMA_DBI_get_tables($database);
632 foreach ( $tables as $table ) {
633 $columns[$table] = PMA_DBI_get_columns_full(
634 $database, $table, null, $link);
636 return $columns;
639 $sql = 'SHOW FULL COLUMNS FROM '
640 . PMA_backquote($database) . '.' . PMA_backquote($table);
641 if ( null !== $column ) {
642 $sql .= " LIKE '" . $column . "'";
645 $columns = PMA_DBI_fetch_result( $sql, 'Field', null, $link );
647 $ordinal_position = 1;
648 foreach ( $columns as $column_name => $each_column ) {
650 // MySQL forward compatibility
651 // so pma could use this array as if every server is of version >5.0
652 $columns[$column_name]['COLUMN_NAME'] =& $columns[$column_name]['Field'];
653 $columns[$column_name]['COLUMN_TYPE'] =& $columns[$column_name]['Type'];
654 $columns[$column_name]['COLLATION_NAME'] =& $columns[$column_name]['Collation'];
655 $columns[$column_name]['IS_NULLABLE'] =& $columns[$column_name]['Null'];
656 $columns[$column_name]['COLUMN_KEY'] =& $columns[$column_name]['Key'];
657 $columns[$column_name]['COLUMN_DEFAULT'] =& $columns[$column_name]['Default'];
658 $columns[$column_name]['EXTRA'] =& $columns[$column_name]['Extra'];
659 $columns[$column_name]['PRIVILEGES'] =& $columns[$column_name]['Privileges'];
660 $columns[$column_name]['COLUMN_COMMENT'] =& $columns[$column_name]['Comment'];
662 $columns[$column_name]['TABLE_CATALOG'] = null;
663 $columns[$column_name]['TABLE_SCHEMA'] = $database;
664 $columns[$column_name]['TABLE_NAME'] = $table;
665 $columns[$column_name]['ORDINAL_POSITION'] = $ordinal_position;
666 $columns[$column_name]['DATA_TYPE'] =
667 substr($columns[$column_name]['COLUMN_TYPE'], 0,
668 strpos($columns[$column_name]['COLUMN_TYPE'], '('));
669 // @TODO guess CHARACTER_MAXIMUM_LENGTH from COLUMN_TYPE
670 $columns[$column_name]['CHARACTER_MAXIMUM_LENGTH'] = null;
671 // @TODO guess CHARACTER_OCTET_LENGTH from CHARACTER_MAXIMUM_LENGTH
672 $columns[$column_name]['CHARACTER_OCTET_LENGTH'] = null;
673 $columns[$column_name]['NUMERIC_PRECISION'] = null;
674 $columns[$column_name]['NUMERIC_SCALE'] = null;
675 $columns[$column_name]['CHARACTER_SET_NAME'] =
676 substr($columns[$column_name]['COLLATION_NAME'], 0,
677 strpos($columns[$column_name]['COLLATION_NAME'], '_'));
679 $ordinal_position++;
682 if ( null !== $column ) {
683 reset($columns);
684 $columns = current($columns);
688 return $columns;
692 * @TODO should only return columns names, for more info use PMA_DBI_get_columns_full()
694 * @deprecated by PMA_DBI_get_columns() or PMA_DBI_get_columns_full()
695 * @param string $database name of database
696 * @param string $table name of table to retrieve columns from
697 * @param mixed $link mysql link resource
698 * @return array column info
700 function PMA_DBI_get_fields($database, $table, $link = null)
702 // here we use a try_query because when coming from
703 // tbl_create + tbl_properties.inc.php, the table does not exist
704 $fields = PMA_DBI_fetch_result(
705 'SHOW FULL COLUMNS
706 FROM ' . PMA_backquote($database) . '.' . PMA_backquote($table),
707 null, null, $link);
708 if ( ! is_array($fields) || count($fields) < 1 ) {
709 return false;
711 return $fields;
715 * array PMA_DBI_get_columns(string $database, string $table, bool $full = false, mysql db link $link = null)
717 * @param string $database name of database
718 * @param string $table name of table to retrieve columns from
719 * @param boolean $full wether to return full info or only column names
720 * @param mixed $link mysql link resource
721 * @return array column names
723 function PMA_DBI_get_columns($database, $table, $full = false, $link = null)
725 $fields = PMA_DBI_fetch_result(
726 'SHOW ' . ($full ? 'FULL' : '') . ' COLUMNS
727 FROM ' . PMA_backquote($database) . '.' . PMA_backquote($table),
728 'Fields', ($full ? null : 'Fields'), $link);
729 if ( ! is_array($fields) || count($fields) < 1 ) {
730 return false;
732 return $fields;
736 * returns value of given mysql server variable
738 * @param string $var mysql server variable name
739 * @param int $type PMA_DBI_GETVAR_SESSION|PMA_DBI_GETVAR_GLOBAL
740 * @param mixed $link mysql link resource|object
741 * @return mixed value for mysql server variable
743 function PMA_DBI_get_variable($var, $type = PMA_DBI_GETVAR_SESSION, $link = null)
745 if ($link === null) {
746 if (isset($GLOBALS['userlink'])) {
747 $link = $GLOBALS['userlink'];
748 } else {
749 return false;
752 if (PMA_MYSQL_INT_VERSION < 40002) {
753 $type = 0;
755 switch ($type) {
756 case PMA_DBI_GETVAR_SESSION:
757 $modifier = ' SESSION';
758 break;
759 case PMA_DBI_GETVAR_GLOBAL:
760 $modifier = ' GLOBAL';
761 break;
762 default:
763 $modifier = '';
765 return PMA_DBI_fetch_value(
766 'SHOW' . $modifier . ' VARIABLES LIKE \'' . $var . '\';', 0, 1, $link);
770 * @uses ./libraries/charset_conversion.lib.php
771 * @uses PMA_DBI_QUERY_STORE
772 * @uses PMA_REMOVED_NON_UTF_8
773 * @uses PMA_MYSQL_INT_VERSION
774 * @uses PMA_MYSQL_STR_VERSION
775 * @uses PMA_DBI_GETVAR_SESSION
776 * @uses PMA_DBI_fetch_value()
777 * @uses PMA_DBI_query()
778 * @uses PMA_DBI_get_variable()
779 * @uses $GLOBALS['collation_connection']
780 * @uses $GLOBALS['charset_connection']
781 * @uses $GLOBALS['available_languages']
782 * @uses $GLOBALS['mysql_charset_map']
783 * @uses $GLOBALS['charset']
784 * @uses $GLOBALS['lang']
785 * @uses $GLOBALS['cfg']['Lang']
786 * @uses $GLOBALS['cfg']['ColumnTypes']
787 * @uses defined()
788 * @uses explode()
789 * @uses sprintf()
790 * @uses intval()
791 * @uses define()
792 * @uses defined()
793 * @uses substr()
794 * @uses count()
795 * @param mixed $link mysql link resource|object
796 * @param boolean $is_controluser
798 function PMA_DBI_postConnect($link, $is_controluser = false)
800 if (!defined('PMA_MYSQL_INT_VERSION')) {
801 $mysql_version = PMA_DBI_fetch_value(
802 'SELECT VERSION()', 0, 0, $link, PMA_DBI_QUERY_STORE);
803 if ( $mysql_version ) {
804 $match = explode('.', $mysql_version);
805 define('PMA_MYSQL_INT_VERSION',
806 (int) sprintf('%d%02d%02d', $match[0], $match[1],
807 intval($match[2])));
808 define('PMA_MYSQL_STR_VERSION', $mysql_version);
809 unset($mysql_version, $match);
810 } else {
811 define('PMA_MYSQL_INT_VERSION', 32332);
812 define('PMA_MYSQL_STR_VERSION', '3.23.32');
816 if (!defined('PMA_ENGINE_KEYWORD')) {
817 if (PMA_MYSQL_INT_VERSION >= 40102) {
818 define('PMA_ENGINE_KEYWORD','ENGINE');
819 } else {
820 define('PMA_ENGINE_KEYWORD','TYPE');
824 if (PMA_MYSQL_INT_VERSION >= 40100) {
826 // If $lang is defined and we are on MySQL >= 4.1.x,
827 // we auto-switch the lang to its UTF-8 version (if it exists and user
828 // didn't force language)
829 if ( !empty($GLOBALS['lang'])
830 && (substr($GLOBALS['lang'], -5) != 'utf-8')
831 && !isset($GLOBALS['cfg']['Lang']) ) {
832 $lang_utf_8_version =
833 substr($GLOBALS['lang'], 0, strpos($GLOBALS['lang'], '-'))
834 . '-utf-8';
835 if (!empty($GLOBALS['available_languages'][$lang_utf_8_version])) {
836 $GLOBALS['lang'] = $lang_utf_8_version;
837 $GLOBALS['charset'] = 'utf-8';
838 define('PMA_LANG_RELOAD', 1);
842 // and we remove the non-UTF-8 choices to avoid confusion
843 if (!defined('PMA_REMOVED_NON_UTF_8')) {
844 foreach ( $GLOBALS['available_languages'] as $each_lang => $dummy ) {
845 if ( substr($each_lang, -5) != 'utf-8' ) {
846 unset( $GLOBALS['available_languages'][$each_lang] );
849 define('PMA_REMOVED_NON_UTF_8', 1);
852 $mysql_charset = $GLOBALS['mysql_charset_map'][$GLOBALS['charset']];
853 if ( $is_controluser
854 || empty($GLOBALS['collation_connection'])
855 || (strpos($GLOBALS['collation_connection'], '_')
856 ? substr($GLOBALS['collation_connection'], 0, strpos($GLOBALS['collation_connection'], '_'))
857 : $GLOBALS['collation_connection']) == $mysql_charset) {
859 PMA_DBI_query('SET NAMES ' . $mysql_charset . ';', $link,
860 PMA_DBI_QUERY_STORE);
861 } else {
862 PMA_DBI_query('SET CHARACTER SET ' . $mysql_charset . ';', $link,
863 PMA_DBI_QUERY_STORE);
865 if (!empty($GLOBALS['collation_connection'])) {
866 PMA_DBI_query('SET collation_connection = \'' . $GLOBALS['collation_connection'] . '\';',
867 $link, PMA_DBI_QUERY_STORE);
869 if (!$is_controluser) {
870 $GLOBALS['collation_connection'] = PMA_DBI_get_variable('collation_connection',
871 PMA_DBI_GETVAR_SESSION, $link);
872 $GLOBALS['charset_connection'] = PMA_DBI_get_variable('character_set_connection',
873 PMA_DBI_GETVAR_SESSION, $link);
876 // Add some field types to the list, this needs to be done once per session!
877 if ($GLOBALS['cfg']['ColumnTypes'][count($GLOBALS['cfg']['ColumnTypes']) - 1] != 'VARBINARY') {
878 $GLOBALS['cfg']['ColumnTypes'][] = 'BINARY';
879 $GLOBALS['cfg']['ColumnTypes'][] = 'VARBINARY';
882 } else {
883 require_once('./libraries/charset_conversion.lib.php');
888 * returns a single value from the given result or query,
889 * if the query or the result has more than one row or field
890 * the first field of the first row is returned
892 * <code>
893 * $sql = 'SELECT `name` FROM `user` WHERE `id` = 123';
894 * $user_name = PMA_DBI_fetch_value( $sql );
895 * // produces
896 * // $user_name = 'John Doe'
897 * </code>
899 * @uses is_string()
900 * @uses is_int()
901 * @uses PMA_DBI_try_query()
902 * @uses PMA_DBI_num_rows()
903 * @uses PMA_DBI_fetch_row()
904 * @uses PMA_DBI_fetch_assoc()
905 * @uses PMA_DBI_free_result()
906 * @param string|mysql_result $result query or mysql result
907 * @param integer $row_number row to fetch the value from,
908 * starting at 0, with 0 beeing default
909 * @param integer|string $field field to fetch the value from,
910 * starting at 0, with 0 beeing default
911 * @param resource $link mysql link
912 * @param mixed $options
913 * @return mixed value of first field in first row from result
914 * or false if not found
916 function PMA_DBI_fetch_value( $result, $row_number = 0, $field = 0, $link = null, $options = 0 ) {
917 $value = false;
919 if ( is_string( $result ) ) {
920 $result = PMA_DBI_try_query( $result, $link, $options | PMA_DBI_QUERY_STORE );
923 // return false if result is empty or false
924 // or requested row is larger than rows in result
925 if ( PMA_DBI_num_rows( $result ) < ( $row_number + 1 ) ) {
926 return $value;
929 // if $field is an integer use non associative mysql fetch function
930 if ( is_int( $field ) ) {
931 $fetch_function = 'PMA_DBI_fetch_row';
932 } else {
933 $fetch_function = 'PMA_DBI_fetch_assoc';
936 // get requested row
937 for ( $i = 0; $i <= $row_number; $i++ ) {
938 $row = $fetch_function( $result );
940 PMA_DBI_free_result( $result );
942 // return requested field
943 if ( isset( $row[$field] ) ) {
944 $value = $row[$field];
946 unset( $row );
948 return $value;
952 * returns only the first row from the result
954 * <code>
955 * $sql = 'SELECT * FROM `user` WHERE `id` = 123';
956 * $user = PMA_DBI_fetch_single_row( $sql );
957 * // produces
958 * // $user = array( 'id' => 123, 'name' => 'John Doe' )
959 * </code>
961 * @uses is_string()
962 * @uses PMA_DBI_try_query()
963 * @uses PMA_DBI_num_rows()
964 * @uses PMA_DBI_fetch_row()
965 * @uses PMA_DBI_fetch_assoc()
966 * @uses PMA_DBI_fetch_array()
967 * @uses PMA_DBI_free_result()
968 * @param string|mysql_result $result query or mysql result
969 * @param string $type NUM|ASSOC|BOTH
970 * returned array should either numeric
971 * associativ or booth
972 * @param resource $link mysql link
973 * @param mixed $options
974 * @return array|boolean first row from result
975 * or false if result is empty
977 function PMA_DBI_fetch_single_row( $result, $type = 'ASSOC', $link = null, $options = 0 ) {
978 if ( is_string( $result ) ) {
979 $result = PMA_DBI_try_query( $result, $link, $options | PMA_DBI_QUERY_STORE );
982 // return null if result is empty or false
983 if ( ! PMA_DBI_num_rows( $result ) ) {
984 return false;
987 switch ( $type ) {
988 case 'NUM' :
989 $fetch_function = 'PMA_DBI_fetch_row';
990 break;
991 case 'ASSOC' :
992 $fetch_function = 'PMA_DBI_fetch_assoc';
993 break;
994 case 'BOTH' :
995 default :
996 $fetch_function = 'PMA_DBI_fetch_array';
997 break;
1000 $row = $fetch_function( $result );
1001 PMA_DBI_free_result( $result );
1002 return $row;
1006 * returns all rows in the resultset in one array
1008 * <code>
1009 * $sql = 'SELECT * FROM `user`';
1010 * $users = PMA_DBI_fetch_result( $sql );
1011 * // produces
1012 * // $users[] = array( 'id' => 123, 'name' => 'John Doe' )
1014 * $sql = 'SELECT `id`, `name` FROM `user`';
1015 * $users = PMA_DBI_fetch_result( $sql, 'id' );
1016 * // produces
1017 * // $users['123'] = array( 'id' => 123, 'name' => 'John Doe' )
1019 * $sql = 'SELECT `id`, `name` FROM `user`';
1020 * $users = PMA_DBI_fetch_result( $sql, 0 );
1021 * // produces
1022 * // $users['123'] = array( 0 => 123, 1 => 'John Doe' )
1024 * $sql = 'SELECT `id`, `name` FROM `user`';
1025 * $users = PMA_DBI_fetch_result( $sql, 'id', 'name' );
1026 * // or
1027 * $users = PMA_DBI_fetch_result( $sql, 0, 1 );
1028 * // produces
1029 * // $users['123'] = 'John Doe'
1031 * $sql = 'SELECT `name` FROM `user`';
1032 * $users = PMA_DBI_fetch_result( $sql );
1033 * // produces
1034 * // $users[] = 'John Doe'
1035 * </code>
1037 * @uses is_string()
1038 * @uses is_int()
1039 * @uses PMA_DBI_try_query()
1040 * @uses PMA_DBI_num_rows()
1041 * @uses PMA_DBI_num_fields()
1042 * @uses PMA_DBI_fetch_row()
1043 * @uses PMA_DBI_fetch_assoc()
1044 * @uses PMA_DBI_free_result()
1045 * @param string|mysql_result $result query or mysql result
1046 * @param string|integer $key field-name or offset
1047 * used as key for array
1048 * @param string|integer $value value-name or offset
1049 * used as value for array
1050 * @param resource $link mysql link
1051 * @param mixed $options
1052 * @return array resultrows or values indexed by $key
1054 function PMA_DBI_fetch_result( $result, $key = null, $value = null,
1055 $link = null, $options = 0 )
1057 $resultrows = array();
1059 if ( is_string($result) ) {
1060 $result = PMA_DBI_try_query($result, $link, $options);
1063 // return empty array if result is empty or false
1064 if ( ! $result ) {
1065 return $resultrows;
1068 $fetch_function = 'PMA_DBI_fetch_assoc';
1070 // no nested array if only one field is in result
1071 if ( null === $key && 1 === PMA_DBI_num_fields($result) ) {
1072 $value = 0;
1073 $fetch_function = 'PMA_DBI_fetch_row';
1076 // if $key is an integer use non associative mysql fetch function
1077 if ( is_int($key) ) {
1078 $fetch_function = 'PMA_DBI_fetch_row';
1081 if ( null === $key && null === $value ) {
1082 while ( $row = $fetch_function($result) ) {
1083 $resultrows[] = $row;
1085 } elseif ( null === $key ) {
1086 while ( $row = $fetch_function($result) ) {
1087 $resultrows[] = $row[$value];
1089 } elseif ( null === $value ) {
1090 if ( is_array($key) ) {
1091 while ( $row = $fetch_function($result) ) {
1092 $result_target =& $resultrows;
1093 foreach ( $key as $key_index ) {
1094 if ( ! isset( $result_target[$row[$key_index]] ) ) {
1095 $result_target[$row[$key_index]] = array();
1097 $result_target =& $result_target[$row[$key_index]];
1099 $result_target = $row;
1101 } else {
1102 while ( $row = $fetch_function($result) ) {
1103 $resultrows[$row[$key]] = $row;
1106 } else {
1107 if ( is_array($key) ) {
1108 while ( $row = $fetch_function($result) ) {
1109 $result_target =& $resultrows;
1110 foreach ( $key as $key_index ) {
1111 if ( ! isset( $result_target[$row[$key_index]] ) ) {
1112 $result_target[$row[$key_index]] = array();
1114 $result_target =& $result_target[$row[$key_index]];
1116 $result_target = $row[$value];
1118 } else {
1119 while ( $row = $fetch_function($result) ) {
1120 $resultrows[$row[$key]] = $row[$value];
1125 PMA_DBI_free_result($result);
1126 return $resultrows;
1130 * return default table engine for given database
1132 * @return string default table engine
1134 function PMA_DBI_get_default_engine()
1136 if ( PMA_MYSQL_INT_VERSION > 50002 ) {
1137 return PMA_DBI_fetch_value( 'SHOW VARIABLES LIKE \'storage_engine\';', 0, 1 );
1138 } else {
1139 return PMA_DBI_fetch_value( 'SHOW VARIABLES LIKE \'table_type\';', 0, 1 );
1144 * Get supported SQL compatibility modes
1146 * @return array supported SQL compatibility modes
1148 function PMA_DBI_getCompatibilities()
1150 if (PMA_MYSQL_INT_VERSION < 40100) {
1151 return array();
1153 $compats = array('NONE');
1154 if (PMA_MYSQL_INT_VERSION >= 40101) {
1155 $compats[] = 'ANSI';
1156 $compats[] = 'DB2';
1157 $compats[] = 'MAXDB';
1158 $compats[] = 'MYSQL323';
1159 $compats[] = 'MYSQL40';
1160 $compats[] = 'MSSQL';
1161 $compats[] = 'ORACLE';
1162 $compats[] = 'POSTGRESQL';
1163 if (PMA_MYSQL_INT_VERSION >= 50002) {
1164 $compats[] = 'TRADITIONAL';
1167 return $compats;
1172 * returns true (int > 0) if current user is superuser
1173 * otherwise 0
1175 * @return integer $is_superuser
1177 function PMA_isSuperuser() {
1178 return PMA_DBI_try_query( 'SELECT COUNT(*) FROM mysql.user',
1179 $GLOBALS['userlink'], PMA_DBI_QUERY_STORE );