Cleaned up the logout script
[openemr.git] / phpmyadmin / sql.php
blobcfe8dea106e3b1407804c43c48a1e463866fde1f
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['is_multi_query'])) {
71 $_SESSION['is_multi_query'] = false;
74 /**
75 * Defines the url to return to in case of error in a sql statement
77 // Security checkings
78 if (! empty($goto)) {
79 $is_gotofile = preg_replace('@^([^?]+).*$@s', '\\1', $goto);
80 if (! @file_exists('' . $is_gotofile)) {
81 unset($goto);
82 } else {
83 $is_gotofile = ($is_gotofile == $goto);
85 } else {
86 if (empty($table)) {
87 $goto = $cfg['DefaultTabDatabase'];
88 } else {
89 $goto = $cfg['DefaultTabTable'];
91 $is_gotofile = true;
92 } // end if
94 if (! isset($err_url)) {
95 $err_url = (! empty($back) ? $back : $goto)
96 . '?' . PMA_generate_common_url($db)
97 . ((strpos(' ' . $goto, 'db_') != 1 && strlen($table))
98 ? '&amp;table=' . urlencode($table)
99 : ''
101 } // end if
103 // Coming from a bookmark dialog
104 if (isset($fields['query'])) {
105 $sql_query = $fields['query'];
108 // This one is just to fill $db
109 if (isset($fields['dbase'])) {
110 $db = $fields['dbase'];
114 * During grid edit, if we have a relational field, show the dropdown for it
116 * Logic taken from libraries/DisplayResults.class.php
118 * This doesn't seem to be the right place to do this, but I can't think of any
119 * better place either.
121 if (isset($_REQUEST['get_relational_values'])
122 && $_REQUEST['get_relational_values'] == true
124 $column = $_REQUEST['column'];
125 $foreigners = PMA_getForeigners($db, $table, $column);
127 $display_field = PMA_getDisplayField(
128 $foreigners[$column]['foreign_db'],
129 $foreigners[$column]['foreign_table']
132 $foreignData = PMA_getForeignData($foreigners, $column, false, '', '');
134 if ($_SESSION['tmp_user_values']['relational_display'] == 'D'
135 && isset($display_field)
136 && strlen($display_field)
137 && isset($_REQUEST['relation_key_or_display_column'])
138 && $_REQUEST['relation_key_or_display_column']
140 $curr_value = $_REQUEST['relation_key_or_display_column'];
141 } else {
142 $curr_value = $_REQUEST['curr_value'];
144 if ($foreignData['disp_row'] == null) {
145 //Handle the case when number of values
146 //is more than $cfg['ForeignKeyMaxLimit']
147 $_url_params = array(
148 'db' => $db,
149 'table' => $table,
150 'field' => $column
153 $dropdown = '<span class="curr_value">'
154 . htmlspecialchars($_REQUEST['curr_value'])
155 . '</span>'
156 . '<a href="browse_foreigners.php'
157 . PMA_generate_common_url($_url_params) . '"'
158 . ' target="_blank" class="browse_foreign" ' .'>'
159 . __('Browse foreign values')
160 . '</a>';
161 } else {
162 $dropdown = PMA_foreignDropdown(
163 $foreignData['disp_row'],
164 $foreignData['foreign_field'],
165 $foreignData['foreign_display'],
166 $curr_value,
167 $cfg['ForeignKeyMaxLimit']
169 $dropdown = '<select>' . $dropdown . '</select>';
172 $response = PMA_Response::getInstance();
173 $response->addJSON('dropdown', $dropdown);
174 exit;
178 * Just like above, find possible values for enum fields during grid edit.
180 * Logic taken from libraries/DisplayResults.class.php
182 if (isset($_REQUEST['get_enum_values']) && $_REQUEST['get_enum_values'] == true) {
183 $field_info_query = PMA_DBI_get_columns_sql($db, $table, $_REQUEST['column']);
185 $field_info_result = PMA_DBI_fetch_result(
186 $field_info_query, null, null, null, PMA_DBI_QUERY_STORE
189 $values = PMA_Util::parseEnumSetValues($field_info_result[0]['Type']);
191 $dropdown = '<option value="">&nbsp;</option>';
192 foreach ($values as $value) {
193 $dropdown .= '<option value="' . $value . '"';
194 if ($value == $_REQUEST['curr_value']) {
195 $dropdown .= ' selected="selected"';
197 $dropdown .= '>' . $value . '</option>';
200 $dropdown = '<select>' . $dropdown . '</select>';
202 $response = PMA_Response::getInstance();
203 $response->addJSON('dropdown', $dropdown);
204 exit;
208 * Find possible values for set fields during grid edit.
210 if (isset($_REQUEST['get_set_values']) && $_REQUEST['get_set_values'] == true) {
211 $field_info_query = PMA_DBI_get_columns_sql($db, $table, $_REQUEST['column']);
213 $field_info_result = PMA_DBI_fetch_result(
214 $field_info_query, null, null, null, PMA_DBI_QUERY_STORE
217 $values = PMA_Util::parseEnumSetValues($field_info_result[0]['Type']);
219 $select = '';
221 //converts characters of $_REQUEST['curr_value'] to HTML entities
222 $converted_curr_value = htmlentities(
223 $_REQUEST['curr_value'], ENT_COMPAT, "UTF-8"
226 $selected_values = explode(',', $converted_curr_value);
228 foreach ($values as $value) {
229 $select .= '<option value="' . $value . '"';
230 if ($value == $converted_curr_value
231 || in_array($value, $selected_values, true)
233 $select .= ' selected="selected" ';
235 $select .= '>' . $value . '</option>';
238 $select_size = (sizeof($values) > 10) ? 10 : sizeof($values);
239 $select = '<select multiple="multiple" size="' . $select_size . '">'
240 . $select . '</select>';
242 $response = PMA_Response::getInstance();
243 $response->addJSON('select', $select);
244 exit;
248 * Check ajax request to set the column order
250 if (isset($_REQUEST['set_col_prefs']) && $_REQUEST['set_col_prefs'] == true) {
251 $pmatable = new PMA_Table($table, $db);
252 $retval = false;
254 // set column order
255 if (isset($_REQUEST['col_order'])) {
256 $col_order = explode(',', $_REQUEST['col_order']);
257 $retval = $pmatable->setUiProp(
258 PMA_Table::PROP_COLUMN_ORDER,
259 $col_order,
260 $_REQUEST['table_create_time']
262 if (gettype($retval) != 'boolean') {
263 $response = PMA_Response::getInstance();
264 $response->isSuccess(false);
265 $response->addJSON('message', $retval->getString());
266 exit;
270 // set column visibility
271 if ($retval === true && isset($_REQUEST['col_visib'])) {
272 $col_visib = explode(',', $_REQUEST['col_visib']);
273 $retval = $pmatable->setUiProp(
274 PMA_Table::PROP_COLUMN_VISIB, $col_visib,
275 $_REQUEST['table_create_time']
277 if (gettype($retval) != 'boolean') {
278 $response = PMA_Response::getInstance();
279 $response->isSuccess(false);
280 $response->addJSON('message', $retval->getString());
281 exit;
285 $response = PMA_Response::getInstance();
286 $response->isSuccess($retval == true);
287 exit;
290 // Default to browse if no query set and we have table
291 // (needed for browsing from DefaultTabTable)
292 if (empty($sql_query) && strlen($table) && strlen($db)) {
293 include_once 'libraries/bookmark.lib.php';
294 $book_sql_query = PMA_Bookmark_get(
295 $db,
296 '\'' . PMA_Util::sqlAddSlashes($table) . '\'',
297 'label',
298 false,
299 true
302 if (! empty($book_sql_query)) {
303 $GLOBALS['using_bookmark_message'] = PMA_message::notice(
304 __('Using bookmark "%s" as default browse query.')
306 $GLOBALS['using_bookmark_message']->addParam($table);
307 $GLOBALS['using_bookmark_message']->addMessage(
308 PMA_Util::showDocu('faq', 'faq6-22')
310 $sql_query = $book_sql_query;
311 } else {
312 $sql_query = 'SELECT * FROM ' . PMA_Util::backquote($table);
314 unset($book_sql_query);
316 // set $goto to what will be displayed if query returns 0 rows
317 $goto = '';
318 } else {
319 // Now we can check the parameters
320 PMA_Util::checkParameters(array('sql_query'));
323 // instead of doing the test twice
324 $is_drop_database = preg_match(
325 '/DROP[[:space:]]+(DATABASE|SCHEMA)[[:space:]]+/i',
326 $sql_query
330 * Check rights in case of DROP DATABASE
332 * This test may be bypassed if $is_js_confirmed = 1 (already checked with js)
333 * but since a malicious user may pass this variable by url/form, we don't take
334 * into account this case.
336 if (! defined('PMA_CHK_DROP')
337 && ! $cfg['AllowUserDropDatabase']
338 && $is_drop_database
339 && ! $is_superuser
341 PMA_Util::mysqlDie(
342 __('"DROP DATABASE" statements are disabled.'),
345 $err_url
347 } // end if
349 // Include PMA_Index class for use in PMA_DisplayResults class
350 require_once './libraries/Index.class.php';
352 require_once 'libraries/DisplayResults.class.php';
354 $displayResultsObject = new PMA_DisplayResults(
355 $GLOBALS['db'], $GLOBALS['table'], $GLOBALS['goto'], $GLOBALS['sql_query']
358 $displayResultsObject->setConfigParamsForDisplayTable();
361 * Need to find the real end of rows?
363 if (isset($find_real_end) && $find_real_end) {
364 $unlim_num_rows = PMA_Table::countRecords($db, $table, true);
365 $_SESSION['tmp_user_values']['pos'] = @((ceil(
366 $unlim_num_rows / $_SESSION['tmp_user_values']['max_rows']
367 ) - 1) * $_SESSION['tmp_user_values']['max_rows']);
372 * Bookmark add
374 if (isset($store_bkm)) {
375 $result = PMA_Bookmark_save(
376 $fields,
377 (isset($bkm_all_users) && $bkm_all_users == 'true' ? true : false)
379 $response = PMA_Response::getInstance();
380 if ($response->isAjax()) {
381 if ($result) {
382 $msg = PMA_message::success(__('Bookmark %s created'));
383 $msg->addParam($fields['label']);
384 $response->addJSON('message', $msg);
385 } else {
386 $msg = PMA_message::error(__('Bookmark not created'));
387 $response->isSuccess(false);
388 $response->addJSON('message', $msg);
390 exit;
391 } else {
392 // go back to sql.php to redisplay query; do not use &amp; in this case:
393 PMA_sendHeaderLocation(
394 $cfg['PmaAbsoluteUri'] . $goto . '&label=' . $fields['label']
397 } // end if
400 * Parse and analyze the query
402 require_once 'libraries/parse_analyze.lib.php';
405 * Sets or modifies the $goto variable if required
407 if ($goto == 'sql.php') {
408 $is_gotofile = false;
409 $goto = 'sql.php?'
410 . PMA_generate_common_url($db, $table)
411 . '&amp;sql_query=' . urlencode($sql_query);
412 } // end if
415 * Go back to further page if table should not be dropped
417 if (isset($_REQUEST['btnDrop']) && $_REQUEST['btnDrop'] == __('No')) {
418 if (! empty($back)) {
419 $goto = $back;
421 if ($is_gotofile) {
422 if (strpos($goto, 'db_') === 0 && strlen($table)) {
423 $table = '';
425 $active_page = $goto;
426 include '' . PMA_securePath($goto);
427 } else {
428 PMA_sendHeaderLocation(
429 $cfg['PmaAbsoluteUri'] . str_replace('&amp;', '&', $goto)
432 exit();
433 } // end if
437 * Displays the confirm page if required
439 * This part of the script is bypassed if $is_js_confirmed = 1 (already checked
440 * with js) because possible security issue is not so important here: at most,
441 * the confirm message isn't displayed.
443 * Also bypassed if only showing php code.or validating a SQL query
445 // if we are coming from a "Create PHP code" or a "Without PHP Code"
446 // dialog, we won't execute the query anyway, so don't confirm
447 if (! $cfg['Confirm']
448 || isset($_REQUEST['is_js_confirmed'])
449 || isset($_REQUEST['btnDrop'])
450 || isset($GLOBALS['show_as_php'])
451 || ! empty($GLOBALS['validatequery'])
453 $do_confirm = false;
454 } else {
455 $do_confirm = isset($analyzed_sql[0]['queryflags']['need_confirm']);
458 if ($do_confirm) {
459 $stripped_sql_query = $sql_query;
460 $input = '<input type="hidden" name="%s" value="%s" />';
461 $output = '';
462 if ($is_drop_database) {
463 $output .= '<h1 class="error">';
464 $output .= __('You are about to DESTROY a complete database!');
465 $output .= '</h1>';
467 $form = '<form class="disableAjax" action="sql.php" method="post">';
468 $form .= PMA_generate_common_hidden_inputs($db, $table);
470 $form .= sprintf(
471 $input, 'sql_query', htmlspecialchars($sql_query)
473 $form .= sprintf(
474 $input, 'message_to_show',
475 (isset($message_to_show) ? PMA_sanitize($message_to_show, true) : '')
477 $form .= sprintf(
478 $input, 'goto', $goto
480 $form .= sprintf(
481 $input, 'back',
482 (isset($back) ? PMA_sanitize($back, true) : '')
484 $form .= sprintf(
485 $input, 'reload',
486 (isset($reload) ? PMA_sanitize($reload, true) : '')
488 $form .= sprintf(
489 $input, 'purge',
490 (isset($purge) ? PMA_sanitize($purge, true) : '')
492 $form .= sprintf(
493 $input, 'dropped_column',
494 (isset($dropped_column) ? PMA_sanitize($dropped_column, true) : '')
496 $form .= sprintf(
497 $input, 'show_query',
498 (isset($message_to_show) ? PMA_sanitize($show_query, true) : '')
500 $form = str_replace('%', '%%', $form) . '%s</form>';
502 $output .='<fieldset class="confirmation">'
503 .'<legend>'
504 . __('Do you really want to execute the following query?')
505 . '</legend>'
506 .'<code>' . htmlspecialchars($stripped_sql_query) . '</code>'
507 .'</fieldset>'
508 .'<fieldset class="tblFooters">';
510 $yes_input = sprintf($input, 'btnDrop', __('Yes'));
511 $yes_input .= '<input type="submit" value="' . __('Yes') . '" id="buttonYes" />';
512 $no_input = sprintf($input, 'btnDrop', __('No'));
513 $no_input .= '<input type="submit" value="' . __('No') . '" id="buttonNo" />';
515 $output .= sprintf($form, $yes_input);
516 $output .= sprintf($form, $no_input);
518 $output .='</fieldset>';
519 $output .= '';
521 PMA_Response::getInstance()->addHTML($output);
523 exit;
524 } // end if $do_confirm
527 // Defines some variables
528 // A table has to be created, renamed, dropped -> navi frame should be reloaded
530 * @todo use the parser/analyzer
533 if (empty($reload)
534 && preg_match('/^(CREATE|ALTER|DROP)\s+(VIEW|TABLE|DATABASE|SCHEMA)\s+/i', $sql_query)
536 $reload = 1;
539 // $is_group added for use in calculation of total number of rows.
540 // $is_count is changed for more correct "LIMIT" clause
541 // appending in queries like
542 // "SELECT COUNT(...) FROM ... GROUP BY ..."
545 * @todo detect all this with the parser, to avoid problems finding
546 * those strings in comments or backquoted identifiers
548 list($is_group, $is_func, $is_count, $is_export, $is_analyse, $is_explain,
549 $is_delete, $is_affected, $is_insert, $is_replace, $is_show, $is_maint)
550 = PMA_getDisplayPropertyParams(
551 $sql_query, $is_select
554 // assign default full_sql_query
555 $full_sql_query = $sql_query;
557 // Handle remembered sorting order, only for single table query
558 if ($GLOBALS['cfg']['RememberSorting']
559 && ! ($is_count || $is_export || $is_func || $is_analyse)
560 && isset($analyzed_sql[0]['select_expr'])
561 && (count($analyzed_sql[0]['select_expr']) == 0)
562 && isset($analyzed_sql[0]['queryflags']['select_from'])
563 && count($analyzed_sql[0]['table_ref']) == 1
565 PMA_handleSortOrder($db, $table, $analyzed_sql, $full_sql_query);
568 $sql_limit_to_append = '';
569 // Do append a "LIMIT" clause?
570 if (($_SESSION['tmp_user_values']['max_rows'] != 'all')
571 && ! ($is_count || $is_export || $is_func || $is_analyse)
572 && isset($analyzed_sql[0]['queryflags']['select_from'])
573 && ! isset($analyzed_sql[0]['queryflags']['offset'])
574 && empty($analyzed_sql[0]['limit_clause'])
576 $sql_limit_to_append = ' LIMIT ' . $_SESSION['tmp_user_values']['pos']
577 . ', ' . $_SESSION['tmp_user_values']['max_rows'] . " ";
578 $full_sql_query = PMA_getSqlWithLimitClause(
579 $full_sql_query,
580 $analyzed_sql,
581 $sql_limit_to_append
585 * @todo pretty printing of this modified query
587 if (isset($display_query)) {
588 // if the analysis of the original query revealed that we found
589 // a section_after_limit, we now have to analyze $display_query
590 // to display it correctly
592 if (! empty($analyzed_sql[0]['section_after_limit'])
593 && trim($analyzed_sql[0]['section_after_limit']) != ';'
595 $analyzed_display_query = PMA_SQP_analyze(
596 PMA_SQP_parse($display_query)
598 $display_query = $analyzed_display_query[0]['section_before_limit']
599 . "\n" . $sql_limit_to_append
600 . $analyzed_display_query[0]['section_after_limit'];
605 if (strlen($db)) {
606 PMA_DBI_select_db($db);
609 // E x e c u t e t h e q u e r y
611 // Only if we didn't ask to see the php code
612 if (isset($GLOBALS['show_as_php']) || ! empty($GLOBALS['validatequery'])) {
613 unset($result);
614 $num_rows = 0;
615 $unlim_num_rows = 0;
616 } else {
617 if (isset($_SESSION['profiling']) && PMA_Util::profilingSupported()) {
618 PMA_DBI_query('SET PROFILING=1;');
621 // Measure query time.
622 $querytime_before = array_sum(explode(' ', microtime()));
624 $result = @PMA_DBI_try_query($full_sql_query, null, PMA_DBI_QUERY_STORE);
626 // If a stored procedure was called, there may be more results that are
627 // queued up and waiting to be flushed from the buffer. So let's do that.
628 do {
629 PMA_DBI_store_result();
630 if (! PMA_DBI_more_results()) {
631 break;
633 } while (PMA_DBI_next_result());
635 $is_procedure = false;
637 // Since multiple query execution is anyway handled,
638 // ignore the WHERE clause of the first sql statement
639 // which might contain a phrase like 'call '
640 if (preg_match("/\bcall\b/i", $full_sql_query)
641 && empty($analyzed_sql[0]['where_clause'])
643 $is_procedure = true;
646 $querytime_after = array_sum(explode(' ', microtime()));
648 $GLOBALS['querytime'] = $querytime_after - $querytime_before;
650 // Displays an error message if required and stop parsing the script
651 $error = PMA_DBI_getError();
652 if ($error) {
653 if ($is_gotofile) {
654 if (strpos($goto, 'db_') === 0 && strlen($table)) {
655 $table = '';
657 $active_page = $goto;
658 $message = PMA_Message::rawError($error);
660 if ($GLOBALS['is_ajax_request'] == true) {
661 $response = PMA_Response::getInstance();
662 $response->isSuccess(false);
663 $response->addJSON('message', $message);
664 exit;
668 * Go to target path.
670 include '' . PMA_securePath($goto);
671 } else {
672 $full_err_url = $err_url;
673 if (preg_match('@^(db|tbl)_@', $err_url)) {
674 $full_err_url .= '&amp;show_query=1&amp;sql_query='
675 . urlencode($sql_query);
677 PMA_Util::mysqlDie($error, $full_sql_query, '', $full_err_url);
679 exit;
681 unset($error);
683 // If there are no errors and bookmarklabel was given,
684 // store the query as a bookmark
685 if (! empty($bkm_label) && ! empty($import_text)) {
686 include_once 'libraries/bookmark.lib.php';
687 $bfields = array(
688 'dbase' => $db,
689 'user' => $cfg['Bookmark']['user'],
690 'query' => urlencode($import_text),
691 'label' => $bkm_label
694 // Should we replace bookmark?
695 if (isset($bkm_replace)) {
696 $bookmarks = PMA_Bookmark_getList($db);
697 foreach ($bookmarks as $key => $val) {
698 if ($val == $bkm_label) {
699 PMA_Bookmark_delete($db, $key);
704 PMA_Bookmark_save($bfields, isset($bkm_all_users));
706 $bookmark_created = true;
707 } // end store bookmarks
709 // Gets the number of rows affected/returned
710 // (This must be done immediately after the query because
711 // mysql_affected_rows() reports about the last query done)
713 if (! $is_affected) {
714 $num_rows = ($result) ? @PMA_DBI_num_rows($result) : 0;
715 } elseif (! isset($num_rows)) {
716 $num_rows = @PMA_DBI_affected_rows();
719 // Grabs the profiling results
720 if (isset($_SESSION['profiling']) && PMA_Util::profilingSupported()) {
721 $profiling_results = PMA_DBI_fetch_result('SHOW PROFILE;');
724 // Checks if the current database has changed
725 // This could happen if the user sends a query like "USE `database`;"
727 * commented out auto-switching to active database - really required?
728 * bug #2558 win: table list disappears (mixed case db names)
729 * https://sourceforge.net/p/phpmyadmin/bugs/2558/
730 * @todo RELEASE test and comit or rollback before release
731 $current_db = PMA_DBI_fetch_value('SELECT DATABASE()');
732 if ($db !== $current_db) {
733 $db = $current_db;
734 $reload = 1;
736 unset($current_db);
739 // tmpfile remove after convert encoding appended by Y.Kawada
740 if (function_exists('PMA_kanji_file_conv')
741 && (isset($textfile) && file_exists($textfile))
743 unlink($textfile);
746 // Counts the total number of rows for the same 'SELECT' query without the
747 // 'LIMIT' clause that may have been programatically added
749 $justBrowsing = false;
750 if (empty($sql_limit_to_append)) {
751 $unlim_num_rows = $num_rows;
752 // if we did not append a limit, set this to get a correct
753 // "Showing rows..." message
754 //$_SESSION['tmp_user_values']['max_rows'] = 'all';
755 } elseif ($is_select) {
757 // c o u n t q u e r y
759 // If we are "just browsing", there is only one table,
760 // and no WHERE clause (or just 'WHERE 1 '),
761 // we do a quick count (which uses MaxExactCount) because
762 // SQL_CALC_FOUND_ROWS is not quick on large InnoDB tables
764 // However, do not count again if we did it previously
765 // due to $find_real_end == true
766 if (! $is_group
767 && ! isset($analyzed_sql[0]['queryflags']['union'])
768 && ! isset($analyzed_sql[0]['queryflags']['distinct'])
769 && ! isset($analyzed_sql[0]['table_ref'][1]['table_name'])
770 && (empty($analyzed_sql[0]['where_clause'])
771 || $analyzed_sql[0]['where_clause'] == '1 ')
772 && ! isset($find_real_end)
774 // "j u s t b r o w s i n g"
775 $justBrowsing = true;
776 $unlim_num_rows = PMA_Table::countRecords(
777 $db,
778 $table,
779 $force_exact = true
782 } else { // n o t " j u s t b r o w s i n g "
784 // add select expression after the SQL_CALC_FOUND_ROWS
786 // for UNION, just adding SQL_CALC_FOUND_ROWS
787 // after the first SELECT works.
789 // take the left part, could be:
790 // SELECT
791 // (SELECT
792 $count_query = PMA_SQP_formatHtml(
793 $parsed_sql,
794 'query_only',
796 $analyzed_sql[0]['position_of_first_select'] + 1
798 $count_query .= ' SQL_CALC_FOUND_ROWS ';
799 // add everything that was after the first SELECT
800 $count_query .= PMA_SQP_formatHtml(
801 $parsed_sql,
802 'query_only',
803 $analyzed_sql[0]['position_of_first_select'] + 1
805 // ensure there is no semicolon at the end of the
806 // count query because we'll probably add
807 // a LIMIT 1 clause after it
808 $count_query = rtrim($count_query);
809 $count_query = rtrim($count_query, ';');
811 // if using SQL_CALC_FOUND_ROWS, add a LIMIT to avoid
812 // long delays. Returned count will be complete anyway.
813 // (but a LIMIT would disrupt results in an UNION)
815 if (! isset($analyzed_sql[0]['queryflags']['union'])) {
816 $count_query .= ' LIMIT 1';
819 // run the count query
821 PMA_DBI_try_query($count_query);
822 // if (mysql_error()) {
823 // void.
824 // I tried the case
825 // (SELECT `User`, `Host`, `Db`, `Select_priv` FROM `db`)
826 // UNION (SELECT `User`, `Host`, "%" AS "Db",
827 // `Select_priv`
828 // FROM `user`) ORDER BY `User`, `Host`, `Db`;
829 // and although the generated count_query is wrong
830 // the SELECT FOUND_ROWS() work! (maybe it gets the
831 // count from the latest query that worked)
833 // another case where the count_query is wrong:
834 // SELECT COUNT(*), f1 from t1 group by f1
835 // and you click to sort on count(*)
836 // }
837 $unlim_num_rows = PMA_DBI_fetch_value('SELECT FOUND_ROWS()');
838 } // end else "just browsing"
840 } else { // not $is_select
841 $unlim_num_rows = 0;
842 } // end rows total count
844 // if a table or database gets dropped, check column comments.
845 if (isset($purge) && $purge == '1') {
847 * Cleanup relations.
849 include_once 'libraries/relation_cleanup.lib.php';
851 if (strlen($table) && strlen($db)) {
852 PMA_relationsCleanupTable($db, $table);
853 } elseif (strlen($db)) {
854 PMA_relationsCleanupDatabase($db);
855 } else {
856 // VOID. No DB/Table gets deleted.
857 } // end if relation-stuff
858 } // end if ($purge)
860 // If a column gets dropped, do relation magic.
861 if (isset($dropped_column)
862 && strlen($db)
863 && strlen($table)
864 && ! empty($dropped_column)
866 include_once 'libraries/relation_cleanup.lib.php';
867 PMA_relationsCleanupColumn($db, $table, $dropped_column);
868 // to refresh the list of indexes (Ajax mode)
869 $extra_data['indexes_list'] = PMA_Index::getView($table, $db);
870 } // end if column was dropped
871 } // end else "didn't ask to see php code"
873 // No rows returned -> move back to the calling page
874 if ((0 == $num_rows && 0 == $unlim_num_rows) || $is_affected) {
875 // Delete related tranformation information
876 if (!empty($analyzed_sql[0]['querytype'])
877 && (($analyzed_sql[0]['querytype'] == 'ALTER')
878 || ($analyzed_sql[0]['querytype'] == 'DROP'))
880 include_once 'libraries/transformations.lib.php';
881 if ($analyzed_sql[0]['querytype'] == 'ALTER') {
882 if (stripos($analyzed_sql[0]['unsorted_query'], 'DROP') !== false) {
883 $drop_column = PMA_getColumnNameInColumnDropSql(
884 $analyzed_sql[0]['unsorted_query']
887 if ($drop_column != '') {
888 PMA_clearTransformations($db, $table, $drop_column);
892 } else if (($analyzed_sql[0]['querytype'] == 'DROP') && ($table != '')) {
893 PMA_clearTransformations($db, $table);
897 if ($is_delete) {
898 $message = PMA_Message::getMessageForDeletedRows($num_rows);
899 } elseif ($is_insert) {
900 if ($is_replace) {
901 // For replace we get DELETED + INSERTED row count,
902 // so we have to call it affected
903 $message = PMA_Message::getMessageForAffectedRows($num_rows);
904 } else {
905 $message = PMA_Message::getMessageForInsertedRows($num_rows);
907 $insert_id = PMA_DBI_insert_id();
908 if ($insert_id != 0) {
909 // insert_id is id of FIRST record inserted in one insert,
910 // so if we inserted multiple rows, we had to increment this
911 $message->addMessage('[br]');
912 // need to use a temporary because the Message class
913 // currently supports adding parameters only to the first
914 // message
915 $_inserted = PMA_Message::notice(__('Inserted row id: %1$d'));
916 $_inserted->addParam($insert_id + $num_rows - 1);
917 $message->addMessage($_inserted);
919 } elseif ($is_affected) {
920 $message = PMA_Message::getMessageForAffectedRows($num_rows);
922 // Ok, here is an explanation for the !$is_select.
923 // The form generated by sql_query_form.lib.php
924 // and db_sql.php has many submit buttons
925 // on the same form, and some confusion arises from the
926 // fact that $message_to_show is sent for every case.
927 // The $message_to_show containing a success message and sent with
928 // the form should not have priority over errors
929 } elseif (! empty($message_to_show) && ! $is_select) {
930 $message = PMA_Message::rawSuccess(htmlspecialchars($message_to_show));
931 } elseif (! empty($GLOBALS['show_as_php'])) {
932 $message = PMA_Message::success(__('Showing as PHP code'));
933 } elseif (isset($GLOBALS['show_as_php'])) {
934 /* User disable showing as PHP, query is only displayed */
935 $message = PMA_Message::notice(__('Showing SQL query'));
936 } elseif (! empty($GLOBALS['validatequery'])) {
937 $message = PMA_Message::notice(__('Validated SQL'));
938 } else {
939 $message = PMA_Message::success(
940 __('MySQL returned an empty result set (i.e. zero rows).')
944 if (isset($GLOBALS['querytime'])) {
945 $_querytime = PMA_Message::notice('(' . __('Query took %01.4f sec') . ')');
946 $_querytime->addParam($GLOBALS['querytime']);
947 $message->addMessage($_querytime);
950 if ($GLOBALS['is_ajax_request'] == true) {
951 if ($cfg['ShowSQL']) {
952 $extra_data['sql_query'] = PMA_Util::getMessage(
953 $message, $GLOBALS['sql_query'], 'success'
956 if (isset($GLOBALS['reload']) && $GLOBALS['reload'] == 1) {
957 $extra_data['reload'] = 1;
958 $extra_data['db'] = $GLOBALS['db'];
960 $response = PMA_Response::getInstance();
961 $response->isSuccess($message->isSuccess());
962 // No need to manually send the message
963 // The Response class will handle that automatically
964 $response->addJSON(isset($extra_data) ? $extra_data : array());
965 if (empty($_REQUEST['ajax_page_request'])) {
966 $response->addJSON('message', $message);
967 exit;
971 if ($is_gotofile) {
972 $goto = PMA_securePath($goto);
973 // Checks for a valid target script
974 $is_db = $is_table = false;
975 if (isset($_REQUEST['purge']) && $_REQUEST['purge'] == '1') {
976 $table = '';
977 unset($url_params['table']);
979 include 'libraries/db_table_exists.lib.php';
981 if (strpos($goto, 'tbl_') === 0 && ! $is_table) {
982 if (strlen($table)) {
983 $table = '';
985 $goto = 'db_sql.php';
987 if (strpos($goto, 'db_') === 0 && ! $is_db) {
988 if (strlen($db)) {
989 $db = '';
991 $goto = 'index.php';
993 // Loads to target script
994 if (strlen($goto) > 0) {
995 $active_page = $goto;
996 include '' . $goto;
997 } else {
998 // Echo at least one character to prevent showing last page from history
999 echo " ";
1002 } else {
1003 // avoid a redirect loop when last record was deleted
1004 if (0 == $num_rows && 'sql.php' == $cfg['DefaultTabTable']) {
1005 $goto = str_replace('sql.php', 'tbl_structure.php', $goto);
1007 PMA_sendHeaderLocation(
1008 $cfg['PmaAbsoluteUri'] . str_replace('&amp;', '&', $goto)
1009 . '&message=' . urlencode($message)
1011 } // end else
1012 exit();
1013 // end no rows returned
1014 } else {
1015 // At least one row is returned -> displays a table with results
1016 //If we are retrieving the full value of a truncated field or the original
1017 // value of a transformed field, show it here and exit
1018 if ($GLOBALS['grid_edit'] == true) {
1019 $row = PMA_DBI_fetch_row($result);
1020 $response = PMA_Response::getInstance();
1021 $response->addJSON('value', $row[0]);
1022 exit;
1025 if (isset($_REQUEST['ajax_request']) && isset($_REQUEST['table_maintenance'])) {
1026 $response = PMA_Response::getInstance();
1027 $header = $response->getHeader();
1028 $scripts = $header->getScripts();
1029 $scripts->addFile('makegrid.js');
1030 $scripts->addFile('sql.js');
1032 // Gets the list of fields properties
1033 if (isset($result) && $result) {
1034 $fields_meta = PMA_DBI_get_fields_meta($result);
1035 $fields_cnt = count($fields_meta);
1038 if (empty($disp_mode)) {
1039 // see the "PMA_setDisplayMode()" function in
1040 // libraries/DisplayResults.class.php
1041 $disp_mode = 'urdr111101';
1044 // hide edit and delete links for information_schema
1045 if (PMA_is_system_schema($db)) {
1046 $disp_mode = 'nnnn110111';
1049 if (isset($message)) {
1050 $message = PMA_Message::success($message);
1051 echo PMA_Util::getMessage(
1052 $message, $GLOBALS['sql_query'], 'success'
1056 // Should be initialized these parameters before parsing
1057 $showtable = isset($showtable) ? $showtable : null;
1058 $printview = isset($printview) ? $printview : null;
1059 $url_query = isset($url_query) ? $url_query : null;
1061 if (!empty($sql_data) && ($sql_data['valid_queries'] > 1)) {
1063 $_SESSION['is_multi_query'] = true;
1064 echo getTableHtmlForMultipleQueries(
1065 $displayResultsObject, $db, $sql_data, $goto,
1066 $pmaThemeImage, $text_dir, $printview, $url_query,
1067 $disp_mode, $sql_limit_to_append, false
1069 } else {
1070 $_SESSION['is_multi_query'] = false;
1071 $displayResultsObject->setProperties(
1072 $unlim_num_rows, $fields_meta, $is_count, $is_export, $is_func,
1073 $is_analyse, $num_rows, $fields_cnt, $querytime, $pmaThemeImage,
1074 $text_dir, $is_maint, $is_explain, $is_show, $showtable,
1075 $printview, $url_query, false
1078 echo $displayResultsObject->getTable(
1079 $result, $disp_mode, $analyzed_sql
1081 exit();
1085 // Displays the headers
1086 if (isset($show_query)) {
1087 unset($show_query);
1089 if (isset($printview) && $printview == '1') {
1090 PMA_Util::checkParameters(array('db', 'full_sql_query'));
1092 $response = PMA_Response::getInstance();
1093 $header = $response->getHeader();
1094 $header->enablePrintView();
1096 $hostname = '';
1097 if ($cfg['Server']['verbose']) {
1098 $hostname = $cfg['Server']['verbose'];
1099 } else {
1100 $hostname = $cfg['Server']['host'];
1101 if (! empty($cfg['Server']['port'])) {
1102 $hostname .= $cfg['Server']['port'];
1106 $versions = "phpMyAdmin&nbsp;" . PMA_VERSION;
1107 $versions .= "&nbsp;/&nbsp;";
1108 $versions .= "MySQL&nbsp;" . PMA_MYSQL_STR_VERSION;
1110 echo "<h1>" . __('SQL result') . "</h1>";
1111 echo "<p>";
1112 echo "<strong>" . __('Host') . ":</strong> $hostname<br />";
1113 echo "<strong>" . __('Database') . ":</strong> "
1114 . htmlspecialchars($db) . "<br />";
1115 echo "<strong>" . __('Generation Time') . ":</strong> "
1116 . PMA_Util::localisedDate() . "<br />";
1117 echo "<strong>" . __('Generated by') . ":</strong> $versions<br />";
1118 echo "<strong>" . __('SQL query') . ":</strong> "
1119 . htmlspecialchars($full_sql_query) . ";";
1120 if (isset($num_rows)) {
1121 echo "<br />";
1122 echo "<strong>" . __('Rows') . ":</strong> $num_rows";
1124 echo "</p>";
1125 } else {
1126 $response = PMA_Response::getInstance();
1127 $header = $response->getHeader();
1128 $scripts = $header->getScripts();
1129 $scripts->addFile('makegrid.js');
1130 $scripts->addFile('sql.js');
1132 unset($message);
1134 if (! $GLOBALS['is_ajax_request']) {
1135 if (strlen($table)) {
1136 include 'libraries/tbl_common.inc.php';
1137 $url_query .= '&amp;goto=tbl_sql.php&amp;back=tbl_sql.php';
1138 include 'libraries/tbl_info.inc.php';
1139 } elseif (strlen($db)) {
1140 include 'libraries/db_common.inc.php';
1141 include 'libraries/db_info.inc.php';
1142 } else {
1143 include 'libraries/server_common.inc.php';
1145 } else {
1146 //we don't need to buffer the output in getMessage here.
1147 //set a global variable and check against it in the function
1148 $GLOBALS['buffer_message'] = false;
1152 if (strlen($db)) {
1153 $cfgRelation = PMA_getRelationsParam();
1156 // Gets the list of fields properties
1157 if (isset($result) && $result) {
1158 $fields_meta = PMA_DBI_get_fields_meta($result);
1159 $fields_cnt = count($fields_meta);
1162 //begin the sqlqueryresults div here. container div
1163 echo '<div id="sqlqueryresults"';
1164 echo ' class="ajax"';
1165 echo '>';
1167 // Display previous update query (from tbl_replace)
1168 if (isset($disp_query) && ($cfg['ShowSQL'] == true) && empty($sql_data)) {
1169 echo PMA_Util::getMessage($disp_message, $disp_query, 'success');
1172 if (isset($profiling_results)) {
1173 // pma_token/url_query needed for chart export
1174 echo '<script type="text/javascript">';
1175 echo 'pma_token = \'' . $_SESSION[' PMA_token '] . '\';';
1176 echo 'url_query = \''
1177 . (isset($url_query) ? $url_query : PMA_generate_common_url($db))
1178 . '\';';
1179 echo 'AJAX.registerOnload(\'sql.js\',makeProfilingChart);';
1180 echo '</script>';
1182 echo '<fieldset><legend>' . __('Profiling') . '</legend>' . "\n";
1183 echo '<div style="float: left;">';
1184 echo '<table>' . "\n";
1185 echo ' <tr>' . "\n";
1186 echo ' <th>' . __('Status')
1187 . PMA_Util::showMySQLDocu(
1188 'general-thread-states', 'general-thread-states'
1190 . '</th>' . "\n";
1191 echo ' <th>' . __('Time') . '</th>' . "\n";
1192 echo ' </tr>' . "\n";
1194 $chart_json = Array();
1195 foreach ($profiling_results as $one_result) {
1196 echo ' <tr>' . "\n";
1197 echo '<td>' . ucwords($one_result['Status']) . '</td>' . "\n";
1198 echo '<td class="right">'
1199 . (PMA_Util::formatNumber($one_result['Duration'], 3, 1))
1200 . 's</td>' . "\n";
1201 if (isset($chart_json[ucwords($one_result['Status'])])) {
1202 $chart_json[ucwords($one_result['Status'])]
1203 += $one_result['Duration'];
1204 } else {
1205 $chart_json[ucwords($one_result['Status'])]
1206 = $one_result['Duration'];
1210 echo '</table>' . "\n";
1211 echo '</div>';
1212 //require_once 'libraries/chart.lib.php';
1213 echo '<div id="profilingChartData" style="display:none;">';
1214 echo json_encode($chart_json);
1215 echo '</div>';
1216 echo '<div id="profilingchart" style="display:none;">';
1217 echo '</div>';
1218 echo '<script type="text/javascript">';
1219 echo 'if($.jqplot !== undefined && $.jqplot.PieRenderer !== undefined) {';
1220 echo 'makeProfilingChart();';
1221 echo '}';
1222 echo '</script>';
1223 echo '</fieldset>' . "\n";
1226 // Displays the results in a table
1227 if (empty($disp_mode)) {
1228 // see the "PMA_setDisplayMode()" function in
1229 // libraries/DisplayResults.class.php
1230 $disp_mode = 'urdr111101';
1233 $resultSetContainsUniqueKey = PMA_resultSetContainsUniqueKey(
1234 $db, $table, $fields_meta
1237 // hide edit and delete links:
1238 // - for information_schema
1239 // - if the result set does not contain all the columns of a unique key
1240 // and we are not just browing all the columns of an updatable view
1241 $updatableView
1242 = $justBrowsing
1243 && trim($analyzed_sql[0]['select_expr_clause']) == '*'
1244 && PMA_Table::isUpdatableView($db, $table);
1245 $editable = $resultSetContainsUniqueKey || $updatableView;
1246 if (!empty($table) && (PMA_is_system_schema($db) || !$editable)) {
1247 $disp_mode = 'nnnn110111';
1248 $msg = PMA_message::notice(
1250 'This table does not contain a unique column.'
1251 . ' Grid edit, checkbox, Edit, Copy and Delete features'
1252 . ' are not available.'
1255 $msg->display();
1258 if (isset($label)) {
1259 $msg = PMA_message::success(__('Bookmark %s created'));
1260 $msg->addParam($label);
1261 $msg->display();
1264 // Should be initialized these parameters before parsing
1265 $showtable = isset($showtable) ? $showtable : null;
1266 $printview = isset($printview) ? $printview : null;
1267 $url_query = isset($url_query) ? $url_query : null;
1269 if (! empty($sql_data) && ($sql_data['valid_queries'] > 1) || $is_procedure) {
1271 $_SESSION['is_multi_query'] = true;
1272 echo getTableHtmlForMultipleQueries(
1273 $displayResultsObject, $db, $sql_data, $goto,
1274 $pmaThemeImage, $text_dir, $printview, $url_query,
1275 $disp_mode, $sql_limit_to_append, $editable
1277 } else {
1278 $_SESSION['is_multi_query'] = false;
1279 $displayResultsObject->setProperties(
1280 $unlim_num_rows, $fields_meta, $is_count, $is_export, $is_func,
1281 $is_analyse, $num_rows, $fields_cnt, $querytime, $pmaThemeImage,
1282 $text_dir, $is_maint, $is_explain, $is_show, $showtable,
1283 $printview, $url_query, $editable
1286 echo $displayResultsObject->getTable($result, $disp_mode, $analyzed_sql);
1287 PMA_DBI_free_result($result);
1290 // BEGIN INDEX CHECK See if indexes should be checked.
1291 if (isset($query_type)
1292 && $query_type == 'check_tbl'
1293 && isset($selected)
1294 && is_array($selected)
1296 foreach ($selected as $idx => $tbl_name) {
1297 $check = PMA_Index::findDuplicates($tbl_name, $db);
1298 if (! empty($check)) {
1299 printf(__('Problems with indexes of table `%s`'), $tbl_name);
1300 echo $check;
1303 } // End INDEX CHECK
1305 // Bookmark support if required
1306 if ($disp_mode[7] == '1'
1307 && (! empty($cfg['Bookmark']) && empty($id_bookmark))
1308 && ! empty($sql_query)
1310 echo "\n";
1311 $goto = 'sql.php?'
1312 . PMA_generate_common_url($db, $table)
1313 . '&amp;sql_query=' . urlencode($sql_query)
1314 . '&amp;id_bookmark=1';
1316 echo '<form action="sql.php" method="post"'
1317 . ' onsubmit="return ! emptyFormElements(this, \'fields[label]\');"'
1318 . ' id="bookmarkQueryForm">';
1319 echo PMA_generate_common_hidden_inputs();
1320 echo '<input type="hidden" name="goto" value="' . $goto . '" />';
1321 echo '<input type="hidden" name="fields[dbase]"'
1322 . ' value="' . htmlspecialchars($db) . '" />';
1323 echo '<input type="hidden" name="fields[user]"'
1324 . ' value="' . $cfg['Bookmark']['user'] . '" />';
1325 echo '<input type="hidden" name="fields[query]"' . ' value="'
1326 . urlencode(isset($complete_query) ? $complete_query : $sql_query)
1327 . '" />';
1328 echo '<fieldset>';
1329 echo '<legend>';
1330 echo PMA_Util::getIcon(
1331 'b_bookmark.png', __('Bookmark this SQL query'), true
1333 echo '</legend>';
1334 echo '<div class="formelement">';
1335 echo '<label for="fields_label_">' . __('Label') . ':</label>';
1336 echo '<input type="text" id="fields_label_"'
1337 . ' name="fields[label]" value="" />';
1338 echo '</div>';
1339 echo '<div class="formelement">';
1340 echo '<input type="checkbox" name="bkm_all_users"'
1341 . ' id="bkm_all_users" value="true" />';
1342 echo '<label for="bkm_all_users">'
1343 . __('Let every user access this bookmark')
1344 . '</label>';
1345 echo '</div>';
1346 echo '<div class="clearfloat"></div>';
1347 echo '</fieldset>';
1348 echo '<fieldset class="tblFooters">';
1349 echo '<input type="hidden" name="store_bkm" value="1" />';
1350 echo '<input type="submit"'
1351 . ' value="' . __('Bookmark this SQL query') . '" />';
1352 echo '</fieldset>';
1353 echo '</form>';
1354 } // end bookmark support
1356 // Do print the page if required
1357 if (isset($printview) && $printview == '1') {
1358 echo PMA_Util::getButton();
1359 } // end print case
1360 echo '</div>'; // end sqlqueryresults div
1361 } // end rows returned
1363 $_SESSION['is_multi_query'] = false;
1366 * Displays the footer
1368 if (! isset($_REQUEST['table_maintenance'])) {
1369 exit;
1373 // These functions will need for use set the required parameters for display results
1376 * Initialize some parameters needed to display results
1378 * @param string $sql_query SQL statement
1379 * @param boolean $is_select select query or not
1381 * @return array set of parameters
1383 * @access public
1385 function PMA_getDisplayPropertyParams($sql_query, $is_select)
1387 $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;
1389 if ($is_select) {
1390 $is_group = preg_match('@(GROUP[[:space:]]+BY|HAVING|SELECT[[:space:]]+DISTINCT)[[:space:]]+@i', $sql_query);
1391 $is_func = ! $is_group && (preg_match('@[[:space:]]+(SUM|AVG|STD|STDDEV|MIN|MAX|BIT_OR|BIT_AND)\s*\(@i', $sql_query));
1392 $is_count = ! $is_group && (preg_match('@^SELECT[[:space:]]+COUNT\((.*\.+)?.*\)@i', $sql_query));
1393 $is_export = preg_match('@[[:space:]]+INTO[[:space:]]+OUTFILE[[:space:]]+@i', $sql_query);
1394 $is_analyse = preg_match('@[[:space:]]+PROCEDURE[[:space:]]+ANALYSE@i', $sql_query);
1395 } elseif (preg_match('@^EXPLAIN[[:space:]]+@i', $sql_query)) {
1396 $is_explain = true;
1397 } elseif (preg_match('@^DELETE[[:space:]]+@i', $sql_query)) {
1398 $is_delete = true;
1399 $is_affected = true;
1400 } elseif (preg_match('@^(INSERT|LOAD[[:space:]]+DATA|REPLACE)[[:space:]]+@i', $sql_query)) {
1401 $is_insert = true;
1402 $is_affected = true;
1403 if (preg_match('@^(REPLACE)[[:space:]]+@i', $sql_query)) {
1404 $is_replace = true;
1406 } elseif (preg_match('@^UPDATE[[:space:]]+@i', $sql_query)) {
1407 $is_affected = true;
1408 } elseif (preg_match('@^[[:space:]]*SHOW[[:space:]]+@i', $sql_query)) {
1409 $is_show = true;
1410 } elseif (preg_match('@^(CHECK|ANALYZE|REPAIR|OPTIMIZE)[[:space:]]+TABLE[[:space:]]+@i', $sql_query)) {
1411 $is_maint = true;
1414 return array(
1415 $is_group, $is_func, $is_count, $is_export, $is_analyse, $is_explain,
1416 $is_delete, $is_affected, $is_insert, $is_replace,$is_show, $is_maint
1421 * Get the database name inside a USE query
1423 * @param string $sql SQL query
1424 * @param array $databases array with all databases
1426 * @return strin $db new database name
1428 function PMA_getNewDatabase($sql, $databases)
1430 $db = '';
1431 // loop through all the databases
1432 foreach ($databases as $database) {
1433 if (strpos($sql, $database['SCHEMA_NAME']) !== false) {
1434 $db = $database;
1435 break;
1438 return $db;
1442 * Get the table name in a sql query
1443 * If there are several tables in the SQL query,
1444 * first table wil lreturn
1446 * @param string $sql SQL query
1447 * @param array $tables array of names in current database
1449 * @return string $table table name
1451 function PMA_getTableNameBySQL($sql, $tables)
1453 $table = '';
1455 // loop through all the tables in the database
1456 foreach ($tables as $tbl) {
1457 if (strpos($sql, $tbl)) {
1458 $table .= ' ' . $tbl;
1462 if (count(explode(' ', trim($table))) > 1) {
1463 $tmp_array = explode(' ', trim($table));
1464 return $tmp_array[0];
1467 return trim($table);
1472 * Generate table html when SQL statement have multiple queries
1473 * which return displayable results
1475 * @param PMA_DisplayResults $displayResultsObject object
1476 * @param string $db database name
1477 * @param array $sql_data information about SQL statement
1478 * @param string $goto URL to go back in case of errors
1479 * @param string $pmaThemeImage path for theme images directory
1480 * @param string $text_dir text direction
1481 * @param string $printview whether printview is enabled
1482 * @param string $url_query URL query
1483 * @param array $disp_mode the display mode
1484 * @param string $sql_limit_to_append limit clause
1485 * @param bool $editable whether result set is editable
1487 * @return string $table_html html content
1489 function getTableHtmlForMultipleQueries(
1490 $displayResultsObject, $db, $sql_data, $goto, $pmaThemeImage,
1491 $text_dir, $printview, $url_query, $disp_mode, $sql_limit_to_append,
1492 $editable
1494 $table_html = '';
1496 $tables_array = PMA_DBI_get_tables($db);
1497 $databases_array = PMA_DBI_get_databases_full();
1498 $multi_sql = implode(";", $sql_data['valid_sql']);
1499 $querytime_before = array_sum(explode(' ', microtime()));
1501 // Assignment for variable is not needed since the results are
1502 // looiping using the connection
1503 @PMA_DBI_try_multi_query($multi_sql);
1505 $querytime_after = array_sum(explode(' ', microtime()));
1506 $querytime = $querytime_after - $querytime_before;
1507 $sql_no = 0;
1509 do {
1510 $analyzed_sql = array();
1511 $is_affected = false;
1513 $result = PMA_DBI_store_result();
1514 $fields_meta = ($result !== false)
1515 ? PMA_DBI_get_fields_meta($result)
1516 : array();
1517 $fields_cnt = count($fields_meta);
1519 // Initialize needed params related to each query in multiquery statement
1520 if (isset($sql_data['valid_sql'][$sql_no])) {
1521 // 'Use' query can change the database
1522 if (stripos($sql_data['valid_sql'][$sql_no], "use ")) {
1523 $db = PMA_getNewDatabase(
1524 $sql_data['valid_sql'][$sql_no],
1525 $databases_array
1528 $parsed_sql = PMA_SQP_parse($sql_data['valid_sql'][$sql_no]);
1529 $table = PMA_getTableNameBySQL(
1530 $sql_data['valid_sql'][$sql_no],
1531 $tables_array
1534 $analyzed_sql = PMA_SQP_analyze($parsed_sql);
1535 $is_select = isset($analyzed_sql[0]['queryflags']['select_from']);
1536 $unlim_num_rows = PMA_Table::countRecords($db, $table, true);
1537 $showtable = PMA_Table::sGetStatusInfo($db, $table, null, true);
1538 $url_query = PMA_generate_common_url($db, $table);
1540 list($is_group, $is_func, $is_count, $is_export, $is_analyse,
1541 $is_explain, $is_delete, $is_affected, $is_insert, $is_replace,
1542 $is_show, $is_maint)
1543 = PMA_getDisplayPropertyParams(
1544 $sql_data['valid_sql'][$sql_no], $is_select
1547 // Handle remembered sorting order, only for single table query
1548 if ($GLOBALS['cfg']['RememberSorting']
1549 && ! ($is_count || $is_export || $is_func || $is_analyse)
1550 && isset($analyzed_sql[0]['select_expr'])
1551 && (count($analyzed_sql[0]['select_expr']) == 0)
1552 && isset($analyzed_sql[0]['queryflags']['select_from'])
1553 && count($analyzed_sql[0]['table_ref']) == 1
1555 PMA_handleSortOrder(
1556 $db,
1557 $table,
1558 $analyzed_sql,
1559 $sql_data['valid_sql'][$sql_no]
1563 // Do append a "LIMIT" clause?
1564 if (($_SESSION['tmp_user_values']['max_rows'] != 'all')
1565 && ! ($is_count || $is_export || $is_func || $is_analyse)
1566 && isset($analyzed_sql[0]['queryflags']['select_from'])
1567 && ! isset($analyzed_sql[0]['queryflags']['offset'])
1568 && empty($analyzed_sql[0]['limit_clause'])
1570 $sql_limit_to_append = ' LIMIT '
1571 . $_SESSION['tmp_user_values']['pos']
1572 . ', ' . $_SESSION['tmp_user_values']['max_rows'] . " ";
1573 $sql_data['valid_sql'][$sql_no] = PMA_getSqlWithLimitClause(
1574 $sql_data['valid_sql'][$sql_no],
1575 $analyzed_sql,
1576 $sql_limit_to_append
1580 // Set the needed properties related to executing sql query
1581 $displayResultsObject->__set('db', $db);
1582 $displayResultsObject->__set('table', $table);
1583 $displayResultsObject->__set('goto', $goto);
1586 if (! $is_affected) {
1587 $num_rows = ($result) ? @PMA_DBI_num_rows($result) : 0;
1588 } elseif (! isset($num_rows)) {
1589 $num_rows = @PMA_DBI_affected_rows();
1592 if (isset($sql_data['valid_sql'][$sql_no])) {
1594 $displayResultsObject->__set(
1595 'sql_query',
1596 $sql_data['valid_sql'][$sql_no]
1598 $displayResultsObject->setProperties(
1599 $unlim_num_rows, $fields_meta, $is_count, $is_export, $is_func,
1600 $is_analyse, $num_rows, $fields_cnt, $querytime, $pmaThemeImage,
1601 $text_dir, $is_maint, $is_explain, $is_show, $showtable,
1602 $printview, $url_query, $editable
1606 if ($num_rows == 0) {
1607 continue;
1610 // With multiple results, operations are limied
1611 $disp_mode = 'nnnn000000';
1612 $is_limited_display = true;
1614 // Collect the tables
1615 $table_html .= $displayResultsObject->getTable(
1616 $result, $disp_mode, $analyzed_sql, $is_limited_display
1619 // Free the result to save the memory
1620 PMA_DBI_free_result($result);
1622 $sql_no++;
1624 } while (PMA_DBI_more_results() && PMA_DBI_next_result());
1626 return $table_html;
1630 * Handle remembered sorting order, only for single table query
1632 * @param string $db database name
1633 * @param string $table table name
1634 * @param array &$analyzed_sql the analyzed query
1635 * @param string &$full_sql_query SQL query
1637 * @return void
1639 function PMA_handleSortOrder($db, $table, &$analyzed_sql, &$full_sql_query)
1641 $pmatable = new PMA_Table($table, $db);
1642 if (empty($analyzed_sql[0]['order_by_clause'])) {
1643 $sorted_col = $pmatable->getUiProp(PMA_Table::PROP_SORTED_COLUMN);
1644 if ($sorted_col) {
1645 // retrieve the remembered sorting order for current table
1646 $sql_order_to_append = ' ORDER BY ' . $sorted_col . ' ';
1647 $full_sql_query = $analyzed_sql[0]['section_before_limit']
1648 . $sql_order_to_append . $analyzed_sql[0]['limit_clause']
1649 . ' ' . $analyzed_sql[0]['section_after_limit'];
1651 // update the $analyzed_sql
1652 $analyzed_sql[0]['section_before_limit'] .= $sql_order_to_append;
1653 $analyzed_sql[0]['order_by_clause'] = $sorted_col;
1655 } else {
1656 // store the remembered table into session
1657 $pmatable->setUiProp(
1658 PMA_Table::PROP_SORTED_COLUMN,
1659 $analyzed_sql[0]['order_by_clause']
1665 * Append limit clause to SQL query
1667 * @param string $full_sql_query SQL query
1668 * @param array $analyzed_sql the analyzed query
1669 * @param string $sql_limit_to_append clause to append
1671 * @return string limit clause appended SQL query
1673 function PMA_getSqlWithLimitClause($full_sql_query, $analyzed_sql,
1674 $sql_limit_to_append
1676 return $analyzed_sql[0]['section_before_limit'] . "\n"
1677 . $sql_limit_to_append . $analyzed_sql[0]['section_after_limit'];
1682 * Get column name from a drop SQL statement
1684 * @param string $sql SQL query
1686 * @return string $drop_column Name of the column
1688 function PMA_getColumnNameInColumnDropSql($sql)
1690 $tmpArray1 = explode('DROP', $sql);
1691 $str_to_check = trim($tmpArray1[1]);
1693 if (stripos($str_to_check, 'COLUMN') !== false) {
1694 $tmpArray2 = explode('COLUMN', $str_to_check);
1695 $str_to_check = trim($tmpArray2[1]);
1698 $tmpArray3 = explode(' ', $str_to_check);
1699 $str_to_check = trim($tmpArray3[0]);
1701 $drop_column = str_replace(';', '', trim($str_to_check));
1702 $drop_column = str_replace('`', '', $drop_column);
1704 return $drop_column;
1708 * Verify whether the result set contains all the columns
1709 * of at least one unique key
1711 * @param string $db database name
1712 * @param string $table table name
1713 * @param string $fields_meta meta fields
1715 * @return boolean whether the result set contains a unique key
1717 function PMA_resultSetContainsUniqueKey($db, $table, $fields_meta)
1719 $resultSetColumnNames = array();
1720 foreach ($fields_meta as $oneMeta) {
1721 $resultSetColumnNames[] = $oneMeta->name;
1723 foreach (PMA_Index::getFromTable($table, $db) as $index) {
1724 if ($index->isUnique()) {
1725 $indexColumns = $index->getColumns();
1726 $numberFound = 0;
1727 foreach ($indexColumns as $indexColumnName => $dummy) {
1728 if (in_array($indexColumnName, $resultSetColumnNames)) {
1729 $numberFound++;
1732 if ($numberFound == count($indexColumns)) {
1733 return true;
1737 return false;