2 /* vim: set expandtab sw=4 ts=4 sts=4: */
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
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');
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);
38 * Sets globals from $_POST
45 foreach ($post_params as $one_post_param) {
46 if (isset($_POST[$one_post_param])) {
47 $GLOBALS[$one_post_param] = $_POST[$one_post_param];
52 * Sets globals from $_GET
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;
75 * Defines the url to return to in case of error in a sql statement
79 $is_gotofile = preg_replace('@^([^?]+).*$@s', '\\1', $goto);
80 if (! @file_exists
('' . $is_gotofile)) {
83 $is_gotofile = ($is_gotofile == $goto);
87 $goto = $cfg['DefaultTabDatabase'];
89 $goto = $cfg['DefaultTabTable'];
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 ?
'&table=' . urlencode($table)
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'];
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(
153 $dropdown = '<span class="curr_value">'
154 . htmlspecialchars($_REQUEST['curr_value'])
156 . '<a href="browse_foreigners.php'
157 . PMA_generate_common_url($_url_params) . '"'
158 . ' target="_blank" class="browse_foreign" ' .'>'
159 . __('Browse foreign values')
162 $dropdown = PMA_foreignDropdown(
163 $foreignData['disp_row'],
164 $foreignData['foreign_field'],
165 $foreignData['foreign_display'],
167 $cfg['ForeignKeyMaxLimit']
169 $dropdown = '<select>' . $dropdown . '</select>';
172 $response = PMA_Response
::getInstance();
173 $response->addJSON('dropdown', $dropdown);
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=""> </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);
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']);
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);
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);
255 if (isset($_REQUEST['col_order'])) {
256 $col_order = explode(',', $_REQUEST['col_order']);
257 $retval = $pmatable->setUiProp(
258 PMA_Table
::PROP_COLUMN_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());
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());
285 $response = PMA_Response
::getInstance();
286 $response->isSuccess($retval == true);
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(
296 '\'' . PMA_Util
::sqlAddSlashes($table) . '\'',
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;
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
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',
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']
342 __('"DROP DATABASE" statements are disabled.'),
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']);
374 if (isset($store_bkm)) {
375 $result = PMA_Bookmark_save(
377 (isset($bkm_all_users) && $bkm_all_users == 'true' ?
true : false)
379 $response = PMA_Response
::getInstance();
380 if ($response->isAjax()) {
382 $msg = PMA_message
::success(__('Bookmark %s created'));
383 $msg->addParam($fields['label']);
384 $response->addJSON('message', $msg);
386 $msg = PMA_message
::error(__('Bookmark not created'));
387 $response->isSuccess(false);
388 $response->addJSON('message', $msg);
392 // go back to sql.php to redisplay query; do not use & in this case:
393 PMA_sendHeaderLocation(
394 $cfg['PmaAbsoluteUri'] . $goto . '&label=' . $fields['label']
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;
410 . PMA_generate_common_url($db, $table)
411 . '&sql_query=' . urlencode($sql_query);
415 * Go back to further page if table should not be dropped
417 if (isset($_REQUEST['btnDrop']) && $_REQUEST['btnDrop'] == __('No')) {
418 if (! empty($back)) {
422 if (strpos($goto, 'db_') === 0 && strlen($table)) {
425 $active_page = $goto;
426 include '' . PMA_securePath($goto);
428 PMA_sendHeaderLocation(
429 $cfg['PmaAbsoluteUri'] . str_replace('&', '&', $goto)
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'])
455 $do_confirm = isset($analyzed_sql[0]['queryflags']['need_confirm']);
459 $stripped_sql_query = $sql_query;
460 $input = '<input type="hidden" name="%s" value="%s" />';
462 if ($is_drop_database) {
463 $output .= '<h1 class="error">';
464 $output .= __('You are about to DESTROY a complete database!');
467 $form = '<form class="disableAjax" action="sql.php" method="post">';
468 $form .= PMA_generate_common_hidden_inputs($db, $table);
471 $input, 'sql_query', htmlspecialchars($sql_query)
474 $input, 'message_to_show',
475 (isset($message_to_show) ?
PMA_sanitize($message_to_show, true) : '')
478 $input, 'goto', $goto
482 (isset($back) ?
PMA_sanitize($back, true) : '')
486 (isset($reload) ?
PMA_sanitize($reload, true) : '')
490 (isset($purge) ?
PMA_sanitize($purge, true) : '')
493 $input, 'dropped_column',
494 (isset($dropped_column) ?
PMA_sanitize($dropped_column, true) : '')
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">'
504 . __('Do you really want to execute the following query?')
506 .'<code>' . htmlspecialchars($stripped_sql_query) . '</code>'
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>';
521 PMA_Response
::getInstance()->addHTML($output);
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
534 && preg_match('/^(CREATE|ALTER|DROP)\s+(VIEW|TABLE|DATABASE|SCHEMA)\s+/i', $sql_query)
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(
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'];
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'])) {
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.
629 PMA_DBI_store_result();
630 if (! PMA_DBI_more_results()) {
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();
654 if (strpos($goto, 'db_') === 0 && strlen($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);
670 include '' . PMA_securePath($goto);
672 $full_err_url = $err_url;
673 if (preg_match('@^(db|tbl)_@', $err_url)) {
674 $full_err_url .= '&show_query=1&sql_query='
675 . urlencode($sql_query);
677 PMA_Util
::mysqlDie($error, $full_sql_query, '', $full_err_url);
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';
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) {
739 // tmpfile remove after convert encoding appended by Y.Kawada
740 if (function_exists('PMA_kanji_file_conv')
741 && (isset($textfile) && file_exists($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
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(
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:
792 $count_query = PMA_SQP_formatHtml(
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(
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()) {
825 // (SELECT `User`, `Host`, `Db`, `Select_priv` FROM `db`)
826 // UNION (SELECT `User`, `Host`, "%" AS "Db",
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(*)
837 $unlim_num_rows = PMA_DBI_fetch_value('SELECT FOUND_ROWS()');
838 } // end else "just browsing"
840 } else { // not $is_select
842 } // end rows total count
844 // if a table or database gets dropped, check column comments.
845 if (isset($purge) && $purge == '1') {
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);
856 // VOID. No DB/Table gets deleted.
857 } // end if relation-stuff
860 // If a column gets dropped, do relation magic.
861 if (isset($dropped_column)
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);
898 $message = PMA_Message
::getMessageForDeletedRows($num_rows);
899 } elseif ($is_insert) {
901 // For replace we get DELETED + INSERTED row count,
902 // so we have to call it affected
903 $message = PMA_Message
::getMessageForAffectedRows($num_rows);
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
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'));
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);
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') {
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)) {
985 $goto = 'db_sql.php';
987 if (strpos($goto, 'db_') === 0 && ! $is_db) {
993 // Loads to target script
994 if (strlen($goto) > 0) {
995 $active_page = $goto;
998 // Echo at least one character to prevent showing last page from history
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('&', '&', $goto)
1009 . '&message=' . urlencode($message)
1013 // end no rows returned
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]);
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
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
1085 // Displays the headers
1086 if (isset($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();
1097 if ($cfg['Server']['verbose']) {
1098 $hostname = $cfg['Server']['verbose'];
1100 $hostname = $cfg['Server']['host'];
1101 if (! empty($cfg['Server']['port'])) {
1102 $hostname .= $cfg['Server']['port'];
1106 $versions = "phpMyAdmin " . PMA_VERSION
;
1107 $versions .= " / ";
1108 $versions .= "MySQL " . PMA_MYSQL_STR_VERSION
;
1110 echo "<h1>" . __('SQL result') . "</h1>";
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)) {
1122 echo "<strong>" . __('Rows') . ":</strong> $num_rows";
1126 $response = PMA_Response
::getInstance();
1127 $header = $response->getHeader();
1128 $scripts = $header->getScripts();
1129 $scripts->addFile('makegrid.js');
1130 $scripts->addFile('sql.js');
1134 if (! $GLOBALS['is_ajax_request']) {
1135 if (strlen($table)) {
1136 include 'libraries/tbl_common.inc.php';
1137 $url_query .= '&goto=tbl_sql.php&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';
1143 include 'libraries/server_common.inc.php';
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;
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"';
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))
1179 echo 'AJAX.registerOnload(\'sql.js\',makeProfilingChart);';
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'
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))
1201 if (isset($chart_json[ucwords($one_result['Status'])])) {
1202 $chart_json[ucwords($one_result['Status'])]
1203 +
= $one_result['Duration'];
1205 $chart_json[ucwords($one_result['Status'])]
1206 = $one_result['Duration'];
1210 echo '</table>' . "\n";
1212 //require_once 'libraries/chart.lib.php';
1213 echo '<div id="profilingChartData" style="display:none;">';
1214 echo json_encode($chart_json);
1216 echo '<div id="profilingchart" style="display:none;">';
1218 echo '<script type="text/javascript">';
1219 echo 'if($.jqplot !== undefined && $.jqplot.PieRenderer !== undefined) {';
1220 echo 'makeProfilingChart();';
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 // (unless this is an updatable view)
1242 = trim($analyzed_sql[0]['select_expr_clause']) == '*'
1243 && PMA_Table
::isUpdatableView($db, $table);
1244 $editable = $resultSetContainsUniqueKey ||
$updatableView;
1245 if (!empty($table) && (PMA_is_system_schema($db) ||
!$editable)) {
1246 $disp_mode = 'nnnn110111';
1247 $msg = PMA_message
::notice(
1249 'This table does not contain a unique column.'
1250 . ' Grid edit, checkbox, Edit, Copy and Delete features'
1251 . ' are not available.'
1257 if (isset($label)) {
1258 $msg = PMA_message
::success(__('Bookmark %s created'));
1259 $msg->addParam($label);
1263 // Should be initialized these parameters before parsing
1264 $showtable = isset($showtable) ?
$showtable : null;
1265 $printview = isset($printview) ?
$printview : null;
1266 $url_query = isset($url_query) ?
$url_query : null;
1268 if (! empty($sql_data) && ($sql_data['valid_queries'] > 1) ||
$is_procedure) {
1270 $_SESSION['is_multi_query'] = true;
1271 echo getTableHtmlForMultipleQueries(
1272 $displayResultsObject, $db, $sql_data, $goto,
1273 $pmaThemeImage, $text_dir, $printview, $url_query,
1274 $disp_mode, $sql_limit_to_append, $editable
1277 $_SESSION['is_multi_query'] = false;
1278 $displayResultsObject->setProperties(
1279 $unlim_num_rows, $fields_meta, $is_count, $is_export, $is_func,
1280 $is_analyse, $num_rows, $fields_cnt, $querytime, $pmaThemeImage,
1281 $text_dir, $is_maint, $is_explain, $is_show, $showtable,
1282 $printview, $url_query, $editable
1285 echo $displayResultsObject->getTable($result, $disp_mode, $analyzed_sql);
1286 PMA_DBI_free_result($result);
1289 // BEGIN INDEX CHECK See if indexes should be checked.
1290 if (isset($query_type)
1291 && $query_type == 'check_tbl'
1293 && is_array($selected)
1295 foreach ($selected as $idx => $tbl_name) {
1296 $check = PMA_Index
::findDuplicates($tbl_name, $db);
1297 if (! empty($check)) {
1298 printf(__('Problems with indexes of table `%s`'), $tbl_name);
1302 } // End INDEX CHECK
1304 // Bookmark support if required
1305 if ($disp_mode[7] == '1'
1306 && (! empty($cfg['Bookmark']) && empty($id_bookmark))
1307 && ! empty($sql_query)
1311 . PMA_generate_common_url($db, $table)
1312 . '&sql_query=' . urlencode($sql_query)
1313 . '&id_bookmark=1';
1315 echo '<form action="sql.php" method="post"'
1316 . ' onsubmit="return ! emptyFormElements(this, \'fields[label]\');"'
1317 . ' id="bookmarkQueryForm">';
1318 echo PMA_generate_common_hidden_inputs();
1319 echo '<input type="hidden" name="goto" value="' . $goto . '" />';
1320 echo '<input type="hidden" name="fields[dbase]"'
1321 . ' value="' . htmlspecialchars($db) . '" />';
1322 echo '<input type="hidden" name="fields[user]"'
1323 . ' value="' . $cfg['Bookmark']['user'] . '" />';
1324 echo '<input type="hidden" name="fields[query]"' . ' value="'
1325 . urlencode(isset($complete_query) ?
$complete_query : $sql_query)
1329 echo PMA_Util
::getIcon(
1330 'b_bookmark.png', __('Bookmark this SQL query'), true
1333 echo '<div class="formelement">';
1334 echo '<label for="fields_label_">' . __('Label') . ':</label>';
1335 echo '<input type="text" id="fields_label_"'
1336 . ' name="fields[label]" value="" />';
1338 echo '<div class="formelement">';
1339 echo '<input type="checkbox" name="bkm_all_users"'
1340 . ' id="bkm_all_users" value="true" />';
1341 echo '<label for="bkm_all_users">'
1342 . __('Let every user access this bookmark')
1345 echo '<div class="clearfloat"></div>';
1347 echo '<fieldset class="tblFooters">';
1348 echo '<input type="hidden" name="store_bkm" value="1" />';
1349 echo '<input type="submit"'
1350 . ' value="' . __('Bookmark this SQL query') . '" />';
1353 } // end bookmark support
1355 // Do print the page if required
1356 if (isset($printview) && $printview == '1') {
1357 echo PMA_Util
::getButton();
1359 echo '</div>'; // end sqlqueryresults div
1360 } // end rows returned
1362 $_SESSION['is_multi_query'] = false;
1365 * Displays the footer
1367 if (! isset($_REQUEST['table_maintenance'])) {
1372 // These functions will need for use set the required parameters for display results
1375 * Initialize some parameters needed to display results
1377 * @param string $sql_query SQL statement
1378 * @param boolean $is_select select query or not
1380 * @return array set of parameters
1384 function PMA_getDisplayPropertyParams($sql_query, $is_select)
1386 $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 $is_group = preg_match('@(GROUP[[:space:]]+BY|HAVING|SELECT[[:space:]]+DISTINCT)[[:space:]]+@i', $sql_query);
1390 $is_func = ! $is_group && (preg_match('@[[:space:]]+(SUM|AVG|STD|STDDEV|MIN|MAX|BIT_OR|BIT_AND)\s*\(@i', $sql_query));
1391 $is_count = ! $is_group && (preg_match('@^SELECT[[:space:]]+COUNT\((.*\.+)?.*\)@i', $sql_query));
1392 $is_export = preg_match('@[[:space:]]+INTO[[:space:]]+OUTFILE[[:space:]]+@i', $sql_query);
1393 $is_analyse = preg_match('@[[:space:]]+PROCEDURE[[:space:]]+ANALYSE@i', $sql_query);
1394 } elseif (preg_match('@^EXPLAIN[[:space:]]+@i', $sql_query)) {
1396 } elseif (preg_match('@^DELETE[[:space:]]+@i', $sql_query)) {
1398 $is_affected = true;
1399 } elseif (preg_match('@^(INSERT|LOAD[[:space:]]+DATA|REPLACE)[[:space:]]+@i', $sql_query)) {
1401 $is_affected = true;
1402 if (preg_match('@^(REPLACE)[[:space:]]+@i', $sql_query)) {
1405 } elseif (preg_match('@^UPDATE[[:space:]]+@i', $sql_query)) {
1406 $is_affected = true;
1407 } elseif (preg_match('@^[[:space:]]*SHOW[[:space:]]+@i', $sql_query)) {
1409 } elseif (preg_match('@^(CHECK|ANALYZE|REPAIR|OPTIMIZE)[[:space:]]+TABLE[[:space:]]+@i', $sql_query)) {
1414 $is_group, $is_func, $is_count, $is_export, $is_analyse, $is_explain,
1415 $is_delete, $is_affected, $is_insert, $is_replace,$is_show, $is_maint
1420 * Get the database name inside a USE query
1422 * @param string $sql SQL query
1423 * @param array $databases array with all databases
1425 * @return strin $db new database name
1427 function PMA_getNewDatabase($sql, $databases)
1430 // loop through all the databases
1431 foreach ($databases as $database) {
1432 if (strpos($sql, $database['SCHEMA_NAME']) !== false) {
1441 * Get the table name in a sql query
1442 * If there are several tables in the SQL query,
1443 * first table wil lreturn
1445 * @param string $sql SQL query
1446 * @param array $tables array of names in current database
1448 * @return string $table table name
1450 function PMA_getTableNameBySQL($sql, $tables)
1454 // loop through all the tables in the database
1455 foreach ($tables as $tbl) {
1456 if (strpos($sql, $tbl)) {
1457 $table .= ' ' . $tbl;
1461 if (count(explode(' ', trim($table))) > 1) {
1462 $tmp_array = explode(' ', trim($table));
1463 return $tmp_array[0];
1466 return trim($table);
1471 * Generate table html when SQL statement have multiple queries
1472 * which return displayable results
1474 * @param PMA_DisplayResults $displayResultsObject object
1475 * @param string $db database name
1476 * @param array $sql_data information about SQL statement
1477 * @param string $goto URL to go back in case of errors
1478 * @param string $pmaThemeImage path for theme images directory
1479 * @param string $text_dir text direction
1480 * @param string $printview whether printview is enabled
1481 * @param string $url_query URL query
1482 * @param array $disp_mode the display mode
1483 * @param string $sql_limit_to_append limit clause
1484 * @param bool $editable whether result set is editable
1486 * @return string $table_html html content
1488 function getTableHtmlForMultipleQueries(
1489 $displayResultsObject, $db, $sql_data, $goto, $pmaThemeImage,
1490 $text_dir, $printview, $url_query, $disp_mode, $sql_limit_to_append,
1495 $tables_array = PMA_DBI_get_tables($db);
1496 $databases_array = PMA_DBI_get_databases_full();
1497 $multi_sql = implode(";", $sql_data['valid_sql']);
1498 $querytime_before = array_sum(explode(' ', microtime()));
1500 // Assignment for variable is not needed since the results are
1501 // looiping using the connection
1502 @PMA_DBI_try_multi_query
($multi_sql);
1504 $querytime_after = array_sum(explode(' ', microtime()));
1505 $querytime = $querytime_after - $querytime_before;
1509 $analyzed_sql = array();
1510 $is_affected = false;
1512 $result = PMA_DBI_store_result();
1513 $fields_meta = ($result !== false)
1514 ?
PMA_DBI_get_fields_meta($result)
1516 $fields_cnt = count($fields_meta);
1518 // Initialize needed params related to each query in multiquery statement
1519 if (isset($sql_data['valid_sql'][$sql_no])) {
1520 // 'Use' query can change the database
1521 if (stripos($sql_data['valid_sql'][$sql_no], "use ")) {
1522 $db = PMA_getNewDatabase(
1523 $sql_data['valid_sql'][$sql_no],
1527 $parsed_sql = PMA_SQP_parse($sql_data['valid_sql'][$sql_no]);
1528 $table = PMA_getTableNameBySQL(
1529 $sql_data['valid_sql'][$sql_no],
1533 $analyzed_sql = PMA_SQP_analyze($parsed_sql);
1534 $is_select = isset($analyzed_sql[0]['queryflags']['select_from']);
1535 $unlim_num_rows = PMA_Table
::countRecords($db, $table, true);
1536 $showtable = PMA_Table
::sGetStatusInfo($db, $table, null, true);
1537 $url_query = PMA_generate_common_url($db, $table);
1539 list($is_group, $is_func, $is_count, $is_export, $is_analyse,
1540 $is_explain, $is_delete, $is_affected, $is_insert, $is_replace,
1541 $is_show, $is_maint)
1542 = PMA_getDisplayPropertyParams(
1543 $sql_data['valid_sql'][$sql_no], $is_select
1546 // Handle remembered sorting order, only for single table query
1547 if ($GLOBALS['cfg']['RememberSorting']
1548 && ! ($is_count ||
$is_export ||
$is_func ||
$is_analyse)
1549 && isset($analyzed_sql[0]['select_expr'])
1550 && (count($analyzed_sql[0]['select_expr']) == 0)
1551 && isset($analyzed_sql[0]['queryflags']['select_from'])
1552 && count($analyzed_sql[0]['table_ref']) == 1
1554 PMA_handleSortOrder(
1558 $sql_data['valid_sql'][$sql_no]
1562 // Do append a "LIMIT" clause?
1563 if (($_SESSION['tmp_user_values']['max_rows'] != 'all')
1564 && ! ($is_count ||
$is_export ||
$is_func ||
$is_analyse)
1565 && isset($analyzed_sql[0]['queryflags']['select_from'])
1566 && ! isset($analyzed_sql[0]['queryflags']['offset'])
1567 && empty($analyzed_sql[0]['limit_clause'])
1569 $sql_limit_to_append = ' LIMIT '
1570 . $_SESSION['tmp_user_values']['pos']
1571 . ', ' . $_SESSION['tmp_user_values']['max_rows'] . " ";
1572 $sql_data['valid_sql'][$sql_no] = PMA_getSqlWithLimitClause(
1573 $sql_data['valid_sql'][$sql_no],
1575 $sql_limit_to_append
1579 // Set the needed properties related to executing sql query
1580 $displayResultsObject->__set('db', $db);
1581 $displayResultsObject->__set('table', $table);
1582 $displayResultsObject->__set('goto', $goto);
1585 if (! $is_affected) {
1586 $num_rows = ($result) ? @PMA_DBI_num_rows
($result) : 0;
1587 } elseif (! isset($num_rows)) {
1588 $num_rows = @PMA_DBI_affected_rows
();
1591 if (isset($sql_data['valid_sql'][$sql_no])) {
1593 $displayResultsObject->__set(
1595 $sql_data['valid_sql'][$sql_no]
1597 $displayResultsObject->setProperties(
1598 $unlim_num_rows, $fields_meta, $is_count, $is_export, $is_func,
1599 $is_analyse, $num_rows, $fields_cnt, $querytime, $pmaThemeImage,
1600 $text_dir, $is_maint, $is_explain, $is_show, $showtable,
1601 $printview, $url_query, $editable
1605 if ($num_rows == 0) {
1609 // With multiple results, operations are limied
1610 $disp_mode = 'nnnn000000';
1611 $is_limited_display = true;
1613 // Collect the tables
1614 $table_html .= $displayResultsObject->getTable(
1615 $result, $disp_mode, $analyzed_sql, $is_limited_display
1618 // Free the result to save the memory
1619 PMA_DBI_free_result($result);
1623 } while (PMA_DBI_more_results() && PMA_DBI_next_result());
1629 * Handle remembered sorting order, only for single table query
1631 * @param string $db database name
1632 * @param string $table table name
1633 * @param array &$analyzed_sql the analyzed query
1634 * @param string &$full_sql_query SQL query
1638 function PMA_handleSortOrder($db, $table, &$analyzed_sql, &$full_sql_query)
1640 $pmatable = new PMA_Table($table, $db);
1641 if (empty($analyzed_sql[0]['order_by_clause'])) {
1642 $sorted_col = $pmatable->getUiProp(PMA_Table
::PROP_SORTED_COLUMN
);
1644 // retrieve the remembered sorting order for current table
1645 $sql_order_to_append = ' ORDER BY ' . $sorted_col . ' ';
1646 $full_sql_query = $analyzed_sql[0]['section_before_limit']
1647 . $sql_order_to_append . $analyzed_sql[0]['limit_clause']
1648 . ' ' . $analyzed_sql[0]['section_after_limit'];
1650 // update the $analyzed_sql
1651 $analyzed_sql[0]['section_before_limit'] .= $sql_order_to_append;
1652 $analyzed_sql[0]['order_by_clause'] = $sorted_col;
1655 // store the remembered table into session
1656 $pmatable->setUiProp(
1657 PMA_Table
::PROP_SORTED_COLUMN
,
1658 $analyzed_sql[0]['order_by_clause']
1664 * Append limit clause to SQL query
1666 * @param string $full_sql_query SQL query
1667 * @param array $analyzed_sql the analyzed query
1668 * @param string $sql_limit_to_append clause to append
1670 * @return string limit clause appended SQL query
1672 function PMA_getSqlWithLimitClause($full_sql_query, $analyzed_sql,
1673 $sql_limit_to_append
1675 return $analyzed_sql[0]['section_before_limit'] . "\n"
1676 . $sql_limit_to_append . $analyzed_sql[0]['section_after_limit'];
1681 * Get column name from a drop SQL statement
1683 * @param string $sql SQL query
1685 * @return string $drop_column Name of the column
1687 function PMA_getColumnNameInColumnDropSql($sql)
1689 $tmpArray1 = explode('DROP', $sql);
1690 $str_to_check = trim($tmpArray1[1]);
1692 if (stripos($str_to_check, 'COLUMN') !== false) {
1693 $tmpArray2 = explode('COLUMN', $str_to_check);
1694 $str_to_check = trim($tmpArray2[1]);
1697 $tmpArray3 = explode(' ', $str_to_check);
1698 $str_to_check = trim($tmpArray3[0]);
1700 $drop_column = str_replace(';', '', trim($str_to_check));
1701 $drop_column = str_replace('`', '', $drop_column);
1703 return $drop_column;
1707 * Verify whether the result set contains all the columns
1708 * of at least one unique key
1710 * @param string $db database name
1711 * @param string $table table name
1712 * @param string $fields_meta meta fields
1714 * @return boolean whether the result set contains a unique key
1716 function PMA_resultSetContainsUniqueKey($db, $table, $fields_meta)
1718 $resultSetColumnNames = array();
1719 foreach ($fields_meta as $oneMeta) {
1720 $resultSetColumnNames[] = $oneMeta->name
;
1722 foreach (PMA_Index
::getFromTable($table, $db) as $index) {
1723 if ($index->isUnique()) {
1724 $indexColumns = $index->getColumns();
1726 foreach ($indexColumns as $indexColumnName => $dummy) {
1727 if (in_array($indexColumnName, $resultSetColumnNames)) {
1731 if ($numberFound == count($indexColumns)) {