2 /* vim: set expandtab sw=4 ts=4 sts=4: */
4 * @todo we must handle the case if sql.php is called directly with a query
5 * that returns 0 rows - to prevent cyclic redirects or includes
10 * Gets some core libraries
12 require_once 'libraries/common.inc.php';
13 require_once 'libraries/Table.class.php';
14 require_once 'libraries/check_user_privileges.lib.php';
15 require_once 'libraries/bookmark.lib.php';
17 $GLOBALS['js_include'][] = 'jquery/timepicker.js';
18 $GLOBALS['js_include'][] = 'tbl_change.js';
19 // the next one needed because sql.php may do a "goto" to tbl_structure.php
20 $GLOBALS['js_include'][] = 'tbl_structure.js';
21 $GLOBALS['js_include'][] = 'gis_data_editor.js';
23 if ($GLOBALS['cfg']['CodemirrorEnable']) {
24 $GLOBALS['js_include'][] = 'codemirror/lib/codemirror.js';
25 $GLOBALS['js_include'][] = 'codemirror/mode/mysql/mysql.js';
30 * Sets globals from $_POST
37 foreach ($post_params as $one_post_param) {
38 if (isset($_POST[$one_post_param])) {
39 $GLOBALS[$one_post_param] = $_POST[$one_post_param];
44 * Sets globals from $_GET
51 foreach ($get_params as $one_get_param) {
52 if (isset($_GET[$one_get_param])) {
53 $GLOBALS[$one_get_param] = $_GET[$one_get_param];
58 if (isset($_REQUEST['printview'])) {
59 $GLOBALS['printview'] = $_REQUEST['printview'];
62 if (isset($_SESSION['profiling'])) {
63 $GLOBALS['js_include'][] = 'highcharts/highcharts.js';
64 /* Files required for chart exporting */
65 $GLOBALS['js_include'][] = 'highcharts/exporting.js';
66 /* < IE 9 doesn't support canvas natively */
67 if (PMA_USR_BROWSER_AGENT
== 'IE' && PMA_USR_BROWSER_VER
< 9) {
68 $GLOBALS['js_include'][] = 'canvg/flashcanvas.js';
70 $GLOBALS['js_include'][] = 'canvg/canvg.js';
74 * Defines the url to return to in case of error in a sql statement
78 $is_gotofile = preg_replace('@^([^?]+).*$@s', '\\1', $goto);
79 if (! @file_exists
('' . $is_gotofile)) {
82 $is_gotofile = ($is_gotofile == $goto);
85 $goto = (! strlen($table)) ?
$cfg['DefaultTabDatabase'] : $cfg['DefaultTabTable'];
89 if (! isset($err_url)) {
90 $err_url = (! empty($back) ?
$back : $goto)
91 . '?' . PMA_generate_common_url($db)
92 . ((strpos(' ' . $goto, 'db_') != 1 && strlen($table)) ?
'&table=' . urlencode($table) : '');
95 // Coming from a bookmark dialog
96 if (isset($fields['query'])) {
97 $sql_query = $fields['query'];
100 // This one is just to fill $db
101 if (isset($fields['dbase'])) {
102 $db = $fields['dbase'];
106 * During grid edit, if we have a relational field, show the dropdown for it
108 * Logic taken from libraries/display_tbl_lib.php
110 * This doesn't seem to be the right place to do this, but I can't think of any
111 * better place either.
113 if (isset($_REQUEST['get_relational_values']) && $_REQUEST['get_relational_values'] == true) {
114 include_once 'libraries/relation.lib.php';
116 $column = $_REQUEST['column'];
117 $foreigners = PMA_getForeigners($db, $table, $column);
119 $display_field = PMA_getDisplayField($foreigners[$column]['foreign_db'], $foreigners[$column]['foreign_table']);
121 $foreignData = PMA_getForeignData($foreigners, $column, false, '', '');
123 if ($_SESSION['tmp_user_values']['relational_display'] == 'D'
124 && isset($display_field)
125 && strlen($display_field)
126 && isset($_REQUEST['relation_key_or_display_column'])
127 && $_REQUEST['relation_key_or_display_column']
129 $curr_value = $_REQUEST['relation_key_or_display_column'];
131 $curr_value = $_REQUEST['curr_value'];
133 if ($foreignData['disp_row'] == null) {
134 //Handle the case when number of values is more than $cfg['ForeignKeyMaxLimit']
135 $_url_params = array(
141 $dropdown = '<span class="curr_value">' . htmlspecialchars($_REQUEST['curr_value']) . '</span> <a href="browse_foreigners.php' . PMA_generate_common_url($_url_params) . '"'
142 . ' target="_blank" class="browse_foreign" '
143 .'>' . __('Browse foreign values') . '</a>';
145 $dropdown = PMA_foreignDropdown($foreignData['disp_row'], $foreignData['foreign_field'], $foreignData['foreign_display'], $curr_value, $cfg['ForeignKeyMaxLimit']);
146 $dropdown = '<select>' . $dropdown . '</select>';
149 $extra_data['dropdown'] = $dropdown;
150 PMA_ajaxResponse(null, true, $extra_data);
154 * Just like above, find possible values for enum fields during grid edit.
156 * Logic taken from libraries/display_tbl_lib.php
158 if (isset($_REQUEST['get_enum_values']) && $_REQUEST['get_enum_values'] == true) {
159 $field_info_query = PMA_DBI_get_columns_sql($db, $table, $_REQUEST['column']);
161 $field_info_result = PMA_DBI_fetch_result($field_info_query, null, null, null, PMA_DBI_QUERY_STORE
);
163 $search = array('enum', '(', ')', "'");
165 $values = explode(',', str_replace($search, '', $field_info_result[0]['Type']));
167 $dropdown = '<option value=""> </option>';
168 foreach ($values as $value) {
169 $dropdown .= '<option value="' . htmlspecialchars($value) . '"';
170 if ($value == $_REQUEST['curr_value']) {
171 $dropdown .= ' selected="selected"';
173 $dropdown .= '>' . $value . '</option>';
176 $dropdown = '<select>' . $dropdown . '</select>';
178 $extra_data['dropdown'] = $dropdown;
179 PMA_ajaxResponse(null, true, $extra_data);
183 * Find possible values for set fields during grid edit.
185 if (isset($_REQUEST['get_set_values']) && $_REQUEST['get_set_values'] == true) {
186 $field_info_query = PMA_DBI_get_columns_sql($db, $table, $_REQUEST['column']);
188 $field_info_result = PMA_DBI_fetch_result($field_info_query, null, null, null, PMA_DBI_QUERY_STORE
);
190 $selected_values = explode(',', $_REQUEST['curr_value']);
192 $search = array('set', '(', ')', "'");
193 $values = explode(',', str_replace($search, '', $field_info_result[0]['Type']));
196 foreach ($values as $value) {
197 $select .= '<option value="' . htmlspecialchars($value) . '"';
198 if (in_array($value, $selected_values, true)) {
199 $select .= ' selected="selected"';
201 $select .= '>' . $value . '</option>';
204 $select_size = (sizeof($values) > 10) ?
10 : sizeof($values);
205 $select = '<select multiple="multiple" size="' . $select_size . '">' . $select . '</select>';
207 $extra_data['select'] = $select;
208 PMA_ajaxResponse(null, true, $extra_data);
212 * Check ajax request to set the column order
214 if (isset($_REQUEST['set_col_prefs']) && $_REQUEST['set_col_prefs'] == true) {
215 $pmatable = new PMA_Table($table, $db);
219 if (isset($_REQUEST['col_order'])) {
220 $col_order = explode(',', $_REQUEST['col_order']);
221 $retval = $pmatable->setUiProp(PMA_Table
::PROP_COLUMN_ORDER
, $col_order, $_REQUEST['table_create_time']);
222 if (gettype($retval) != 'boolean') {
223 PMA_ajaxResponse($retval->getString(), false);
227 // set column visibility
228 if ($retval === true && isset($_REQUEST['col_visib'])) {
229 $col_visib = explode(',', $_REQUEST['col_visib']);
230 $retval = $pmatable->setUiProp(PMA_Table
::PROP_COLUMN_VISIB
, $col_visib, $_REQUEST['table_create_time']);
231 if (gettype($retval) != 'boolean') {
232 PMA_ajaxResponse($retval->getString(), false);
236 PMA_ajaxResponse(null, ($retval == true));
239 // Default to browse if no query set and we have table
240 // (needed for browsing from DefaultTabTable)
241 if (empty($sql_query) && strlen($table) && strlen($db)) {
242 include_once 'libraries/bookmark.lib.php';
243 $book_sql_query = PMA_Bookmark_get(
245 '\'' . PMA_sqlAddSlashes($table) . '\'',
251 if (! empty($book_sql_query)) {
252 $GLOBALS['using_bookmark_message'] = PMA_message
::notice(__('Using bookmark "%s" as default browse query.'));
253 $GLOBALS['using_bookmark_message']->addParam($table);
254 $GLOBALS['using_bookmark_message']->addMessage(PMA_showDocu('faq6_22'));
255 $sql_query = $book_sql_query;
257 $sql_query = 'SELECT * FROM ' . PMA_backquote($table);
259 unset($book_sql_query);
261 // set $goto to what will be displayed if query returns 0 rows
262 $goto = 'tbl_structure.php';
264 // Now we can check the parameters
265 PMA_checkParameters(array('sql_query'));
268 // instead of doing the test twice
269 $is_drop_database = preg_match(
270 '/DROP[[:space:]]+(DATABASE|SCHEMA)[[:space:]]+/i',
275 * Check rights in case of DROP DATABASE
277 * This test may be bypassed if $is_js_confirmed = 1 (already checked with js)
278 * but since a malicious user may pass this variable by url/form, we don't take
279 * into account this case.
281 if (! defined('PMA_CHK_DROP')
282 && ! $cfg['AllowUserDropDatabase']
286 include_once 'libraries/header.inc.php';
287 PMA_mysqlDie(__('"DROP DATABASE" statements are disabled.'), '', '', $err_url);
290 require_once 'libraries/display_tbl.lib.php';
291 PMA_displayTable_checkConfigParams();
294 * Need to find the real end of rows?
296 if (isset($find_real_end) && $find_real_end) {
297 $unlim_num_rows = PMA_Table
::countRecords($db, $table, $force_exact = true);
298 $_SESSION['tmp_user_values']['pos'] = @((ceil($unlim_num_rows / $_SESSION['tmp_user_values']['max_rows']) - 1) * $_SESSION['tmp_user_values']['max_rows']);
305 if (isset($store_bkm)) {
306 PMA_Bookmark_save($fields, (isset($bkm_all_users) && $bkm_all_users == 'true' ?
true : false));
307 // go back to sql.php to redisplay query; do not use & in this case:
308 PMA_sendHeaderLocation($cfg['PmaAbsoluteUri'] . $goto . '&label=' . $fields['label']);
312 * Parse and analyze the query
314 require_once 'libraries/parse_analyze.lib.php';
317 * Sets or modifies the $goto variable if required
319 if ($goto == 'sql.php') {
320 $is_gotofile = false;
322 . PMA_generate_common_url($db, $table)
323 . '&sql_query=' . urlencode($sql_query);
328 * Go back to further page if table should not be dropped
330 if (isset($btnDrop) && $btnDrop == __('No')) {
331 if (! empty($back)) {
335 if (strpos($goto, 'db_') === 0 && strlen($table)) {
338 $active_page = $goto;
339 include '' . PMA_securePath($goto);
341 PMA_sendHeaderLocation($cfg['PmaAbsoluteUri'] . str_replace('&', '&', $goto));
348 * Displays the confirm page if required
350 * This part of the script is bypassed if $is_js_confirmed = 1 (already checked
351 * with js) because possible security issue is not so important here: at most,
352 * the confirm message isn't displayed.
354 * Also bypassed if only showing php code.or validating a SQL query
356 if (! $cfg['Confirm']
357 ||
isset($_REQUEST['is_js_confirmed'])
359 // if we are coming from a "Create PHP code" or a "Without PHP Code"
360 // dialog, we won't execute the query anyway, so don't confirm
361 ||
isset($GLOBALS['show_as_php'])
362 ||
! empty($GLOBALS['validatequery'])
366 $do_confirm = isset($analyzed_sql[0]['queryflags']['need_confirm']);
370 $stripped_sql_query = $sql_query;
371 include_once 'libraries/header.inc.php';
372 if ($is_drop_database) {
373 echo '<h1 class="error">' . __('You are about to DESTROY a complete database!') . '</h1>';
375 echo '<form action="sql.php" method="post">' . "\n"
376 .PMA_generate_common_hidden_inputs($db, $table);
378 <input type
="hidden" name
="sql_query" value
="<?php echo htmlspecialchars($sql_query); ?>" />
379 <input type
="hidden" name
="message_to_show" value
="<?php echo isset($message_to_show) ? PMA_sanitize($message_to_show, true) : ''; ?>" />
380 <input type
="hidden" name
="goto" value
="<?php echo $goto; ?>" />
381 <input type
="hidden" name
="back" value
="<?php echo isset($back) ? PMA_sanitize($back, true) : ''; ?>" />
382 <input type
="hidden" name
="reload" value
="<?php echo isset($reload) ? PMA_sanitize($reload, true) : 0; ?>" />
383 <input type
="hidden" name
="purge" value
="<?php echo isset($purge) ? PMA_sanitize($purge, true) : ''; ?>" />
384 <input type
="hidden" name
="dropped_column" value
="<?php echo isset($dropped_column) ? PMA_sanitize($dropped_column, true) : ''; ?>" />
385 <input type
="hidden" name
="show_query" value
="<?php echo isset($show_query) ? PMA_sanitize($show_query, true) : ''; ?>" />
387 echo '<fieldset class="confirmation">' . "\n"
388 .' <legend>' . __('Do you really want to execute following query?') . '</legend>'
389 .' <code>' . htmlspecialchars($stripped_sql_query) . '</code>' . "\n"
390 .'</fieldset>' . "\n"
391 .'<fieldset class="tblFooters">' . "\n";
393 <input type
="submit" name
="btnDrop" value
="<?php echo __('Yes'); ?>" id
="buttonYes" />
394 <input type
="submit" name
="btnDrop" value
="<?php echo __('No'); ?>" id
="buttonNo" />
396 echo '</fieldset>' . "\n"
400 * Displays the footer and exit
402 include 'libraries/footer.inc.php';
403 } // end if $do_confirm
406 // Defines some variables
407 // A table has to be created, renamed, dropped -> navi frame should be reloaded
409 * @todo use the parser/analyzer
413 && preg_match('/^(CREATE|ALTER|DROP)\s+(VIEW|TABLE|DATABASE|SCHEMA)\s+/i', $sql_query)
418 // SK -- Patch: $is_group added for use in calculation of total number of
420 // $is_count is changed for more correct "LIMIT" clause
421 // appending in queries like
422 // "SELECT COUNT(...) FROM ... GROUP BY ..."
425 * @todo detect all this with the parser, to avoid problems finding
426 * those strings in comments or backquoted identifiers
429 $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;
430 if ($is_select) { // see line 141
431 $is_group = preg_match('@(GROUP[[:space:]]+BY|HAVING|SELECT[[:space:]]+DISTINCT)[[:space:]]+@i', $sql_query);
432 $is_func = ! $is_group && (preg_match('@[[:space:]]+(SUM|AVG|STD|STDDEV|MIN|MAX|BIT_OR|BIT_AND)\s*\(@i', $sql_query));
433 $is_count = ! $is_group && (preg_match('@^SELECT[[:space:]]+COUNT\((.*\.+)?.*\)@i', $sql_query));
434 $is_export = (preg_match('@[[:space:]]+INTO[[:space:]]+OUTFILE[[:space:]]+@i', $sql_query));
435 $is_analyse = (preg_match('@[[:space:]]+PROCEDURE[[:space:]]+ANALYSE@i', $sql_query));
436 } elseif (preg_match('@^EXPLAIN[[:space:]]+@i', $sql_query)) {
438 } elseif (preg_match('@^DELETE[[:space:]]+@i', $sql_query)) {
441 } elseif (preg_match('@^(INSERT|LOAD[[:space:]]+DATA|REPLACE)[[:space:]]+@i', $sql_query)) {
444 if (preg_match('@^(REPLACE)[[:space:]]+@i', $sql_query)) {
447 } elseif (preg_match('@^UPDATE[[:space:]]+@i', $sql_query)) {
449 } elseif (preg_match('@^[[:space:]]*SHOW[[:space:]]+@i', $sql_query)) {
451 } elseif (preg_match('@^(CHECK|ANALYZE|REPAIR|OPTIMIZE)[[:space:]]+TABLE[[:space:]]+@i', $sql_query)) {
455 // assign default full_sql_query
456 $full_sql_query = $sql_query;
458 // Handle remembered sorting order, only for single table query
459 if ($GLOBALS['cfg']['RememberSorting']
460 && ! ($is_count ||
$is_export ||
$is_func ||
$is_analyse)
461 && count($analyzed_sql[0]['select_expr']) == 0
462 && isset($analyzed_sql[0]['queryflags']['select_from'])
463 && count($analyzed_sql[0]['table_ref']) == 1
465 $pmatable = new PMA_Table($table, $db);
466 if (empty($analyzed_sql[0]['order_by_clause'])) {
467 $sorted_col = $pmatable->getUiProp(PMA_Table
::PROP_SORTED_COLUMN
);
469 // retrieve the remembered sorting order for current table
470 $sql_order_to_append = ' ORDER BY ' . $sorted_col . ' ';
471 $full_sql_query = $analyzed_sql[0]['section_before_limit'] . $sql_order_to_append
472 . $analyzed_sql[0]['limit_clause'] . ' ' . $analyzed_sql[0]['section_after_limit'];
474 // update the $analyzed_sql
475 $analyzed_sql[0]['section_before_limit'] .= $sql_order_to_append;
476 $analyzed_sql[0]['order_by_clause'] = $sorted_col;
479 // store the remembered table into session
480 $pmatable->setUiProp(PMA_Table
::PROP_SORTED_COLUMN
, $analyzed_sql[0]['order_by_clause']);
484 // Do append a "LIMIT" clause?
485 if (($_SESSION['tmp_user_values']['max_rows'] != 'all')
486 && ! ($is_count ||
$is_export ||
$is_func ||
$is_analyse)
487 && isset($analyzed_sql[0]['queryflags']['select_from'])
488 && ! isset($analyzed_sql[0]['queryflags']['offset'])
489 && empty($analyzed_sql[0]['limit_clause'])
491 $sql_limit_to_append = ' LIMIT ' . $_SESSION['tmp_user_values']['pos']
492 . ', ' . $_SESSION['tmp_user_values']['max_rows'] . " ";
494 $full_sql_query = $analyzed_sql[0]['section_before_limit'] . "\n"
495 . $sql_limit_to_append . $analyzed_sql[0]['section_after_limit'];
497 * @todo pretty printing of this modified query
499 if (isset($display_query)) {
500 // if the analysis of the original query revealed that we found
501 // a section_after_limit, we now have to analyze $display_query
502 // to display it correctly
504 if (! empty($analyzed_sql[0]['section_after_limit'])
505 && trim($analyzed_sql[0]['section_after_limit']) != ';'
507 $analyzed_display_query = PMA_SQP_analyze(PMA_SQP_parse($display_query));
508 $display_query = $analyzed_display_query[0]['section_before_limit']
509 . "\n" . $sql_limit_to_append . $analyzed_display_query[0]['section_after_limit'];
516 PMA_DBI_select_db($db);
519 // E x e c u t e t h e q u e r y
521 // Only if we didn't ask to see the php code (mikebeck)
522 if (isset($GLOBALS['show_as_php']) ||
! empty($GLOBALS['validatequery'])) {
527 if (isset($_SESSION['profiling']) && PMA_profilingSupported()) {
528 PMA_DBI_query('SET PROFILING=1;');
531 // Measure query time.
532 $querytime_before = array_sum(explode(' ', microtime()));
534 $result = @PMA_DBI_try_query
($full_sql_query, null, PMA_DBI_QUERY_STORE
);
536 // If a stored procedure was called, there may be more results that are
537 // queued up and waiting to be flushed from the buffer. So let's do that.
539 if (! PMA_DBI_more_results()) {
542 PMA_DBI_next_result();
545 $querytime_after = array_sum(explode(' ', microtime()));
547 $GLOBALS['querytime'] = $querytime_after - $querytime_before;
549 // Displays an error message if required and stop parsing the script
550 $error = PMA_DBI_getError();
553 if (strpos($goto, 'db_') === 0 && strlen($table)) {
556 $active_page = $goto;
557 $message = PMA_Message
::rawError($error);
559 if ($GLOBALS['is_ajax_request'] == true) {
560 PMA_ajaxResponse($message, false);
566 include '' . PMA_securePath($goto);
568 $full_err_url = (preg_match('@^(db|tbl)_@', $err_url))
569 ?
$err_url . '&show_query=1&sql_query=' . urlencode($sql_query)
571 PMA_mysqlDie($error, $full_sql_query, '', $full_err_url);
577 // If there are no errors and bookmarklabel was given,
578 // store the query as a bookmark
579 if (! empty($bkm_label) && ! empty($import_text)) {
580 include_once 'libraries/bookmark.lib.php';
583 'user' => $cfg['Bookmark']['user'],
584 'query' => urlencode($import_text),
585 'label' => $bkm_label
588 // Should we replace bookmark?
589 if (isset($bkm_replace)) {
590 $bookmarks = PMA_Bookmark_getList($db);
591 foreach ($bookmarks as $key => $val) {
592 if ($val == $bkm_label) {
593 PMA_Bookmark_delete($db, $key);
598 PMA_Bookmark_save($bfields, isset($bkm_all_users));
600 $bookmark_created = true;
601 } // end store bookmarks
603 // Gets the number of rows affected/returned
604 // (This must be done immediately after the query because
605 // mysql_affected_rows() reports about the last query done)
607 if (! $is_affected) {
608 $num_rows = ($result) ? @PMA_DBI_num_rows
($result) : 0;
609 } elseif (! isset($num_rows)) {
610 $num_rows = @PMA_DBI_affected_rows
();
613 // Grabs the profiling results
614 if (isset($_SESSION['profiling']) && PMA_profilingSupported()) {
615 $profiling_results = PMA_DBI_fetch_result('SHOW PROFILE;');
618 // Checks if the current database has changed
619 // This could happen if the user sends a query like "USE `database`;"
621 * commented out auto-switching to active database - really required?
622 * bug #1814718 win: table list disappears (mixed case db names)
623 * https://sourceforge.net/support/tracker.php?aid=1814718
624 * @todo RELEASE test and comit or rollback before release
625 $current_db = PMA_DBI_fetch_value('SELECT DATABASE()');
626 if ($db !== $current_db) {
633 // tmpfile remove after convert encoding appended by Y.Kawada
634 if (function_exists('PMA_kanji_file_conv')
635 && (isset($textfile) && file_exists($textfile))
640 // Counts the total number of rows for the same 'SELECT' query without the
641 // 'LIMIT' clause that may have been programatically added
643 if (empty($sql_limit_to_append)) {
644 $unlim_num_rows = $num_rows;
645 // if we did not append a limit, set this to get a correct
646 // "Showing rows..." message
647 //$_SESSION['tmp_user_values']['max_rows'] = 'all';
648 } elseif ($is_select) {
650 // c o u n t q u e r y
652 // If we are "just browsing", there is only one table,
653 // and no WHERE clause (or just 'WHERE 1 '),
654 // we do a quick count (which uses MaxExactCount) because
655 // SQL_CALC_FOUND_ROWS is not quick on large InnoDB tables
657 // However, do not count again if we did it previously
658 // due to $find_real_end == true
661 && ! isset($analyzed_sql[0]['queryflags']['union'])
662 && ! isset($analyzed_sql[0]['queryflags']['distinct'])
663 && ! isset($analyzed_sql[0]['table_ref'][1]['table_name'])
664 && (empty($analyzed_sql[0]['where_clause']) ||
$analyzed_sql[0]['where_clause'] == '1 ')
665 && ! isset($find_real_end)
668 // "j u s t b r o w s i n g"
669 $unlim_num_rows = PMA_Table
::countRecords($db, $table);
671 } else { // n o t " j u s t b r o w s i n g "
673 // add select expression after the SQL_CALC_FOUND_ROWS
675 // for UNION, just adding SQL_CALC_FOUND_ROWS
676 // after the first SELECT works.
678 // take the left part, could be:
681 $count_query = PMA_SQP_formatHtml($parsed_sql, 'query_only', 0, $analyzed_sql[0]['position_of_first_select'] +
1);
682 $count_query .= ' SQL_CALC_FOUND_ROWS ';
683 // add everything that was after the first SELECT
684 $count_query .= PMA_SQP_formatHtml($parsed_sql, 'query_only', $analyzed_sql[0]['position_of_first_select'] +
1);
685 // ensure there is no semicolon at the end of the
686 // count query because we'll probably add
687 // a LIMIT 1 clause after it
688 $count_query = rtrim($count_query);
689 $count_query = rtrim($count_query, ';');
691 // if using SQL_CALC_FOUND_ROWS, add a LIMIT to avoid
692 // long delays. Returned count will be complete anyway.
693 // (but a LIMIT would disrupt results in an UNION)
695 if (! isset($analyzed_sql[0]['queryflags']['union'])) {
696 $count_query .= ' LIMIT 1';
699 // run the count query
701 PMA_DBI_try_query($count_query);
702 // if (mysql_error()) {
705 // (SELECT `User`, `Host`, `Db`, `Select_priv` FROM `db`)
706 // UNION (SELECT `User`, `Host`, "%" AS "Db",
708 // FROM `user`) ORDER BY `User`, `Host`, `Db`;
709 // and although the generated count_query is wrong
710 // the SELECT FOUND_ROWS() work! (maybe it gets the
711 // count from the latest query that worked)
713 // another case where the count_query is wrong:
714 // SELECT COUNT(*), f1 from t1 group by f1
715 // and you click to sort on count(*)
717 $unlim_num_rows = PMA_DBI_fetch_value('SELECT FOUND_ROWS()');
718 } // end else "just browsing"
720 } else { // not $is_select
722 } // end rows total count
724 // if a table or database gets dropped, check column comments.
725 if (isset($purge) && $purge == '1') {
729 include_once 'libraries/relation_cleanup.lib.php';
731 if (strlen($table) && strlen($db)) {
732 PMA_relationsCleanupTable($db, $table);
733 } elseif (strlen($db)) {
734 PMA_relationsCleanupDatabase($db);
736 // VOID. No DB/Table gets deleted.
737 } // end if relation-stuff
740 // If a column gets dropped, do relation magic.
741 if (isset($dropped_column) && strlen($db) && strlen($table) && ! empty($dropped_column)) {
742 include_once 'libraries/relation_cleanup.lib.php';
743 PMA_relationsCleanupColumn($db, $table, $dropped_column);
744 // to refresh the list of indexes (Ajax mode)
745 $extra_data['indexes_list'] = PMA_Index
::getView($table, $db);
746 } // end if column was dropped
747 } // end else "didn't ask to see php code"
749 // No rows returned -> move back to the calling page
750 if ((0 == $num_rows && 0 == $unlim_num_rows) ||
$is_affected) {
752 $message = PMA_Message
::deleted_rows($num_rows);
753 } elseif ($is_insert) {
755 /* For replace we get DELETED + INSERTED row count, so we have to call it affected */
756 $message = PMA_Message
::affected_rows($num_rows);
758 $message = PMA_Message
::inserted_rows($num_rows);
760 $insert_id = PMA_DBI_insert_id();
761 if ($insert_id != 0) {
762 // insert_id is id of FIRST record inserted in one insert, so if we inserted multiple rows, we had to increment this
763 $message->addMessage('[br]');
764 // need to use a temporary because the Message class
765 // currently supports adding parameters only to the first
767 $_inserted = PMA_Message
::notice(__('Inserted row id: %1$d'));
768 $_inserted->addParam($insert_id +
$num_rows - 1);
769 $message->addMessage($_inserted);
771 } elseif ($is_affected) {
772 $message = PMA_Message
::affected_rows($num_rows);
774 // Ok, here is an explanation for the !$is_select.
775 // The form generated by sql_query_form.lib.php
776 // and db_sql.php has many submit buttons
777 // on the same form, and some confusion arises from the
778 // fact that $message_to_show is sent for every case.
779 // The $message_to_show containing a success message and sent with
780 // the form should not have priority over errors
781 } elseif (! empty($message_to_show) && ! $is_select) {
782 $message = PMA_Message
::rawSuccess(htmlspecialchars($message_to_show));
783 } elseif (! empty($GLOBALS['show_as_php'])) {
784 $message = PMA_Message
::success(__('Showing as PHP code'));
785 } elseif (isset($GLOBALS['show_as_php'])) {
786 /* User disable showing as PHP, query is only displayed */
787 $message = PMA_Message
::notice(__('Showing SQL query'));
788 } elseif (! empty($GLOBALS['validatequery'])) {
789 $message = PMA_Message
::notice(__('Validated SQL'));
791 $message = PMA_Message
::success(__('MySQL returned an empty result set (i.e. zero rows).'));
794 if (isset($GLOBALS['querytime'])) {
795 $_querytime = PMA_Message
::notice('(' . __('Query took %01.4f sec') . ')');
796 $_querytime->addParam($GLOBALS['querytime']);
797 $message->addMessage($_querytime);
800 if ($GLOBALS['is_ajax_request'] == true) {
801 if ($cfg['ShowSQL']) {
802 $extra_data['sql_query'] = PMA_showMessage($message, $GLOBALS['sql_query'], 'success');
804 if (isset($GLOBALS['reload']) && $GLOBALS['reload'] == 1) {
805 $extra_data['reload'] = 1;
806 $extra_data['db'] = $GLOBALS['db'];
808 PMA_ajaxResponse($message, $message->isSuccess(), (isset($extra_data) ?
$extra_data : ''));
812 $goto = PMA_securePath($goto);
813 // Checks for a valid target script
814 $is_db = $is_table = false;
815 if (isset($_REQUEST['purge']) && $_REQUEST['purge'] == '1') {
817 unset($url_params['table']);
819 include 'libraries/db_table_exists.lib.php';
821 if (strpos($goto, 'tbl_') === 0 && ! $is_table) {
822 if (strlen($table)) {
825 $goto = 'db_sql.php';
827 if (strpos($goto, 'db_') === 0 && ! $is_db) {
833 // Loads to target script
834 if ($goto != 'main.php') {
835 include_once 'libraries/header.inc.php';
837 $active_page = $goto;
840 // avoid a redirect loop when last record was deleted
841 if (0 == $num_rows && 'sql.php' == $cfg['DefaultTabTable']) {
842 $goto = str_replace('sql.php', 'tbl_structure.php', $goto);
844 PMA_sendHeaderLocation($cfg['PmaAbsoluteUri'] . str_replace('&', '&', $goto) . '&message=' . urlencode($message));
847 // end no rows returned
849 // At least one row is returned -> displays a table with results
850 //If we are retrieving the full value of a truncated field or the original
851 // value of a transformed field, show it here and exit
852 if ($GLOBALS['grid_edit'] == true && $GLOBALS['cfg']['AjaxEnable']) {
853 $row = PMA_DBI_fetch_row($result);
854 $extra_data = array();
855 $extra_data['value'] = $row[0];
856 PMA_ajaxResponse(null, true, $extra_data);
859 if (isset($_REQUEST['ajax_request']) && isset($_REQUEST['table_maintenance'])) {
860 $GLOBALS['js_include'][] = 'functions.js';
861 $GLOBALS['js_include'][] = 'makegrid.js';
862 $GLOBALS['js_include'][] = 'sql.js';
864 // Gets the list of fields properties
865 if (isset($result) && $result) {
866 $fields_meta = PMA_DBI_get_fields_meta($result);
867 $fields_cnt = count($fields_meta);
870 if (empty($disp_mode)) {
871 // see the "PMA_setDisplayMode()" function in
872 // libraries/display_tbl.lib.php
873 $disp_mode = 'urdr111101';
876 // hide edit and delete links for information_schema
877 if (PMA_is_system_schema($db)) {
878 $disp_mode = 'nnnn110111';
881 if (isset($message)) {
882 $message = PMA_Message
::success($message);
883 echo PMA_showMessage($message, $GLOBALS['sql_query'], 'success');
885 PMA_displayTable($result, $disp_mode, $analyzed_sql);
889 // Displays the headers
890 if (isset($show_query)) {
893 if (isset($printview) && $printview == '1') {
894 include_once 'libraries/header_printview.inc.php';
897 $GLOBALS['js_include'][] = 'functions.js';
898 $GLOBALS['js_include'][] = 'makegrid.js';
899 $GLOBALS['js_include'][] = 'sql.js';
903 if (! $GLOBALS['is_ajax_request'] ||
! $GLOBALS['cfg']['AjaxEnable']) {
904 if (strlen($table)) {
905 include 'libraries/tbl_common.php';
906 $url_query .= '&goto=tbl_sql.php&back=tbl_sql.php';
907 include 'libraries/tbl_info.inc.php';
908 include 'libraries/tbl_links.inc.php';
909 } elseif (strlen($db)) {
910 include 'libraries/db_common.inc.php';
911 include 'libraries/db_info.inc.php';
913 include 'libraries/server_common.inc.php';
914 include 'libraries/server_links.inc.php';
917 include_once 'libraries/header.inc.php';
918 //we don't need to buffer the output in PMA_showMessage here.
919 //set a global variable and check against it in the function
920 $GLOBALS['buffer_message'] = false;
925 $cfgRelation = PMA_getRelationsParam();
928 // Gets the list of fields properties
929 if (isset($result) && $result) {
930 $fields_meta = PMA_DBI_get_fields_meta($result);
931 $fields_cnt = count($fields_meta);
934 if (! $GLOBALS['is_ajax_request']) {
935 //begin the sqlqueryresults div here. container div
936 echo '<div id="sqlqueryresults"';
937 if ($GLOBALS['cfg']['AjaxEnable']) {
938 echo ' class="ajax"';
943 // Display previous update query (from tbl_replace)
944 if (isset($disp_query) && $cfg['ShowSQL'] == true) {
945 PMA_showMessage($disp_message, $disp_query, 'success');
948 if (isset($profiling_results)) {
949 // pma_token/url_query needed for chart export
951 <script type
="text/javascript">
952 pma_token
= '<?php echo $_SESSION[' PMA_token
']; ?>';
953 url_query
= '<?php echo isset($url_query)?$url_query:PMA_generate_common_url($db);?>';
954 $
(makeProfilingChart
);
957 echo '<fieldset><legend>' . __('Profiling') . '</legend>' . "\n";
958 echo '<div style="float: left;">';
959 echo '<table>' . "\n";
961 echo ' <th>' . __('Status') . PMA_showMySQLDocu('general-thread-states', 'general-thread-states') . '</th>' . "\n";
962 echo ' <th>' . __('Time') . '</th>' . "\n";
963 echo ' </tr>' . "\n";
965 $chart_json = Array();
966 foreach ($profiling_results as $one_result) {
968 echo '<td>' . ucwords($one_result['Status']) . '</td>' . "\n";
969 echo '<td class="right">' . (PMA_formatNumber($one_result['Duration'], 3, 1)) . 's</td>' . "\n";
970 if (isset($chart_json[ucwords($one_result['Status'])])) {
971 $chart_json[ucwords($one_result['Status'])] +
= $one_result['Duration'];
973 $chart_json[ucwords($one_result['Status'])] = $one_result['Duration'];
977 echo '</table>' . "\n";
979 //require_once 'libraries/chart.lib.php';
980 echo '<div id="profilingchart" style="display:none;">';
981 //PMA_chart_profiling($profiling_results);
982 echo json_encode($chart_json);
984 echo '</fieldset>' . "\n";
987 // Displays the results in a table
988 if (empty($disp_mode)) {
989 // see the "PMA_setDisplayMode()" function in
990 // libraries/display_tbl.lib.php
991 $disp_mode = 'urdr111101';
994 // hide edit and delete links for information_schema
995 if (PMA_is_system_schema($db)) {
996 $disp_mode = 'nnnn110111';
1000 $message = PMA_message
::success(__('Bookmark %s created'));
1001 $message->addParam($label);
1002 $message->display();
1005 PMA_displayTable($result, $disp_mode, $analyzed_sql);
1006 PMA_DBI_free_result($result);
1008 // BEGIN INDEX CHECK See if indexes should be checked.
1009 if (isset($query_type) && $query_type == 'check_tbl' && isset($selected) && is_array($selected)) {
1010 foreach ($selected as $idx => $tbl_name) {
1011 $check = PMA_Index
::findDuplicates($tbl_name, $db);
1012 if (! empty($check)) {
1013 printf(__('Problems with indexes of table `%s`'), $tbl_name);
1017 } // End INDEX CHECK
1019 // Bookmark support if required
1020 if ($disp_mode[7] == '1'
1021 && (! empty($cfg['Bookmark']) && empty($id_bookmark))
1022 && ! empty($sql_query)
1027 . PMA_generate_common_url($db, $table)
1028 . '&sql_query=' . urlencode($sql_query)
1029 . '&id_bookmark=1';
1032 <form action
="sql.php" method
="post" onsubmit
="return emptyFormElements(this, 'fields[label]');">
1033 <?php
echo PMA_generate_common_hidden_inputs(); ?
>
1034 <input type
="hidden" name
="goto" value
="<?php echo $goto; ?>" />
1035 <input type
="hidden" name
="fields[dbase]" value
="<?php echo htmlspecialchars($db); ?>" />
1036 <input type
="hidden" name
="fields[user]" value
="<?php echo $cfg['Bookmark']['user']; ?>" />
1037 <input type
="hidden" name
="fields[query]" value
="<?php echo urlencode(isset($complete_query) ? $complete_query : $sql_query); ?>" />
1040 echo PMA_getIcon('b_bookmark.png', __('Bookmark this SQL query'), true);
1044 <div
class="formelement">
1045 <label
for="fields_label_"><?php
echo __('Label'); ?
>:</label
>
1046 <input type
="text" id
="fields_label_" name
="fields[label]" value
="" />
1049 <div
class="formelement">
1050 <input type
="checkbox" name
="bkm_all_users" id
="bkm_all_users" value
="true" />
1051 <label
for="bkm_all_users"><?php
echo __('Let every user access this bookmark'); ?
></label
>
1054 <div
class="clearfloat"></div
>
1056 <fieldset
class="tblFooters">
1057 <input type
="submit" name
="store_bkm" value
="<?php echo __('Bookmark this SQL query'); ?>" />
1061 } // end bookmark support
1063 // Do print the page if required
1064 if (isset($printview) && $printview == '1') {
1068 if ($GLOBALS['is_ajax_request'] != true) {
1069 echo '</div>'; // end sqlqueryresults div
1071 } // end rows returned
1074 * Displays the footer
1076 if (! isset($_REQUEST['table_maintenance'])) {
1077 include 'libraries/footer.inc.php';