Translated using Weblate (Italian)
[phpmyadmin.git] / sql.php
blobab7c4d82072fb7431d7af15d4382b1cc28482028
1 <?php
2 /* vim: set expandtab sw=4 ts=4 sts=4: */
3 /**
4 * SQL executor
6 * @todo we must handle the case if sql.php is called directly with a query
7 * that returns 0 rows - to prevent cyclic redirects or includes
8 * @package PhpMyAdmin
9 */
11 /**
12 * Gets some core libraries
14 require_once 'libraries/common.inc.php';
15 require_once 'libraries/Table.class.php';
16 require_once 'libraries/Header.class.php';
17 require_once 'libraries/check_user_privileges.lib.php';
18 require_once 'libraries/bookmark.lib.php';
20 $response = PMA_Response::getInstance();
21 $header = $response->getHeader();
22 $scripts = $header->getScripts();
23 $scripts->addFile('jquery/jquery-ui-timepicker-addon.js');
24 $scripts->addFile('tbl_change.js');
25 // the next one needed because sql.php may do a "goto" to tbl_structure.php
26 $scripts->addFile('tbl_structure.js');
27 $scripts->addFile('indexes.js');
28 $scripts->addFile('gis_data_editor.js');
30 /**
31 * Set ajax_reload in the response if it was already set
33 if (isset($ajax_reload) && $ajax_reload['reload'] === true) {
34 $response->addJSON('ajax_reload', $ajax_reload);
37 /**
38 * Sets globals from $_POST
40 $post_params = array(
41 'bkm_all_users',
42 'fields',
43 'store_bkm'
45 foreach ($post_params as $one_post_param) {
46 if (isset($_POST[$one_post_param])) {
47 $GLOBALS[$one_post_param] = $_POST[$one_post_param];
51 /**
52 * Sets globals from $_GET
54 $get_params = array(
55 'id_bookmark',
56 'label',
57 'sql_query'
59 foreach ($get_params as $one_get_param) {
60 if (isset($_GET[$one_get_param])) {
61 $GLOBALS[$one_get_param] = $_GET[$one_get_param];
66 if (isset($_REQUEST['printview'])) {
67 $GLOBALS['printview'] = $_REQUEST['printview'];
70 if (isset($_SESSION['profiling'])) {
71 $response = PMA_Response::getInstance();
72 $header = $response->getHeader();
73 $scripts = $header->getScripts();
74 /* < IE 9 doesn't support canvas natively */
75 if (PMA_USR_BROWSER_AGENT == 'IE' && PMA_USR_BROWSER_VER < 9) {
76 $scripts->addFile('canvg/flashcanvas.js');
78 $scripts->addFile('jqplot/jquery.jqplot.js');
79 $scripts->addFile('jqplot/plugins/jqplot.pieRenderer.js');
80 $scripts->addFile('canvg/canvg.js');
83 if (!isset($_SESSION['is_multi_query'])) {
84 $_SESSION['is_multi_query'] = false;
87 /**
88 * Defines the url to return to in case of error in a sql statement
90 // Security checkings
91 if (! empty($goto)) {
92 $is_gotofile = preg_replace('@^([^?]+).*$@s', '\\1', $goto);
93 if (! @file_exists('' . $is_gotofile)) {
94 unset($goto);
95 } else {
96 $is_gotofile = ($is_gotofile == $goto);
98 } else {
99 if (empty($table)) {
100 $goto = $cfg['DefaultTabDatabase'];
101 } else {
102 $goto = $cfg['DefaultTabTable'];
104 $is_gotofile = true;
105 } // end if
107 if (! isset($err_url)) {
108 $err_url = (! empty($back) ? $back : $goto)
109 . '?' . PMA_generate_common_url($db)
110 . ((strpos(' ' . $goto, 'db_') != 1 && strlen($table))
111 ? '&amp;table=' . urlencode($table)
112 : ''
114 } // end if
116 // Coming from a bookmark dialog
117 if (isset($fields['query'])) {
118 $sql_query = $fields['query'];
121 // This one is just to fill $db
122 if (isset($fields['dbase'])) {
123 $db = $fields['dbase'];
127 * During grid edit, if we have a relational field, show the dropdown for it
129 * Logic taken from libraries/DisplayResults.class.php
131 * This doesn't seem to be the right place to do this, but I can't think of any
132 * better place either.
134 if (isset($_REQUEST['get_relational_values'])
135 && $_REQUEST['get_relational_values'] == true
137 $column = $_REQUEST['column'];
138 $foreigners = PMA_getForeigners($db, $table, $column);
140 $display_field = PMA_getDisplayField(
141 $foreigners[$column]['foreign_db'],
142 $foreigners[$column]['foreign_table']
145 $foreignData = PMA_getForeignData($foreigners, $column, false, '', '');
147 if ($_SESSION['tmp_user_values']['relational_display'] == 'D'
148 && isset($display_field)
149 && strlen($display_field)
150 && isset($_REQUEST['relation_key_or_display_column'])
151 && $_REQUEST['relation_key_or_display_column']
153 $curr_value = $_REQUEST['relation_key_or_display_column'];
154 } else {
155 $curr_value = $_REQUEST['curr_value'];
157 if ($foreignData['disp_row'] == null) {
158 //Handle the case when number of values
159 //is more than $cfg['ForeignKeyMaxLimit']
160 $_url_params = array(
161 'db' => $db,
162 'table' => $table,
163 'field' => $column
166 $dropdown = '<span class="curr_value">'
167 . htmlspecialchars($_REQUEST['curr_value'])
168 . '</span>'
169 . '<a href="browse_foreigners.php'
170 . PMA_generate_common_url($_url_params) . '"'
171 . ' target="_blank" class="browse_foreign" ' .'>'
172 . __('Browse foreign values')
173 . '</a>';
174 } else {
175 $dropdown = PMA_foreignDropdown(
176 $foreignData['disp_row'],
177 $foreignData['foreign_field'],
178 $foreignData['foreign_display'],
179 $curr_value,
180 $cfg['ForeignKeyMaxLimit']
182 $dropdown = '<select>' . $dropdown . '</select>';
185 $response = PMA_Response::getInstance();
186 $response->addJSON('dropdown', $dropdown);
187 exit;
191 * Just like above, find possible values for enum fields during grid edit.
193 * Logic taken from libraries/DisplayResults.class.php
195 if (isset($_REQUEST['get_enum_values']) && $_REQUEST['get_enum_values'] == true) {
196 $field_info_query = PMA_DBI_get_columns_sql($db, $table, $_REQUEST['column']);
198 $field_info_result = PMA_DBI_fetch_result(
199 $field_info_query, null, null, null, PMA_DBI_QUERY_STORE
202 $values = PMA_Util::parseEnumSetValues($field_info_result[0]['Type']);
204 $dropdown = '<option value="">&nbsp;</option>';
205 foreach ($values as $value) {
206 $dropdown .= '<option value="' . $value . '"';
207 if ($value == $_REQUEST['curr_value']) {
208 $dropdown .= ' selected="selected"';
210 $dropdown .= '>' . $value . '</option>';
213 $dropdown = '<select>' . $dropdown . '</select>';
215 $response = PMA_Response::getInstance();
216 $response->addJSON('dropdown', $dropdown);
217 exit;
221 * Find possible values for set fields during grid edit.
223 if (isset($_REQUEST['get_set_values']) && $_REQUEST['get_set_values'] == true) {
224 $field_info_query = PMA_DBI_get_columns_sql($db, $table, $_REQUEST['column']);
226 $field_info_result = PMA_DBI_fetch_result(
227 $field_info_query, null, null, null, PMA_DBI_QUERY_STORE
230 $values = PMA_Util::parseEnumSetValues($field_info_result[0]['Type']);
232 $select = '';
234 //converts characters of $_REQUEST['curr_value'] to HTML entities
235 $converted_curr_value = htmlentities(
236 $_REQUEST['curr_value'], ENT_COMPAT, "UTF-8"
239 $selected_values = explode(',', $converted_curr_value);
241 foreach ($values as $value) {
242 $select .= '<option value="' . $value . '"';
243 if ($value == $converted_curr_value
244 || in_array($value, $selected_values, true)
246 $select .= ' selected="selected" ';
248 $select .= '>' . $value . '</option>';
251 $select_size = (sizeof($values) > 10) ? 10 : sizeof($values);
252 $select = '<select multiple="multiple" size="' . $select_size . '">'
253 . $select . '</select>';
255 $response = PMA_Response::getInstance();
256 $response->addJSON('select', $select);
257 exit;
261 * Check ajax request to set the column order
263 if (isset($_REQUEST['set_col_prefs']) && $_REQUEST['set_col_prefs'] == true) {
264 $pmatable = new PMA_Table($table, $db);
265 $retval = false;
267 // set column order
268 if (isset($_REQUEST['col_order'])) {
269 $col_order = explode(',', $_REQUEST['col_order']);
270 $retval = $pmatable->setUiProp(
271 PMA_Table::PROP_COLUMN_ORDER,
272 $col_order,
273 $_REQUEST['table_create_time']
275 if (gettype($retval) != 'boolean') {
276 $response = PMA_Response::getInstance();
277 $response->isSuccess(false);
278 $response->addJSON('message', $retval->getString());
279 exit;
283 // set column visibility
284 if ($retval === true && isset($_REQUEST['col_visib'])) {
285 $col_visib = explode(',', $_REQUEST['col_visib']);
286 $retval = $pmatable->setUiProp(
287 PMA_Table::PROP_COLUMN_VISIB, $col_visib,
288 $_REQUEST['table_create_time']
290 if (gettype($retval) != 'boolean') {
291 $response = PMA_Response::getInstance();
292 $response->isSuccess(false);
293 $response->addJSON('message', $retval->getString());
294 exit;
298 $response = PMA_Response::getInstance();
299 $response->isSuccess($retval == true);
300 exit;
303 // Default to browse if no query set and we have table
304 // (needed for browsing from DefaultTabTable)
305 if (empty($sql_query) && strlen($table) && strlen($db)) {
306 include_once 'libraries/bookmark.lib.php';
307 $book_sql_query = PMA_Bookmark_get(
308 $db,
309 '\'' . PMA_Util::sqlAddSlashes($table) . '\'',
310 'label',
311 false,
312 true
315 if (! empty($book_sql_query)) {
316 $GLOBALS['using_bookmark_message'] = PMA_message::notice(
317 __('Using bookmark "%s" as default browse query.')
319 $GLOBALS['using_bookmark_message']->addParam($table);
320 $GLOBALS['using_bookmark_message']->addMessage(
321 PMA_Util::showDocu('faq', 'faq6-22')
323 $sql_query = $book_sql_query;
324 } else {
325 $sql_query = 'SELECT * FROM ' . PMA_Util::backquote($table);
327 unset($book_sql_query);
329 // set $goto to what will be displayed if query returns 0 rows
330 $goto = '';
331 } else {
332 // Now we can check the parameters
333 PMA_Util::checkParameters(array('sql_query'));
336 // instead of doing the test twice
337 $is_drop_database = preg_match(
338 '/DROP[[:space:]]+(DATABASE|SCHEMA)[[:space:]]+/i',
339 $sql_query
343 * Check rights in case of DROP DATABASE
345 * This test may be bypassed if $is_js_confirmed = 1 (already checked with js)
346 * but since a malicious user may pass this variable by url/form, we don't take
347 * into account this case.
349 if (! defined('PMA_CHK_DROP')
350 && ! $cfg['AllowUserDropDatabase']
351 && $is_drop_database
352 && ! $is_superuser
354 PMA_Util::mysqlDie(
355 __('"DROP DATABASE" statements are disabled.'),
358 $err_url
360 } // end if
362 // Include PMA_Index class for use in PMA_DisplayResults class
363 require_once './libraries/Index.class.php';
365 require_once 'libraries/DisplayResults.class.php';
367 $displayResultsObject = new PMA_DisplayResults(
368 $GLOBALS['db'], $GLOBALS['table'], $GLOBALS['goto'], $GLOBALS['sql_query']
371 $displayResultsObject->setConfigParamsForDisplayTable();
374 * Need to find the real end of rows?
376 if (isset($find_real_end) && $find_real_end) {
377 $unlim_num_rows = PMA_Table::countRecords($db, $table, true);
378 $_SESSION['tmp_user_values']['pos'] = @((ceil(
379 $unlim_num_rows / $_SESSION['tmp_user_values']['max_rows']
380 ) - 1) * $_SESSION['tmp_user_values']['max_rows']);
385 * Bookmark add
387 if (isset($store_bkm)) {
388 $result = PMA_Bookmark_save(
389 $fields,
390 (isset($bkm_all_users) && $bkm_all_users == 'true' ? true : false)
392 $response = PMA_Response::getInstance();
393 if ($response->isAjax()) {
394 if ($result) {
395 $msg = PMA_message::success(__('Bookmark %s created'));
396 $msg->addParam($fields['label']);
397 $response->addJSON('message', $msg);
398 } else {
399 $msg = PMA_message::error(__('Bookmark not created'));
400 $response->isSuccess(false);
401 $response->addJSON('message', $msg);
403 exit;
404 } else {
405 // go back to sql.php to redisplay query; do not use &amp; in this case:
406 PMA_sendHeaderLocation(
407 $cfg['PmaAbsoluteUri'] . $goto . '&label=' . $fields['label']
410 } // end if
413 * Parse and analyze the query
415 require_once 'libraries/parse_analyze.lib.php';
418 * Sets or modifies the $goto variable if required
420 if ($goto == 'sql.php') {
421 $is_gotofile = false;
422 $goto = 'sql.php?'
423 . PMA_generate_common_url($db, $table)
424 . '&amp;sql_query=' . urlencode($sql_query);
425 } // end if
428 * Go back to further page if table should not be dropped
430 if (isset($_REQUEST['btnDrop']) && $_REQUEST['btnDrop'] == __('No')) {
431 if (! empty($back)) {
432 $goto = $back;
434 if ($is_gotofile) {
435 if (strpos($goto, 'db_') === 0 && strlen($table)) {
436 $table = '';
438 $active_page = $goto;
439 include '' . PMA_securePath($goto);
440 } else {
441 PMA_sendHeaderLocation(
442 $cfg['PmaAbsoluteUri'] . str_replace('&amp;', '&', $goto)
445 exit();
446 } // end if
450 * Displays the confirm page if required
452 * This part of the script is bypassed if $is_js_confirmed = 1 (already checked
453 * with js) because possible security issue is not so important here: at most,
454 * the confirm message isn't displayed.
456 * Also bypassed if only showing php code.or validating a SQL query
458 // if we are coming from a "Create PHP code" or a "Without PHP Code"
459 // dialog, we won't execute the query anyway, so don't confirm
460 if (! $cfg['Confirm']
461 || isset($_REQUEST['is_js_confirmed'])
462 || isset($_REQUEST['btnDrop'])
463 || isset($GLOBALS['show_as_php'])
464 || ! empty($GLOBALS['validatequery'])
466 $do_confirm = false;
467 } else {
468 $do_confirm = isset($analyzed_sql[0]['queryflags']['need_confirm']);
471 if ($do_confirm) {
472 $stripped_sql_query = $sql_query;
473 $input = '<input type="hidden" name="%s" value="%s" />';
474 $output = '';
475 if ($is_drop_database) {
476 $output .= '<h1 class="error">';
477 $output .= __('You are about to DESTROY a complete database!');
478 $output .= '</h1>';
480 $form = '<form class="disableAjax" action="sql.php" method="post">';
481 $form .= PMA_generate_common_hidden_inputs($db, $table);
483 $form .= sprintf(
484 $input, 'sql_query', htmlspecialchars($sql_query)
486 $form .= sprintf(
487 $input, 'message_to_show',
488 (isset($message_to_show) ? PMA_sanitize($message_to_show, true) : '')
490 $form .= sprintf(
491 $input, 'goto', $goto
493 $form .= sprintf(
494 $input, 'back',
495 (isset($back) ? PMA_sanitize($back, true) : '')
497 $form .= sprintf(
498 $input, 'reload',
499 (isset($reload) ? PMA_sanitize($reload, true) : '')
501 $form .= sprintf(
502 $input, 'purge',
503 (isset($purge) ? PMA_sanitize($purge, true) : '')
505 $form .= sprintf(
506 $input, 'dropped_column',
507 (isset($dropped_column) ? PMA_sanitize($dropped_column, true) : '')
509 $form .= sprintf(
510 $input, 'show_query',
511 (isset($message_to_show) ? PMA_sanitize($show_query, true) : '')
513 $form = str_replace('%', '%%', $form) . '%s</form>';
515 $output .='<fieldset class="confirmation">'
516 .'<legend>'
517 . __('Do you really want to execute the following query?')
518 . '</legend>'
519 .'<code>' . htmlspecialchars($stripped_sql_query) . '</code>'
520 .'</fieldset>'
521 .'<fieldset class="tblFooters">';
523 $yes_input = sprintf($input, 'btnDrop', __('Yes'));
524 $yes_input .= '<input type="submit" value="' . __('Yes') . '" id="buttonYes" />';
525 $no_input = sprintf($input, 'btnDrop', __('No'));
526 $no_input .= '<input type="submit" value="' . __('No') . '" id="buttonNo" />';
528 $output .= sprintf($form, $yes_input);
529 $output .= sprintf($form, $no_input);
531 $output .='</fieldset>';
532 $output .= '';
534 PMA_Response::getInstance()->addHTML($output);
536 exit;
537 } // end if $do_confirm
540 // Defines some variables
541 // A table has to be created, renamed, dropped -> navi frame should be reloaded
543 * @todo use the parser/analyzer
546 if (empty($reload)
547 && preg_match('/^(CREATE|ALTER|DROP)\s+(VIEW|TABLE|DATABASE|SCHEMA)\s+/i', $sql_query)
549 $reload = 1;
552 // $is_group added for use in calculation of total number of rows.
553 // $is_count is changed for more correct "LIMIT" clause
554 // appending in queries like
555 // "SELECT COUNT(...) FROM ... GROUP BY ..."
558 * @todo detect all this with the parser, to avoid problems finding
559 * those strings in comments or backquoted identifiers
561 list($is_group, $is_func, $is_count, $is_export, $is_analyse, $is_explain,
562 $is_delete, $is_affected, $is_insert, $is_replace, $is_show, $is_maint)
563 = PMA_getDisplayPropertyParams(
564 $sql_query, $is_select
567 // assign default full_sql_query
568 $full_sql_query = $sql_query;
570 // Handle remembered sorting order, only for single table query
571 if ($GLOBALS['cfg']['RememberSorting']
572 && ! ($is_count || $is_export || $is_func || $is_analyse)
573 && isset($analyzed_sql[0]['select_expr'])
574 && (count($analyzed_sql[0]['select_expr']) == 0)
575 && isset($analyzed_sql[0]['queryflags']['select_from'])
576 && count($analyzed_sql[0]['table_ref']) == 1
578 PMA_handleSortOrder($db, $table, $analyzed_sql, $full_sql_query);
581 $sql_limit_to_append = '';
582 // Do append a "LIMIT" clause?
583 if (($_SESSION['tmp_user_values']['max_rows'] != 'all')
584 && ! ($is_count || $is_export || $is_func || $is_analyse)
585 && isset($analyzed_sql[0]['queryflags']['select_from'])
586 && ! isset($analyzed_sql[0]['queryflags']['offset'])
587 && empty($analyzed_sql[0]['limit_clause'])
589 $sql_limit_to_append = ' LIMIT ' . $_SESSION['tmp_user_values']['pos']
590 . ', ' . $_SESSION['tmp_user_values']['max_rows'] . " ";
591 $full_sql_query = PMA_getSqlWithLimitClause(
592 $full_sql_query,
593 $analyzed_sql,
594 $sql_limit_to_append
598 * @todo pretty printing of this modified query
600 if (isset($display_query)) {
601 // if the analysis of the original query revealed that we found
602 // a section_after_limit, we now have to analyze $display_query
603 // to display it correctly
605 if (! empty($analyzed_sql[0]['section_after_limit'])
606 && trim($analyzed_sql[0]['section_after_limit']) != ';'
608 $analyzed_display_query = PMA_SQP_analyze(
609 PMA_SQP_parse($display_query)
611 $display_query = $analyzed_display_query[0]['section_before_limit']
612 . "\n" . $sql_limit_to_append
613 . $analyzed_display_query[0]['section_after_limit'];
618 if (strlen($db)) {
619 PMA_DBI_select_db($db);
622 // E x e c u t e t h e q u e r y
624 // Only if we didn't ask to see the php code
625 if (isset($GLOBALS['show_as_php']) || ! empty($GLOBALS['validatequery'])) {
626 unset($result);
627 $num_rows = 0;
628 $unlim_num_rows = 0;
629 } else {
630 if (isset($_SESSION['profiling']) && PMA_Util::profilingSupported()) {
631 PMA_DBI_query('SET PROFILING=1;');
634 // Measure query time.
635 $querytime_before = array_sum(explode(' ', microtime()));
637 $result = @PMA_DBI_try_query($full_sql_query, null, PMA_DBI_QUERY_STORE);
639 // If a stored procedure was called, there may be more results that are
640 // queued up and waiting to be flushed from the buffer. So let's do that.
641 do {
642 PMA_DBI_store_result();
643 if (! PMA_DBI_more_results()) {
644 break;
646 } while (PMA_DBI_next_result());
648 $is_procedure = false;
650 // Since multiple query execution is anyway handled,
651 // ignore the WHERE clause of the first sql statement
652 // which might contain a phrase like 'call '
653 if (preg_match("/\bcall\b/i", $full_sql_query)
654 && empty($analyzed_sql[0]['where_clause'])
656 $is_procedure = true;
659 $querytime_after = array_sum(explode(' ', microtime()));
661 $GLOBALS['querytime'] = $querytime_after - $querytime_before;
663 // Displays an error message if required and stop parsing the script
664 $error = PMA_DBI_getError();
665 if ($error) {
666 if ($is_gotofile) {
667 if (strpos($goto, 'db_') === 0 && strlen($table)) {
668 $table = '';
670 $active_page = $goto;
671 $message = PMA_Message::rawError($error);
673 if ($GLOBALS['is_ajax_request'] == true) {
674 $response = PMA_Response::getInstance();
675 $response->isSuccess(false);
676 $response->addJSON('message', $message);
677 exit;
681 * Go to target path.
683 include '' . PMA_securePath($goto);
684 } else {
685 $full_err_url = $err_url;
686 if (preg_match('@^(db|tbl)_@', $err_url)) {
687 $full_err_url .= '&amp;show_query=1&amp;sql_query='
688 . urlencode($sql_query);
690 PMA_Util::mysqlDie($error, $full_sql_query, '', $full_err_url);
692 exit;
694 unset($error);
696 // If there are no errors and bookmarklabel was given,
697 // store the query as a bookmark
698 if (! empty($bkm_label) && ! empty($import_text)) {
699 include_once 'libraries/bookmark.lib.php';
700 $bfields = array(
701 'dbase' => $db,
702 'user' => $cfg['Bookmark']['user'],
703 'query' => urlencode($import_text),
704 'label' => $bkm_label
707 // Should we replace bookmark?
708 if (isset($bkm_replace)) {
709 $bookmarks = PMA_Bookmark_getList($db);
710 foreach ($bookmarks as $key => $val) {
711 if ($val == $bkm_label) {
712 PMA_Bookmark_delete($db, $key);
717 PMA_Bookmark_save($bfields, isset($bkm_all_users));
719 $bookmark_created = true;
720 } // end store bookmarks
722 // Gets the number of rows affected/returned
723 // (This must be done immediately after the query because
724 // mysql_affected_rows() reports about the last query done)
726 if (! $is_affected) {
727 $num_rows = ($result) ? @PMA_DBI_num_rows($result) : 0;
728 } elseif (! isset($num_rows)) {
729 $num_rows = @PMA_DBI_affected_rows();
732 // Grabs the profiling results
733 if (isset($_SESSION['profiling']) && PMA_Util::profilingSupported()) {
734 $profiling_results = PMA_DBI_fetch_result('SHOW PROFILE;');
737 // Checks if the current database has changed
738 // This could happen if the user sends a query like "USE `database`;"
740 * commented out auto-switching to active database - really required?
741 * bug #2558 win: table list disappears (mixed case db names)
742 * https://sourceforge.net/p/phpmyadmin/bugs/2558/
743 * @todo RELEASE test and comit or rollback before release
744 $current_db = PMA_DBI_fetch_value('SELECT DATABASE()');
745 if ($db !== $current_db) {
746 $db = $current_db;
747 $reload = 1;
749 unset($current_db);
752 // tmpfile remove after convert encoding appended by Y.Kawada
753 if (function_exists('PMA_kanji_file_conv')
754 && (isset($textfile) && file_exists($textfile))
756 unlink($textfile);
759 // Counts the total number of rows for the same 'SELECT' query without the
760 // 'LIMIT' clause that may have been programatically added
762 $justBrowsing = false;
763 if (empty($sql_limit_to_append)) {
764 $unlim_num_rows = $num_rows;
765 // if we did not append a limit, set this to get a correct
766 // "Showing rows..." message
767 //$_SESSION['tmp_user_values']['max_rows'] = 'all';
768 } elseif ($is_select) {
770 // c o u n t q u e r y
772 // If we are "just browsing", there is only one table,
773 // and no WHERE clause (or just 'WHERE 1 '),
774 // we do a quick count (which uses MaxExactCount) because
775 // SQL_CALC_FOUND_ROWS is not quick on large InnoDB tables
777 // However, do not count again if we did it previously
778 // due to $find_real_end == true
779 if (! $is_group
780 && ! isset($analyzed_sql[0]['queryflags']['union'])
781 && ! isset($analyzed_sql[0]['queryflags']['distinct'])
782 && ! isset($analyzed_sql[0]['table_ref'][1]['table_name'])
783 && (empty($analyzed_sql[0]['where_clause'])
784 || $analyzed_sql[0]['where_clause'] == '1 ')
785 && ! isset($find_real_end)
787 // "j u s t b r o w s i n g"
788 $justBrowsing = true;
789 $unlim_num_rows = PMA_Table::countRecords($db, $table);
791 } else { // n o t " j u s t b r o w s i n g "
793 // add select expression after the SQL_CALC_FOUND_ROWS
795 // for UNION, just adding SQL_CALC_FOUND_ROWS
796 // after the first SELECT works.
798 // take the left part, could be:
799 // SELECT
800 // (SELECT
801 $count_query = PMA_SQP_formatHtml(
802 $parsed_sql,
803 'query_only',
805 $analyzed_sql[0]['position_of_first_select'] + 1
807 $count_query .= ' SQL_CALC_FOUND_ROWS ';
808 // add everything that was after the first SELECT
809 $count_query .= PMA_SQP_formatHtml(
810 $parsed_sql,
811 'query_only',
812 $analyzed_sql[0]['position_of_first_select'] + 1
814 // ensure there is no semicolon at the end of the
815 // count query because we'll probably add
816 // a LIMIT 1 clause after it
817 $count_query = rtrim($count_query);
818 $count_query = rtrim($count_query, ';');
820 // if using SQL_CALC_FOUND_ROWS, add a LIMIT to avoid
821 // long delays. Returned count will be complete anyway.
822 // (but a LIMIT would disrupt results in an UNION)
824 if (! isset($analyzed_sql[0]['queryflags']['union'])) {
825 $count_query .= ' LIMIT 1';
828 // run the count query
830 PMA_DBI_try_query($count_query);
831 // if (mysql_error()) {
832 // void.
833 // I tried the case
834 // (SELECT `User`, `Host`, `Db`, `Select_priv` FROM `db`)
835 // UNION (SELECT `User`, `Host`, "%" AS "Db",
836 // `Select_priv`
837 // FROM `user`) ORDER BY `User`, `Host`, `Db`;
838 // and although the generated count_query is wrong
839 // the SELECT FOUND_ROWS() work! (maybe it gets the
840 // count from the latest query that worked)
842 // another case where the count_query is wrong:
843 // SELECT COUNT(*), f1 from t1 group by f1
844 // and you click to sort on count(*)
845 // }
846 $unlim_num_rows = PMA_DBI_fetch_value('SELECT FOUND_ROWS()');
847 } // end else "just browsing"
849 } else { // not $is_select
850 $unlim_num_rows = 0;
851 } // end rows total count
853 // if a table or database gets dropped, check column comments.
854 if (isset($purge) && $purge == '1') {
856 * Cleanup relations.
858 include_once 'libraries/relation_cleanup.lib.php';
860 if (strlen($table) && strlen($db)) {
861 PMA_relationsCleanupTable($db, $table);
862 } elseif (strlen($db)) {
863 PMA_relationsCleanupDatabase($db);
864 } else {
865 // VOID. No DB/Table gets deleted.
866 } // end if relation-stuff
867 } // end if ($purge)
869 // If a column gets dropped, do relation magic.
870 if (isset($dropped_column)
871 && strlen($db)
872 && strlen($table)
873 && ! empty($dropped_column)
875 include_once 'libraries/relation_cleanup.lib.php';
876 PMA_relationsCleanupColumn($db, $table, $dropped_column);
877 // to refresh the list of indexes (Ajax mode)
878 $extra_data['indexes_list'] = PMA_Index::getView($table, $db);
879 } // end if column was dropped
880 } // end else "didn't ask to see php code"
882 // No rows returned -> move back to the calling page
883 if ((0 == $num_rows && 0 == $unlim_num_rows) || $is_affected) {
884 // Delete related tranformation information
885 if (!empty($analyzed_sql[0]['querytype'])
886 && (($analyzed_sql[0]['querytype'] == 'ALTER')
887 || ($analyzed_sql[0]['querytype'] == 'DROP'))
889 include_once 'libraries/transformations.lib.php';
890 if ($analyzed_sql[0]['querytype'] == 'ALTER') {
891 if (stripos($analyzed_sql[0]['unsorted_query'], 'DROP') !== false) {
892 $drop_column = PMA_getColumnNameInColumnDropSql(
893 $analyzed_sql[0]['unsorted_query']
896 if ($drop_column != '') {
897 PMA_clearTransformations($db, $table, $drop_column);
901 } else if (($analyzed_sql[0]['querytype'] == 'DROP') && ($table != '')) {
902 PMA_clearTransformations($db, $table);
906 if ($is_delete) {
907 $message = PMA_Message::getMessageForDeletedRows($num_rows);
908 } elseif ($is_insert) {
909 if ($is_replace) {
910 // For replace we get DELETED + INSERTED row count,
911 // so we have to call it affected
912 $message = PMA_Message::getMessageForAffectedRows($num_rows);
913 } else {
914 $message = PMA_Message::getMessageForInsertedRows($num_rows);
916 $insert_id = PMA_DBI_insert_id();
917 if ($insert_id != 0) {
918 // insert_id is id of FIRST record inserted in one insert,
919 // so if we inserted multiple rows, we had to increment this
920 $message->addMessage('[br]');
921 // need to use a temporary because the Message class
922 // currently supports adding parameters only to the first
923 // message
924 $_inserted = PMA_Message::notice(__('Inserted row id: %1$d'));
925 $_inserted->addParam($insert_id + $num_rows - 1);
926 $message->addMessage($_inserted);
928 } elseif ($is_affected) {
929 $message = PMA_Message::getMessageForAffectedRows($num_rows);
931 // Ok, here is an explanation for the !$is_select.
932 // The form generated by sql_query_form.lib.php
933 // and db_sql.php has many submit buttons
934 // on the same form, and some confusion arises from the
935 // fact that $message_to_show is sent for every case.
936 // The $message_to_show containing a success message and sent with
937 // the form should not have priority over errors
938 } elseif (! empty($message_to_show) && ! $is_select) {
939 $message = PMA_Message::rawSuccess(htmlspecialchars($message_to_show));
940 } elseif (! empty($GLOBALS['show_as_php'])) {
941 $message = PMA_Message::success(__('Showing as PHP code'));
942 } elseif (isset($GLOBALS['show_as_php'])) {
943 /* User disable showing as PHP, query is only displayed */
944 $message = PMA_Message::notice(__('Showing SQL query'));
945 } elseif (! empty($GLOBALS['validatequery'])) {
946 $message = PMA_Message::notice(__('Validated SQL'));
947 } else {
948 $message = PMA_Message::success(
949 __('MySQL returned an empty result set (i.e. zero rows).')
953 if (isset($GLOBALS['querytime'])) {
954 $_querytime = PMA_Message::notice('(' . __('Query took %01.4f sec') . ')');
955 $_querytime->addParam($GLOBALS['querytime']);
956 $message->addMessage($_querytime);
959 if ($GLOBALS['is_ajax_request'] == true) {
960 if ($cfg['ShowSQL']) {
961 $extra_data['sql_query'] = PMA_Util::getMessage(
962 $message, $GLOBALS['sql_query'], 'success'
965 if (isset($GLOBALS['reload']) && $GLOBALS['reload'] == 1) {
966 $extra_data['reload'] = 1;
967 $extra_data['db'] = $GLOBALS['db'];
969 $response = PMA_Response::getInstance();
970 $response->isSuccess($message->isSuccess());
971 // No need to manually send the message
972 // The Response class will handle that automatically
973 $response->addJSON(isset($extra_data) ? $extra_data : array());
974 if (empty($_REQUEST['ajax_page_request'])) {
975 $response->addJSON('message', $message);
976 exit;
980 if ($is_gotofile) {
981 $goto = PMA_securePath($goto);
982 // Checks for a valid target script
983 $is_db = $is_table = false;
984 if (isset($_REQUEST['purge']) && $_REQUEST['purge'] == '1') {
985 $table = '';
986 unset($url_params['table']);
988 include 'libraries/db_table_exists.lib.php';
990 if (strpos($goto, 'tbl_') === 0 && ! $is_table) {
991 if (strlen($table)) {
992 $table = '';
994 $goto = 'db_sql.php';
996 if (strpos($goto, 'db_') === 0 && ! $is_db) {
997 if (strlen($db)) {
998 $db = '';
1000 $goto = 'index.php';
1002 // Loads to target script
1003 if (strlen($goto) > 0) {
1004 $active_page = $goto;
1005 include '' . $goto;
1006 } else {
1007 // Echo at least one character to prevent showing last page from history
1008 echo " ";
1011 } else {
1012 // avoid a redirect loop when last record was deleted
1013 if (0 == $num_rows && 'sql.php' == $cfg['DefaultTabTable']) {
1014 $goto = str_replace('sql.php', 'tbl_structure.php', $goto);
1016 PMA_sendHeaderLocation(
1017 $cfg['PmaAbsoluteUri'] . str_replace('&amp;', '&', $goto)
1018 . '&message=' . urlencode($message)
1020 } // end else
1021 exit();
1022 // end no rows returned
1023 } else {
1024 // At least one row is returned -> displays a table with results
1025 //If we are retrieving the full value of a truncated field or the original
1026 // value of a transformed field, show it here and exit
1027 if ($GLOBALS['grid_edit'] == true) {
1028 $row = PMA_DBI_fetch_row($result);
1029 $response = PMA_Response::getInstance();
1030 $response->addJSON('value', $row[0]);
1031 exit;
1034 if (isset($_REQUEST['ajax_request']) && isset($_REQUEST['table_maintenance'])) {
1035 $response = PMA_Response::getInstance();
1036 $header = $response->getHeader();
1037 $scripts = $header->getScripts();
1038 $scripts->addFile('makegrid.js');
1039 $scripts->addFile('sql.js');
1041 // Gets the list of fields properties
1042 if (isset($result) && $result) {
1043 $fields_meta = PMA_DBI_get_fields_meta($result);
1044 $fields_cnt = count($fields_meta);
1047 if (empty($disp_mode)) {
1048 // see the "PMA_setDisplayMode()" function in
1049 // libraries/DisplayResults.class.php
1050 $disp_mode = 'urdr111101';
1053 // hide edit and delete links for information_schema
1054 if (PMA_is_system_schema($db)) {
1055 $disp_mode = 'nnnn110111';
1058 if (isset($message)) {
1059 $message = PMA_Message::success($message);
1060 echo PMA_Util::getMessage(
1061 $message, $GLOBALS['sql_query'], 'success'
1065 // Should be initialized these parameters before parsing
1066 $showtable = isset($showtable) ? $showtable : null;
1067 $printview = isset($printview) ? $printview : null;
1068 $url_query = isset($url_query) ? $url_query : null;
1070 if (!empty($sql_data) && ($sql_data['valid_queries'] > 1)) {
1072 $_SESSION['is_multi_query'] = true;
1073 echo getTableHtmlForMultipleQueries(
1074 $displayResultsObject, $db, $sql_data, $goto,
1075 $pmaThemeImage, $text_dir, $printview, $url_query,
1076 $disp_mode, $sql_limit_to_append, false
1078 } else {
1079 $_SESSION['is_multi_query'] = false;
1080 $displayResultsObject->setProperties(
1081 $unlim_num_rows, $fields_meta, $is_count, $is_export, $is_func,
1082 $is_analyse, $num_rows, $fields_cnt, $querytime, $pmaThemeImage,
1083 $text_dir, $is_maint, $is_explain, $is_show, $showtable,
1084 $printview, $url_query, false
1087 echo $displayResultsObject->getTable(
1088 $result, $disp_mode, $analyzed_sql
1090 exit();
1094 // Displays the headers
1095 if (isset($show_query)) {
1096 unset($show_query);
1098 if (isset($printview) && $printview == '1') {
1099 PMA_Util::checkParameters(array('db', 'full_sql_query'));
1101 $response = PMA_Response::getInstance();
1102 $header = $response->getHeader();
1103 $header->enablePrintView();
1105 $hostname = '';
1106 if ($cfg['Server']['verbose']) {
1107 $hostname = $cfg['Server']['verbose'];
1108 } else {
1109 $hostname = $cfg['Server']['host'];
1110 if (! empty($cfg['Server']['port'])) {
1111 $hostname .= $cfg['Server']['port'];
1115 $versions = "phpMyAdmin&nbsp;" . PMA_VERSION;
1116 $versions .= "&nbsp;/&nbsp;";
1117 $versions .= "MySQL&nbsp;" . PMA_MYSQL_STR_VERSION;
1119 echo "<h1>" . __('SQL result') . "</h1>";
1120 echo "<p>";
1121 echo "<strong>" . __('Host') . ":</strong> $hostname<br />";
1122 echo "<strong>" . __('Database') . ":</strong> "
1123 . htmlspecialchars($db) . "<br />";
1124 echo "<strong>" . __('Generation Time') . ":</strong> "
1125 . PMA_Util::localisedDate() . "<br />";
1126 echo "<strong>" . __('Generated by') . ":</strong> $versions<br />";
1127 echo "<strong>" . __('SQL query') . ":</strong> "
1128 . htmlspecialchars($full_sql_query) . ";";
1129 if (isset($num_rows)) {
1130 echo "<br />";
1131 echo "<strong>" . __('Rows') . ":</strong> $num_rows";
1133 echo "</p>";
1134 } else {
1135 $response = PMA_Response::getInstance();
1136 $header = $response->getHeader();
1137 $scripts = $header->getScripts();
1138 $scripts->addFile('makegrid.js');
1139 $scripts->addFile('sql.js');
1141 unset($message);
1143 if (! $GLOBALS['is_ajax_request']) {
1144 if (strlen($table)) {
1145 include 'libraries/tbl_common.inc.php';
1146 $url_query .= '&amp;goto=tbl_sql.php&amp;back=tbl_sql.php';
1147 include 'libraries/tbl_info.inc.php';
1148 } elseif (strlen($db)) {
1149 include 'libraries/db_common.inc.php';
1150 include 'libraries/db_info.inc.php';
1151 } else {
1152 include 'libraries/server_common.inc.php';
1154 } else {
1155 //we don't need to buffer the output in getMessage here.
1156 //set a global variable and check against it in the function
1157 $GLOBALS['buffer_message'] = false;
1161 if (strlen($db)) {
1162 $cfgRelation = PMA_getRelationsParam();
1165 // Gets the list of fields properties
1166 if (isset($result) && $result) {
1167 $fields_meta = PMA_DBI_get_fields_meta($result);
1168 $fields_cnt = count($fields_meta);
1171 //begin the sqlqueryresults div here. container div
1172 echo '<div id="sqlqueryresults"';
1173 echo ' class="ajax"';
1174 echo '>';
1176 // Display previous update query (from tbl_replace)
1177 if (isset($disp_query) && ($cfg['ShowSQL'] == true) && empty($sql_data)) {
1178 echo PMA_Util::getMessage($disp_message, $disp_query, 'success');
1181 if (isset($profiling_results)) {
1182 // pma_token/url_query needed for chart export
1183 echo '<script type="text/javascript">';
1184 echo 'pma_token = \'' . $_SESSION[' PMA_token '] . '\';';
1185 echo 'url_query = \''
1186 . (isset($url_query) ? $url_query : PMA_generate_common_url($db))
1187 . '\';';
1188 echo 'AJAX.registerOnload(\'sql.js\',makeProfilingChart);';
1189 echo '</script>';
1191 echo '<fieldset><legend>' . __('Profiling') . '</legend>' . "\n";
1192 echo '<div style="float: left;">';
1193 echo '<table>' . "\n";
1194 echo ' <tr>' . "\n";
1195 echo ' <th>' . __('Status')
1196 . PMA_Util::showMySQLDocu(
1197 'general-thread-states', 'general-thread-states'
1199 . '</th>' . "\n";
1200 echo ' <th>' . __('Time') . '</th>' . "\n";
1201 echo ' </tr>' . "\n";
1203 $chart_json = Array();
1204 foreach ($profiling_results as $one_result) {
1205 echo ' <tr>' . "\n";
1206 echo '<td>' . ucwords($one_result['Status']) . '</td>' . "\n";
1207 echo '<td class="right">'
1208 . (PMA_Util::formatNumber($one_result['Duration'], 3, 1))
1209 . 's</td>' . "\n";
1210 if (isset($chart_json[ucwords($one_result['Status'])])) {
1211 $chart_json[ucwords($one_result['Status'])]
1212 += $one_result['Duration'];
1213 } else {
1214 $chart_json[ucwords($one_result['Status'])]
1215 = $one_result['Duration'];
1219 echo '</table>' . "\n";
1220 echo '</div>';
1221 //require_once 'libraries/chart.lib.php';
1222 echo '<div id="profilingChartData" style="display:none;">';
1223 echo json_encode($chart_json);
1224 echo '</div>';
1225 echo '<div id="profilingchart" style="display:none;">';
1226 echo '</div>';
1227 echo '<script type="text/javascript">';
1228 echo 'if($.jqplot !== undefined && $.jqplot.PieRenderer !== undefined) {';
1229 echo 'makeProfilingChart();';
1230 echo '}';
1231 echo '</script>';
1232 echo '</fieldset>' . "\n";
1235 // Displays the results in a table
1236 if (empty($disp_mode)) {
1237 // see the "PMA_setDisplayMode()" function in
1238 // libraries/DisplayResults.class.php
1239 $disp_mode = 'urdr111101';
1242 $resultSetContainsUniqueKey = PMA_resultSetContainsUniqueKey(
1243 $db, $table, $fields_meta
1246 // hide edit and delete links:
1247 // - for information_schema
1248 // - if the result set does not contain all the columns of a unique key
1249 // and we are not just browing all the columns of an updatable view
1250 $updatableView
1251 = $justBrowsing
1252 && trim($analyzed_sql[0]['select_expr_clause']) == '*'
1253 && PMA_Table::isUpdatableView($db, $table);
1254 $editable = $resultSetContainsUniqueKey || $updatableView;
1255 if (PMA_is_system_schema($db) || ! $editable) {
1256 $disp_mode = 'nnnn110111';
1257 $msg = PMA_message::notice(
1259 'This table does not contain a unique column.'
1260 . ' Grid edit, checkbox, Edit, Copy and Delete features'
1261 . ' are not available.'
1264 $msg->display();
1267 if (isset($label)) {
1268 $msg = PMA_message::success(__('Bookmark %s created'));
1269 $msg->addParam($label);
1270 $msg->display();
1273 // Should be initialized these parameters before parsing
1274 $showtable = isset($showtable) ? $showtable : null;
1275 $printview = isset($printview) ? $printview : null;
1276 $url_query = isset($url_query) ? $url_query : null;
1278 if (! empty($sql_data) && ($sql_data['valid_queries'] > 1) || $is_procedure) {
1280 $_SESSION['is_multi_query'] = true;
1281 echo getTableHtmlForMultipleQueries(
1282 $displayResultsObject, $db, $sql_data, $goto,
1283 $pmaThemeImage, $text_dir, $printview, $url_query,
1284 $disp_mode, $sql_limit_to_append, $editable
1286 } else {
1287 $_SESSION['is_multi_query'] = false;
1288 $displayResultsObject->setProperties(
1289 $unlim_num_rows, $fields_meta, $is_count, $is_export, $is_func,
1290 $is_analyse, $num_rows, $fields_cnt, $querytime, $pmaThemeImage,
1291 $text_dir, $is_maint, $is_explain, $is_show, $showtable,
1292 $printview, $url_query, $editable
1295 echo $displayResultsObject->getTable($result, $disp_mode, $analyzed_sql);
1296 PMA_DBI_free_result($result);
1299 // BEGIN INDEX CHECK See if indexes should be checked.
1300 if (isset($query_type)
1301 && $query_type == 'check_tbl'
1302 && isset($selected)
1303 && is_array($selected)
1305 foreach ($selected as $idx => $tbl_name) {
1306 $check = PMA_Index::findDuplicates($tbl_name, $db);
1307 if (! empty($check)) {
1308 printf(__('Problems with indexes of table `%s`'), $tbl_name);
1309 echo $check;
1312 } // End INDEX CHECK
1314 // Bookmark support if required
1315 if ($disp_mode[7] == '1'
1316 && (! empty($cfg['Bookmark']) && empty($id_bookmark))
1317 && ! empty($sql_query)
1319 echo "\n";
1320 $goto = 'sql.php?'
1321 . PMA_generate_common_url($db, $table)
1322 . '&amp;sql_query=' . urlencode($sql_query)
1323 . '&amp;id_bookmark=1';
1325 echo '<form action="sql.php" method="post"'
1326 . ' onsubmit="return ! emptyFormElements(this, \'fields[label]\');"'
1327 . ' id="bookmarkQueryForm">';
1328 echo PMA_generate_common_hidden_inputs();
1329 echo '<input type="hidden" name="goto" value="' . $goto . '" />';
1330 echo '<input type="hidden" name="fields[dbase]"'
1331 . ' value="' . htmlspecialchars($db) . '" />';
1332 echo '<input type="hidden" name="fields[user]"'
1333 . ' value="' . $cfg['Bookmark']['user'] . '" />';
1334 echo '<input type="hidden" name="fields[query]"' . ' value="'
1335 . urlencode(isset($complete_query) ? $complete_query : $sql_query)
1336 . '" />';
1337 echo '<fieldset>';
1338 echo '<legend>';
1339 echo PMA_Util::getIcon(
1340 'b_bookmark.png', __('Bookmark this SQL query'), true
1342 echo '</legend>';
1343 echo '<div class="formelement">';
1344 echo '<label for="fields_label_">' . __('Label') . ':</label>';
1345 echo '<input type="text" id="fields_label_"'
1346 . ' name="fields[label]" value="" />';
1347 echo '</div>';
1348 echo '<div class="formelement">';
1349 echo '<input type="checkbox" name="bkm_all_users"'
1350 . ' id="bkm_all_users" value="true" />';
1351 echo '<label for="bkm_all_users">'
1352 . __('Let every user access this bookmark')
1353 . '</label>';
1354 echo '</div>';
1355 echo '<div class="clearfloat"></div>';
1356 echo '</fieldset>';
1357 echo '<fieldset class="tblFooters">';
1358 echo '<input type="hidden" name="store_bkm" value="1" />';
1359 echo '<input type="submit"'
1360 . ' value="' . __('Bookmark this SQL query') . '" />';
1361 echo '</fieldset>';
1362 echo '</form>';
1363 } // end bookmark support
1365 // Do print the page if required
1366 if (isset($printview) && $printview == '1') {
1367 echo PMA_Util::getButton();
1368 } // end print case
1369 echo '</div>'; // end sqlqueryresults div
1370 } // end rows returned
1372 $_SESSION['is_multi_query'] = false;
1375 * Displays the footer
1377 if (! isset($_REQUEST['table_maintenance'])) {
1378 exit;
1382 // These functions will need for use set the required parameters for display results
1385 * Initialize some parameters needed to display results
1387 * @param string $sql_query SQL statement
1388 * @param boolean $is_select select query or not
1390 * @return array set of parameters
1392 * @access public
1394 function PMA_getDisplayPropertyParams($sql_query, $is_select)
1396 $is_explain = $is_count = $is_export = $is_delete = $is_insert = $is_affected = $is_show = $is_maint = $is_analyse = $is_group = $is_func = $is_replace = false;
1398 if ($is_select) {
1399 $is_group = preg_match('@(GROUP[[:space:]]+BY|HAVING|SELECT[[:space:]]+DISTINCT)[[:space:]]+@i', $sql_query);
1400 $is_func = ! $is_group && (preg_match('@[[:space:]]+(SUM|AVG|STD|STDDEV|MIN|MAX|BIT_OR|BIT_AND)\s*\(@i', $sql_query));
1401 $is_count = ! $is_group && (preg_match('@^SELECT[[:space:]]+COUNT\((.*\.+)?.*\)@i', $sql_query));
1402 $is_export = preg_match('@[[:space:]]+INTO[[:space:]]+OUTFILE[[:space:]]+@i', $sql_query);
1403 $is_analyse = preg_match('@[[:space:]]+PROCEDURE[[:space:]]+ANALYSE@i', $sql_query);
1404 } elseif (preg_match('@^EXPLAIN[[:space:]]+@i', $sql_query)) {
1405 $is_explain = true;
1406 } elseif (preg_match('@^DELETE[[:space:]]+@i', $sql_query)) {
1407 $is_delete = true;
1408 $is_affected = true;
1409 } elseif (preg_match('@^(INSERT|LOAD[[:space:]]+DATA|REPLACE)[[:space:]]+@i', $sql_query)) {
1410 $is_insert = true;
1411 $is_affected = true;
1412 if (preg_match('@^(REPLACE)[[:space:]]+@i', $sql_query)) {
1413 $is_replace = true;
1415 } elseif (preg_match('@^UPDATE[[:space:]]+@i', $sql_query)) {
1416 $is_affected = true;
1417 } elseif (preg_match('@^[[:space:]]*SHOW[[:space:]]+@i', $sql_query)) {
1418 $is_show = true;
1419 } elseif (preg_match('@^(CHECK|ANALYZE|REPAIR|OPTIMIZE)[[:space:]]+TABLE[[:space:]]+@i', $sql_query)) {
1420 $is_maint = true;
1423 return array(
1424 $is_group, $is_func, $is_count, $is_export, $is_analyse, $is_explain,
1425 $is_delete, $is_affected, $is_insert, $is_replace,$is_show, $is_maint
1430 * Get the database name inside a USE query
1432 * @param string $sql SQL query
1433 * @param array $databases array with all databases
1435 * @return strin $db new database name
1437 function PMA_getNewDatabase($sql, $databases)
1439 $db = '';
1440 // loop through all the databases
1441 foreach ($databases as $database) {
1442 if (strpos($sql, $database['SCHEMA_NAME']) !== false) {
1443 $db = $database;
1444 break;
1447 return $db;
1451 * Get the table name in a sql query
1452 * If there are several tables in the SQL query,
1453 * first table wil lreturn
1455 * @param string $sql SQL query
1456 * @param array $tables array of names in current database
1458 * @return string $table table name
1460 function PMA_getTableNameBySQL($sql, $tables)
1462 $table = '';
1464 // loop through all the tables in the database
1465 foreach ($tables as $tbl) {
1466 if (strpos($sql, $tbl)) {
1467 $table .= ' ' . $tbl;
1471 if (count(explode(' ', trim($table))) > 1) {
1472 $tmp_array = explode(' ', trim($table));
1473 return $tmp_array[0];
1476 return trim($table);
1481 * Generate table html when SQL statement have multiple queries
1482 * which return displayable results
1484 * @param PMA_DisplayResults $displayResultsObject object
1485 * @param string $db database name
1486 * @param array $sql_data information about SQL statement
1487 * @param string $goto URL to go back in case of errors
1488 * @param string $pmaThemeImage path for theme images directory
1489 * @param string $text_dir text direction
1490 * @param string $printview whether printview is enabled
1491 * @param string $url_query URL query
1492 * @param array $disp_mode the display mode
1493 * @param string $sql_limit_to_append limit clause
1494 * @param bool $editable whether result set is editable
1496 * @return string $table_html html content
1498 function getTableHtmlForMultipleQueries(
1499 $displayResultsObject, $db, $sql_data, $goto, $pmaThemeImage,
1500 $text_dir, $printview, $url_query, $disp_mode, $sql_limit_to_append,
1501 $editable
1503 $table_html = '';
1505 $tables_array = PMA_DBI_get_tables($db);
1506 $databases_array = PMA_DBI_get_databases_full();
1507 $multi_sql = implode(";", $sql_data['valid_sql']);
1508 $querytime_before = array_sum(explode(' ', microtime()));
1510 // Assignment for variable is not needed since the results are
1511 // looiping using the connection
1512 @PMA_DBI_try_multi_query($multi_sql);
1514 $querytime_after = array_sum(explode(' ', microtime()));
1515 $querytime = $querytime_after - $querytime_before;
1516 $sql_no = 0;
1518 do {
1519 $analyzed_sql = array();
1520 $is_affected = false;
1522 $result = PMA_DBI_store_result();
1523 $fields_meta = ($result !== false)
1524 ? PMA_DBI_get_fields_meta($result)
1525 : array();
1526 $fields_cnt = count($fields_meta);
1528 // Initialize needed params related to each query in multiquery statement
1529 if (isset($sql_data['valid_sql'][$sql_no])) {
1530 // 'Use' query can change the database
1531 if (stripos($sql_data['valid_sql'][$sql_no], "use ")) {
1532 $db = PMA_getNewDatabase(
1533 $sql_data['valid_sql'][$sql_no],
1534 $databases_array
1537 $parsed_sql = PMA_SQP_parse($sql_data['valid_sql'][$sql_no]);
1538 $table = PMA_getTableNameBySQL(
1539 $sql_data['valid_sql'][$sql_no],
1540 $tables_array
1543 $analyzed_sql = PMA_SQP_analyze($parsed_sql);
1544 $is_select = isset($analyzed_sql[0]['queryflags']['select_from']);
1545 $unlim_num_rows = PMA_Table::countRecords($db, $table, true);
1546 $showtable = PMA_Table::sGetStatusInfo($db, $table, null, true);
1547 $url_query = PMA_generate_common_url($db, $table);
1549 list($is_group, $is_func, $is_count, $is_export, $is_analyse,
1550 $is_explain, $is_delete, $is_affected, $is_insert, $is_replace,
1551 $is_show, $is_maint)
1552 = PMA_getDisplayPropertyParams(
1553 $sql_data['valid_sql'][$sql_no], $is_select
1556 // Handle remembered sorting order, only for single table query
1557 if ($GLOBALS['cfg']['RememberSorting']
1558 && ! ($is_count || $is_export || $is_func || $is_analyse)
1559 && isset($analyzed_sql[0]['select_expr'])
1560 && (count($analyzed_sql[0]['select_expr']) == 0)
1561 && isset($analyzed_sql[0]['queryflags']['select_from'])
1562 && count($analyzed_sql[0]['table_ref']) == 1
1564 PMA_handleSortOrder(
1565 $db,
1566 $table,
1567 $analyzed_sql,
1568 $sql_data['valid_sql'][$sql_no]
1572 // Do append a "LIMIT" clause?
1573 if (($_SESSION['tmp_user_values']['max_rows'] != 'all')
1574 && ! ($is_count || $is_export || $is_func || $is_analyse)
1575 && isset($analyzed_sql[0]['queryflags']['select_from'])
1576 && ! isset($analyzed_sql[0]['queryflags']['offset'])
1577 && empty($analyzed_sql[0]['limit_clause'])
1579 $sql_limit_to_append = ' LIMIT '
1580 . $_SESSION['tmp_user_values']['pos']
1581 . ', ' . $_SESSION['tmp_user_values']['max_rows'] . " ";
1582 $sql_data['valid_sql'][$sql_no] = PMA_getSqlWithLimitClause(
1583 $sql_data['valid_sql'][$sql_no],
1584 $analyzed_sql,
1585 $sql_limit_to_append
1589 // Set the needed properties related to executing sql query
1590 $displayResultsObject->__set('db', $db);
1591 $displayResultsObject->__set('table', $table);
1592 $displayResultsObject->__set('goto', $goto);
1595 if (! $is_affected) {
1596 $num_rows = ($result) ? @PMA_DBI_num_rows($result) : 0;
1597 } elseif (! isset($num_rows)) {
1598 $num_rows = @PMA_DBI_affected_rows();
1601 if (isset($sql_data['valid_sql'][$sql_no])) {
1603 $displayResultsObject->__set(
1604 'sql_query',
1605 $sql_data['valid_sql'][$sql_no]
1607 $displayResultsObject->setProperties(
1608 $unlim_num_rows, $fields_meta, $is_count, $is_export, $is_func,
1609 $is_analyse, $num_rows, $fields_cnt, $querytime, $pmaThemeImage,
1610 $text_dir, $is_maint, $is_explain, $is_show, $showtable,
1611 $printview, $url_query, $editable
1615 if ($num_rows == 0) {
1616 continue;
1619 // With multiple results, operations are limied
1620 $disp_mode = 'nnnn000000';
1621 $is_limited_display = true;
1623 // Collect the tables
1624 $table_html .= $displayResultsObject->getTable(
1625 $result, $disp_mode, $analyzed_sql, $is_limited_display
1628 // Free the result to save the memory
1629 PMA_DBI_free_result($result);
1631 $sql_no++;
1633 } while (PMA_DBI_more_results() && PMA_DBI_next_result());
1635 return $table_html;
1639 * Handle remembered sorting order, only for single table query
1641 * @param string $db database name
1642 * @param string $table table name
1643 * @param array &$analyzed_sql the analyzed query
1644 * @param string &$full_sql_query SQL query
1646 * @return void
1648 function PMA_handleSortOrder($db, $table, &$analyzed_sql, &$full_sql_query)
1650 $pmatable = new PMA_Table($table, $db);
1651 if (empty($analyzed_sql[0]['order_by_clause'])) {
1652 $sorted_col = $pmatable->getUiProp(PMA_Table::PROP_SORTED_COLUMN);
1653 if ($sorted_col) {
1654 // retrieve the remembered sorting order for current table
1655 $sql_order_to_append = ' ORDER BY ' . $sorted_col . ' ';
1656 $full_sql_query = $analyzed_sql[0]['section_before_limit']
1657 . $sql_order_to_append . $analyzed_sql[0]['limit_clause']
1658 . ' ' . $analyzed_sql[0]['section_after_limit'];
1660 // update the $analyzed_sql
1661 $analyzed_sql[0]['section_before_limit'] .= $sql_order_to_append;
1662 $analyzed_sql[0]['order_by_clause'] = $sorted_col;
1664 } else {
1665 // store the remembered table into session
1666 $pmatable->setUiProp(
1667 PMA_Table::PROP_SORTED_COLUMN,
1668 $analyzed_sql[0]['order_by_clause']
1674 * Append limit clause to SQL query
1676 * @param string $full_sql_query SQL query
1677 * @param array $analyzed_sql the analyzed query
1678 * @param string $sql_limit_to_append clause to append
1680 * @return string limit clause appended SQL query
1682 function PMA_getSqlWithLimitClause($full_sql_query, $analyzed_sql,
1683 $sql_limit_to_append
1685 return $analyzed_sql[0]['section_before_limit'] . "\n"
1686 . $sql_limit_to_append . $analyzed_sql[0]['section_after_limit'];
1691 * Get column name from a drop SQL statement
1693 * @param string $sql SQL query
1695 * @return string $drop_column Name of the column
1697 function PMA_getColumnNameInColumnDropSql($sql)
1699 $tmpArray1 = explode('DROP', $sql);
1700 $str_to_check = trim($tmpArray1[1]);
1702 if (stripos($str_to_check, 'COLUMN') !== false) {
1703 $tmpArray2 = explode('COLUMN', $str_to_check);
1704 $str_to_check = trim($tmpArray2[1]);
1707 $tmpArray3 = explode(' ', $str_to_check);
1708 $str_to_check = trim($tmpArray3[0]);
1710 $drop_column = str_replace(';', '', trim($str_to_check));
1711 $drop_column = str_replace('`', '', $drop_column);
1713 return $drop_column;
1717 * Verify whether the result set contains all the columns
1718 * of at least one unique key
1720 * @param string $db database name
1721 * @param string $table table name
1722 * @param string $fields_meta meta fields
1724 * @return boolean whether the result set contains a unique key
1726 function PMA_resultSetContainsUniqueKey($db, $table, $fields_meta)
1728 $resultSetColumnNames = array();
1729 foreach ($fields_meta as $oneMeta) {
1730 $resultSetColumnNames[] = $oneMeta->name;
1732 foreach (PMA_Index::getFromTable($table, $db) as $index) {
1733 if ($index->isUnique()) {
1734 $indexColumns = $index->getColumns();
1735 $numberFound = 0;
1736 foreach ($indexColumns as $indexColumnName => $dummy) {
1737 if (in_array($indexColumnName, $resultSetColumnNames)) {
1738 $numberFound++;
1741 if ($numberFound == count($indexColumns)) {
1742 return true;
1746 return false;