Translated using Weblate.
[phpmyadmin.git] / sql.php
blobb006141655b77efe5830c3bba8a6b8ecb52f3b3e
1 <?php
2 /* vim: set expandtab sw=4 ts=4 sts=4: */
3 /**
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
6 * @package PhpMyAdmin
7 */
9 /**
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/jquery-ui-1.8.16.custom.js';
18 $GLOBALS['js_include'][] = 'jquery/timepicker.js';
19 $GLOBALS['js_include'][] = 'tbl_change.js';
20 // the next one needed because sql.php may do a "goto" to tbl_structure.php
21 $GLOBALS['js_include'][] = 'tbl_structure.js';
22 $GLOBALS['js_include'][] = 'gis_data_editor.js';
23 $GLOBALS['js_include'][] = 'codemirror/lib/codemirror.js';
24 $GLOBALS['js_include'][] = 'codemirror/mode/mysql/mysql.js';
26 if (isset($_REQUEST['printview'])) {
27 $GLOBALS['printview'] = $_REQUEST['printview'];
30 if (isset($_SESSION['profiling'])) {
31 $GLOBALS['js_include'][] = 'highcharts/highcharts.js';
32 /* Files required for chart exporting */
33 $GLOBALS['js_include'][] = 'highcharts/exporting.js';
34 /* < IE 9 doesn't support canvas natively */
35 if (PMA_USR_BROWSER_AGENT == 'IE' && PMA_USR_BROWSER_VER < 9) {
36 $GLOBALS['js_include'][] = 'canvg/flashcanvas.js';
38 $GLOBALS['js_include'][] = 'canvg/canvg.js';
41 /**
42 * Defines the url to return to in case of error in a sql statement
44 // Security checkings
45 if (! empty($goto)) {
46 $is_gotofile = preg_replace('@^([^?]+).*$@s', '\\1', $goto);
47 if (! @file_exists('./' . $is_gotofile)) {
48 unset($goto);
49 } else {
50 $is_gotofile = ($is_gotofile == $goto);
52 } else {
53 $goto = (! strlen($table)) ? $cfg['DefaultTabDatabase'] : $cfg['DefaultTabTable'];
54 $is_gotofile = true;
55 } // end if
57 if (! isset($err_url)) {
58 $err_url = (! empty($back) ? $back : $goto)
59 . '?' . PMA_generate_common_url($db)
60 . ((strpos(' ' . $goto, 'db_') != 1 && strlen($table)) ? '&amp;table=' . urlencode($table) : '');
61 } // end if
63 // Coming from a bookmark dialog
64 if (isset($fields['query'])) {
65 $sql_query = $fields['query'];
68 // This one is just to fill $db
69 if (isset($fields['dbase'])) {
70 $db = $fields['dbase'];
73 /**
74 * During grid edit, if we have a relational field, show the dropdown for it
76 * Logic taken from libraries/display_tbl_lib.php
78 * This doesn't seem to be the right place to do this, but I can't think of any
79 * better place either.
81 if (isset($_REQUEST['get_relational_values']) && $_REQUEST['get_relational_values'] == true) {
82 include_once 'libraries/relation.lib.php';
84 $column = $_REQUEST['column'];
85 $foreigners = PMA_getForeigners($db, $table, $column);
87 $display_field = PMA_getDisplayField($foreigners[$column]['foreign_db'], $foreigners[$column]['foreign_table']);
89 $foreignData = PMA_getForeignData($foreigners, $column, false, '', '');
91 if ($_SESSION['tmp_user_values']['relational_display'] == 'D'
92 && isset($display_field)
93 && strlen($display_field)
94 && isset($_REQUEST['relation_key_or_display_column'])
95 && $_REQUEST['relation_key_or_display_column']
96 ) {
97 $curr_value = $_REQUEST['relation_key_or_display_column'];
98 } else {
99 $curr_value = $_REQUEST['curr_value'];
101 if ($foreignData['disp_row'] == null) {
102 //Handle the case when number of values is more than $cfg['ForeignKeyMaxLimit']
103 $_url_params = array(
104 'db' => $db,
105 'table' => $table,
106 'field' => $column
109 $dropdown = '<span class="curr_value">' . htmlspecialchars($_REQUEST['curr_value']) . '</span> <a href="browse_foreigners.php' . PMA_generate_common_url($_url_params) . '"'
110 . ' target="_blank" class="browse_foreign" '
111 .'>' . __('Browse foreign values') . '</a>';
112 } else {
113 $dropdown = PMA_foreignDropdown($foreignData['disp_row'], $foreignData['foreign_field'], $foreignData['foreign_display'], $curr_value, $cfg['ForeignKeyMaxLimit']);
114 $dropdown = '<select>' . $dropdown . '</select>';
117 $extra_data['dropdown'] = $dropdown;
118 PMA_ajaxResponse(null, true, $extra_data);
122 * Just like above, find possible values for enum fields during grid edit.
124 * Logic taken from libraries/display_tbl_lib.php
126 if (isset($_REQUEST['get_enum_values']) && $_REQUEST['get_enum_values'] == true) {
127 $field_info_query = PMA_DBI_get_columns_sql($db, $table, $_REQUEST['column']);
129 $field_info_result = PMA_DBI_fetch_result($field_info_query, null, null, null, PMA_DBI_QUERY_STORE);
131 $search = array('enum', '(', ')', "'");
133 $values = explode(',', str_replace($search, '', $field_info_result[0]['Type']));
135 $dropdown = '<option value="">&nbsp;</option>';
136 foreach ($values as $value) {
137 $dropdown .= '<option value="' . htmlspecialchars($value) . '"';
138 if ($value == $_REQUEST['curr_value']) {
139 $dropdown .= ' selected="selected"';
141 $dropdown .= '>' . $value . '</option>';
144 $dropdown = '<select>' . $dropdown . '</select>';
146 $extra_data['dropdown'] = $dropdown;
147 PMA_ajaxResponse(null, true, $extra_data);
151 * Find possible values for set fields during grid edit.
153 if (isset($_REQUEST['get_set_values']) && $_REQUEST['get_set_values'] == true) {
154 $field_info_query = PMA_DBI_get_columns_sql($db, $table, $_REQUEST['column']);
156 $field_info_result = PMA_DBI_fetch_result($field_info_query, null, null, null, PMA_DBI_QUERY_STORE);
158 $selected_values = explode(',', $_REQUEST['curr_value']);
160 $search = array('set', '(', ')', "'");
161 $values = explode(',', str_replace($search, '', $field_info_result[0]['Type']));
163 $select = '';
164 foreach ($values as $value) {
165 $select .= '<option value="' . htmlspecialchars($value) . '"';
166 if (in_array($value, $selected_values, true)) {
167 $select .= ' selected="selected"';
169 $select .= '>' . $value . '</option>';
172 $select_size = (sizeof($values) > 10) ? 10 : sizeof($values);
173 $select = '<select multiple="multiple" size="' . $select_size . '">' . $select . '</select>';
175 $extra_data['select'] = $select;
176 PMA_ajaxResponse(null, true, $extra_data);
180 * Check ajax request to set the column order
182 if (isset($_REQUEST['set_col_prefs']) && $_REQUEST['set_col_prefs'] == true) {
183 $pmatable = new PMA_Table($table, $db);
184 $retval = false;
186 // set column order
187 if (isset($_REQUEST['col_order'])) {
188 $col_order = explode(',', $_REQUEST['col_order']);
189 $retval = $pmatable->setUiProp(PMA_Table::PROP_COLUMN_ORDER, $col_order, $_REQUEST['table_create_time']);
190 if (gettype($retval) != 'boolean') {
191 PMA_ajaxResponse($retval->getString(), false);
195 // set column visibility
196 if ($retval === true && isset($_REQUEST['col_visib'])) {
197 $col_visib = explode(',', $_REQUEST['col_visib']);
198 $retval = $pmatable->setUiProp(PMA_Table::PROP_COLUMN_VISIB, $col_visib, $_REQUEST['table_create_time']);
199 if (gettype($retval) != 'boolean') {
200 PMA_ajaxResponse($retval->getString(), false);
204 PMA_ajaxResponse(null, ($retval == true));
207 // Default to browse if no query set and we have table
208 // (needed for browsing from DefaultTabTable)
209 if (empty($sql_query) && strlen($table) && strlen($db)) {
210 include_once './libraries/bookmark.lib.php';
211 $book_sql_query = PMA_Bookmark_get(
212 $db,
213 '\'' . PMA_sqlAddSlashes($table) . '\'',
214 'label',
215 false,
216 true
219 if (! empty($book_sql_query)) {
220 $GLOBALS['using_bookmark_message'] = PMA_message::notice(__('Using bookmark "%s" as default browse query.'));
221 $GLOBALS['using_bookmark_message']->addParam($table);
222 $GLOBALS['using_bookmark_message']->addMessage(PMA_showDocu('faq6_22'));
223 $sql_query = $book_sql_query;
224 } else {
225 $sql_query = 'SELECT * FROM ' . PMA_backquote($table);
227 unset($book_sql_query);
229 // set $goto to what will be displayed if query returns 0 rows
230 $goto = 'tbl_structure.php';
231 } else {
232 // Now we can check the parameters
233 PMA_checkParameters(array('sql_query'));
236 // instead of doing the test twice
237 $is_drop_database = preg_match(
238 '/DROP[[:space:]]+(DATABASE|SCHEMA)[[:space:]]+/i',
239 $sql_query
243 * Check rights in case of DROP DATABASE
245 * This test may be bypassed if $is_js_confirmed = 1 (already checked with js)
246 * but since a malicious user may pass this variable by url/form, we don't take
247 * into account this case.
249 if (! defined('PMA_CHK_DROP')
250 && ! $cfg['AllowUserDropDatabase']
251 && $is_drop_database
252 && ! $is_superuser
254 include_once './libraries/header.inc.php';
255 PMA_mysqlDie(__('"DROP DATABASE" statements are disabled.'), '', '', $err_url);
256 } // end if
258 require_once './libraries/display_tbl.lib.php';
259 PMA_displayTable_checkConfigParams();
262 * Need to find the real end of rows?
264 if (isset($find_real_end) && $find_real_end) {
265 $unlim_num_rows = PMA_Table::countRecords($db, $table, $force_exact = true);
266 $_SESSION['tmp_user_values']['pos'] = @((ceil($unlim_num_rows / $_SESSION['tmp_user_values']['max_rows']) - 1) * $_SESSION['tmp_user_values']['max_rows']);
271 * Bookmark add
273 if (isset($store_bkm)) {
274 PMA_Bookmark_save($fields, (isset($bkm_all_users) && $bkm_all_users == 'true' ? true : false));
275 // go back to sql.php to redisplay query; do not use &amp; in this case:
276 PMA_sendHeaderLocation($cfg['PmaAbsoluteUri'] . $goto . '&label=' . $fields['label']);
277 } // end if
280 * Parse and analyze the query
282 require_once './libraries/parse_analyze.lib.php';
285 * Sets or modifies the $goto variable if required
287 if ($goto == 'sql.php') {
288 $is_gotofile = false;
289 $goto = 'sql.php?'
290 . PMA_generate_common_url($db, $table)
291 . '&amp;sql_query=' . urlencode($sql_query);
292 } // end if
296 * Go back to further page if table should not be dropped
298 if (isset($btnDrop) && $btnDrop == __('No')) {
299 if (! empty($back)) {
300 $goto = $back;
302 if ($is_gotofile) {
303 if (strpos($goto, 'db_') === 0 && strlen($table)) {
304 $table = '';
306 $active_page = $goto;
307 include './' . PMA_securePath($goto);
308 } else {
309 PMA_sendHeaderLocation($cfg['PmaAbsoluteUri'] . str_replace('&amp;', '&', $goto));
311 exit();
312 } // end if
316 * Displays the confirm page if required
318 * This part of the script is bypassed if $is_js_confirmed = 1 (already checked
319 * with js) because possible security issue is not so important here: at most,
320 * the confirm message isn't displayed.
322 * Also bypassed if only showing php code.or validating a SQL query
324 if (! $cfg['Confirm']
325 || isset($_REQUEST['is_js_confirmed'])
326 || isset($btnDrop)
327 // if we are coming from a "Create PHP code" or a "Without PHP Code"
328 // dialog, we won't execute the query anyway, so don't confirm
329 || isset($GLOBALS['show_as_php'])
330 || ! empty($GLOBALS['validatequery'])
332 $do_confirm = false;
333 } else {
334 $do_confirm = isset($analyzed_sql[0]['queryflags']['need_confirm']);
337 if ($do_confirm) {
338 $stripped_sql_query = $sql_query;
339 include_once './libraries/header.inc.php';
340 if ($is_drop_database) {
341 echo '<h1 class="error">' . __('You are about to DESTROY a complete database!') . '</h1>';
343 echo '<form action="sql.php" method="post">' . "\n"
344 .PMA_generate_common_hidden_inputs($db, $table);
346 <input type="hidden" name="sql_query" value="<?php echo htmlspecialchars($sql_query); ?>" />
347 <input type="hidden" name="message_to_show" value="<?php echo isset($message_to_show) ? PMA_sanitize($message_to_show, true) : ''; ?>" />
348 <input type="hidden" name="goto" value="<?php echo $goto; ?>" />
349 <input type="hidden" name="back" value="<?php echo isset($back) ? PMA_sanitize($back, true) : ''; ?>" />
350 <input type="hidden" name="reload" value="<?php echo isset($reload) ? PMA_sanitize($reload, true) : 0; ?>" />
351 <input type="hidden" name="purge" value="<?php echo isset($purge) ? PMA_sanitize($purge, true) : ''; ?>" />
352 <input type="hidden" name="dropped_column" value="<?php echo isset($dropped_column) ? PMA_sanitize($dropped_column, true) : ''; ?>" />
353 <input type="hidden" name="show_query" value="<?php echo isset($show_query) ? PMA_sanitize($show_query, true) : ''; ?>" />
354 <?php
355 echo '<fieldset class="confirmation">' . "\n"
356 .' <legend>' . __('Do you really want to ') . '</legend>'
357 .' <tt>' . htmlspecialchars($stripped_sql_query) . '</tt>' . "\n"
358 .'</fieldset>' . "\n"
359 .'<fieldset class="tblFooters">' . "\n";
361 <input type="submit" name="btnDrop" value="<?php echo __('Yes'); ?>" id="buttonYes" />
362 <input type="submit" name="btnDrop" value="<?php echo __('No'); ?>" id="buttonNo" />
363 <?php
364 echo '</fieldset>' . "\n"
365 . '</form>' . "\n";
368 * Displays the footer and exit
370 include './libraries/footer.inc.php';
371 } // end if $do_confirm
374 // Defines some variables
375 // A table has to be created, renamed, dropped -> navi frame should be reloaded
377 * @todo use the parser/analyzer
380 if (empty($reload)
381 && preg_match('/^(CREATE|ALTER|DROP)\s+(VIEW|TABLE|DATABASE|SCHEMA)\s+/i', $sql_query)
383 $reload = 1;
386 // SK -- Patch: $is_group added for use in calculation of total number of
387 // rows.
388 // $is_count is changed for more correct "LIMIT" clause
389 // appending in queries like
390 // "SELECT COUNT(...) FROM ... GROUP BY ..."
393 * @todo detect all this with the parser, to avoid problems finding
394 * those strings in comments or backquoted identifiers
397 $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;
398 if ($is_select) { // see line 141
399 $is_group = preg_match('@(GROUP[[:space:]]+BY|HAVING|SELECT[[:space:]]+DISTINCT)[[:space:]]+@i', $sql_query);
400 $is_func = ! $is_group && (preg_match('@[[:space:]]+(SUM|AVG|STD|STDDEV|MIN|MAX|BIT_OR|BIT_AND)\s*\(@i', $sql_query));
401 $is_count = ! $is_group && (preg_match('@^SELECT[[:space:]]+COUNT\((.*\.+)?.*\)@i', $sql_query));
402 $is_export = (preg_match('@[[:space:]]+INTO[[:space:]]+OUTFILE[[:space:]]+@i', $sql_query));
403 $is_analyse = (preg_match('@[[:space:]]+PROCEDURE[[:space:]]+ANALYSE@i', $sql_query));
404 } elseif (preg_match('@^EXPLAIN[[:space:]]+@i', $sql_query)) {
405 $is_explain = true;
406 } elseif (preg_match('@^DELETE[[:space:]]+@i', $sql_query)) {
407 $is_delete = true;
408 $is_affected = true;
409 } elseif (preg_match('@^(INSERT|LOAD[[:space:]]+DATA|REPLACE)[[:space:]]+@i', $sql_query)) {
410 $is_insert = true;
411 $is_affected = true;
412 if (preg_match('@^(REPLACE)[[:space:]]+@i', $sql_query)) {
413 $is_replace = true;
415 } elseif (preg_match('@^UPDATE[[:space:]]+@i', $sql_query)) {
416 $is_affected = true;
417 } elseif (preg_match('@^[[:space:]]*SHOW[[:space:]]+@i', $sql_query)) {
418 $is_show = true;
419 } elseif (preg_match('@^(CHECK|ANALYZE|REPAIR|OPTIMIZE)[[:space:]]+TABLE[[:space:]]+@i', $sql_query)) {
420 $is_maint = true;
423 // assign default full_sql_query
424 $full_sql_query = $sql_query;
426 // Handle remembered sorting order, only for single table query
427 if ($GLOBALS['cfg']['RememberSorting']
428 && ! ($is_count || $is_export || $is_func || $is_analyse)
429 && count($analyzed_sql[0]['select_expr']) == 0
430 && isset($analyzed_sql[0]['queryflags']['select_from'])
431 && count($analyzed_sql[0]['table_ref']) == 1
433 $pmatable = new PMA_Table($table, $db);
434 if (empty($analyzed_sql[0]['order_by_clause'])) {
435 $sorted_col = $pmatable->getUiProp(PMA_Table::PROP_SORTED_COLUMN);
436 if ($sorted_col) {
437 // retrieve the remembered sorting order for current table
438 $sql_order_to_append = ' ORDER BY ' . $sorted_col . ' ';
439 $full_sql_query = $analyzed_sql[0]['section_before_limit'] . $sql_order_to_append
440 . $analyzed_sql[0]['section_after_limit'];
442 // update the $analyzed_sql
443 $analyzed_sql[0]['section_before_limit'] .= $sql_order_to_append;
444 $analyzed_sql[0]['order_by_clause'] = $sorted_col;
446 } else {
447 // store the remembered table into session
448 $pmatable->setUiProp(PMA_Table::PROP_SORTED_COLUMN, $analyzed_sql[0]['order_by_clause']);
452 // Do append a "LIMIT" clause?
453 if (($_SESSION['tmp_user_values']['max_rows'] != 'all')
454 && ! ($is_count || $is_export || $is_func || $is_analyse)
455 && isset($analyzed_sql[0]['queryflags']['select_from'])
456 && ! isset($analyzed_sql[0]['queryflags']['offset'])
457 && empty($analyzed_sql[0]['limit_clause'])
459 $sql_limit_to_append = ' LIMIT ' . $_SESSION['tmp_user_values']['pos']
460 . ', ' . $_SESSION['tmp_user_values']['max_rows'] . " ";
462 $full_sql_query = $analyzed_sql[0]['section_before_limit'] . "\n"
463 . $sql_limit_to_append . $analyzed_sql[0]['section_after_limit'];
465 * @todo pretty printing of this modified query
467 if (isset($display_query)) {
468 // if the analysis of the original query revealed that we found
469 // a section_after_limit, we now have to analyze $display_query
470 // to display it correctly
472 if (! empty($analyzed_sql[0]['section_after_limit'])
473 && trim($analyzed_sql[0]['section_after_limit']) != ';'
475 $analyzed_display_query = PMA_SQP_analyze(PMA_SQP_parse($display_query));
476 $display_query = $analyzed_display_query[0]['section_before_limit']
477 . "\n" . $sql_limit_to_append . $analyzed_display_query[0]['section_after_limit'];
483 if (strlen($db)) {
484 PMA_DBI_select_db($db);
487 // E x e c u t e t h e q u e r y
489 // Only if we didn't ask to see the php code (mikebeck)
490 if (isset($GLOBALS['show_as_php']) || ! empty($GLOBALS['validatequery'])) {
491 unset($result);
492 $num_rows = 0;
493 $unlim_num_rows = 0;
494 } else {
495 if (isset($_SESSION['profiling']) && PMA_profilingSupported()) {
496 PMA_DBI_query('SET PROFILING=1;');
499 // Measure query time.
500 $querytime_before = array_sum(explode(' ', microtime()));
502 $result = @PMA_DBI_try_query($full_sql_query, null, PMA_DBI_QUERY_STORE);
504 // If a stored procedure was called, there may be more results that are
505 // queued up and waiting to be flushed from the buffer. So let's do that.
506 while (true) {
507 if (! PMA_DBI_more_results()) {
508 break;
510 PMA_DBI_next_result();
513 $querytime_after = array_sum(explode(' ', microtime()));
515 $GLOBALS['querytime'] = $querytime_after - $querytime_before;
517 // Displays an error message if required and stop parsing the script
518 if ($error = PMA_DBI_getError()) {
519 if ($is_gotofile) {
520 if (strpos($goto, 'db_') === 0 && strlen($table)) {
521 $table = '';
523 $active_page = $goto;
524 $message = PMA_Message::rawError($error);
526 if ($GLOBALS['is_ajax_request'] == true) {
527 PMA_ajaxResponse($message, false);
531 * Go to target path.
533 include './' . PMA_securePath($goto);
534 } else {
535 $full_err_url = (preg_match('@^(db|tbl)_@', $err_url))
536 ? $err_url . '&amp;show_query=1&amp;sql_query=' . urlencode($sql_query)
537 : $err_url;
538 PMA_mysqlDie($error, $full_sql_query, '', $full_err_url);
540 exit;
542 unset($error);
544 // Gets the number of rows affected/returned
545 // (This must be done immediately after the query because
546 // mysql_affected_rows() reports about the last query done)
548 if (! $is_affected) {
549 $num_rows = ($result) ? @PMA_DBI_num_rows($result) : 0;
550 } elseif (! isset($num_rows)) {
551 $num_rows = @PMA_DBI_affected_rows();
554 // Grabs the profiling results
555 if (isset($_SESSION['profiling']) && PMA_profilingSupported()) {
556 $profiling_results = PMA_DBI_fetch_result('SHOW PROFILE;');
559 // Checks if the current database has changed
560 // This could happen if the user sends a query like "USE `database`;"
562 * commented out auto-switching to active database - really required?
563 * bug #1814718 win: table list disappears (mixed case db names)
564 * https://sourceforge.net/support/tracker.php?aid=1814718
565 * @todo RELEASE test and comit or rollback before release
566 $current_db = PMA_DBI_fetch_value('SELECT DATABASE()');
567 if ($db !== $current_db) {
568 $db = $current_db;
569 $reload = 1;
571 unset($current_db);
574 // tmpfile remove after convert encoding appended by Y.Kawada
575 if (function_exists('PMA_kanji_file_conv')
576 && (isset($textfile) && file_exists($textfile))
578 unlink($textfile);
581 // Counts the total number of rows for the same 'SELECT' query without the
582 // 'LIMIT' clause that may have been programatically added
584 if (empty($sql_limit_to_append)) {
585 $unlim_num_rows = $num_rows;
586 // if we did not append a limit, set this to get a correct
587 // "Showing rows..." message
588 //$_SESSION['tmp_user_values']['max_rows'] = 'all';
589 } elseif ($is_select) {
591 // c o u n t q u e r y
593 // If we are "just browsing", there is only one table,
594 // and no WHERE clause (or just 'WHERE 1 '),
595 // we do a quick count (which uses MaxExactCount) because
596 // SQL_CALC_FOUND_ROWS is not quick on large InnoDB tables
598 // However, do not count again if we did it previously
599 // due to $find_real_end == true
601 if (! $is_group
602 && ! isset($analyzed_sql[0]['queryflags']['union'])
603 && ! isset($analyzed_sql[0]['queryflags']['distinct'])
604 && ! isset($analyzed_sql[0]['table_ref'][1]['table_name'])
605 && (empty($analyzed_sql[0]['where_clause']) || $analyzed_sql[0]['where_clause'] == '1 ')
606 && ! isset($find_real_end)
609 // "j u s t b r o w s i n g"
610 $unlim_num_rows = PMA_Table::countRecords($db, $table);
612 } else { // n o t " j u s t b r o w s i n g "
614 // add select expression after the SQL_CALC_FOUND_ROWS
616 // for UNION, just adding SQL_CALC_FOUND_ROWS
617 // after the first SELECT works.
619 // take the left part, could be:
620 // SELECT
621 // (SELECT
622 $count_query = PMA_SQP_formatHtml($parsed_sql, 'query_only', 0, $analyzed_sql[0]['position_of_first_select'] + 1);
623 $count_query .= ' SQL_CALC_FOUND_ROWS ';
624 // add everything that was after the first SELECT
625 $count_query .= PMA_SQP_formatHtml($parsed_sql, 'query_only', $analyzed_sql[0]['position_of_first_select'] + 1);
626 // ensure there is no semicolon at the end of the
627 // count query because we'll probably add
628 // a LIMIT 1 clause after it
629 $count_query = rtrim($count_query);
630 $count_query = rtrim($count_query, ';');
632 // if using SQL_CALC_FOUND_ROWS, add a LIMIT to avoid
633 // long delays. Returned count will be complete anyway.
634 // (but a LIMIT would disrupt results in an UNION)
636 if (! isset($analyzed_sql[0]['queryflags']['union'])) {
637 $count_query .= ' LIMIT 1';
640 // run the count query
642 PMA_DBI_try_query($count_query);
643 // if (mysql_error()) {
644 // void.
645 // I tried the case
646 // (SELECT `User`, `Host`, `Db`, `Select_priv` FROM `db`)
647 // UNION (SELECT `User`, `Host`, "%" AS "Db",
648 // `Select_priv`
649 // FROM `user`) ORDER BY `User`, `Host`, `Db`;
650 // and although the generated count_query is wrong
651 // the SELECT FOUND_ROWS() work! (maybe it gets the
652 // count from the latest query that worked)
654 // another case where the count_query is wrong:
655 // SELECT COUNT(*), f1 from t1 group by f1
656 // and you click to sort on count(*)
657 // }
658 $unlim_num_rows = PMA_DBI_fetch_value('SELECT FOUND_ROWS()');
659 } // end else "just browsing"
661 } else { // not $is_select
662 $unlim_num_rows = 0;
663 } // end rows total count
665 // if a table or database gets dropped, check column comments.
666 if (isset($purge) && $purge == '1') {
668 * Cleanup relations.
670 include_once './libraries/relation_cleanup.lib.php';
672 if (strlen($table) && strlen($db)) {
673 PMA_relationsCleanupTable($db, $table);
674 } elseif (strlen($db)) {
675 PMA_relationsCleanupDatabase($db);
676 } else {
677 // VOID. No DB/Table gets deleted.
678 } // end if relation-stuff
679 } // end if ($purge)
681 // If a column gets dropped, do relation magic.
682 if (isset($dropped_column) && strlen($db) && strlen($table) && ! empty($dropped_column)) {
683 include_once './libraries/relation_cleanup.lib.php';
684 PMA_relationsCleanupColumn($db, $table, $dropped_column);
685 // to refresh the list of indexes (Ajax mode)
686 $extra_data['indexes_list'] = PMA_Index::getView($table, $db);
687 } // end if column was dropped
688 } // end else "didn't ask to see php code"
690 // No rows returned -> move back to the calling page
691 if ((0 == $num_rows && 0 == $unlim_num_rows) || $is_affected) {
692 if ($is_delete) {
693 $message = PMA_Message::deleted_rows($num_rows);
694 } elseif ($is_insert) {
695 if ($is_replace) {
696 /* For replace we get DELETED + INSERTED row count, so we have to call it affected */
697 $message = PMA_Message::affected_rows($num_rows);
698 } else {
699 $message = PMA_Message::inserted_rows($num_rows);
701 $insert_id = PMA_DBI_insert_id();
702 if ($insert_id != 0) {
703 // insert_id is id of FIRST record inserted in one insert, so if we inserted multiple rows, we had to increment this
704 $message->addMessage('[br]');
705 // need to use a temporary because the Message class
706 // currently supports adding parameters only to the first
707 // message
708 $_inserted = PMA_Message::notice(__('Inserted row id: %1$d'));
709 $_inserted->addParam($insert_id + $num_rows - 1);
710 $message->addMessage($_inserted);
712 } elseif ($is_affected) {
713 $message = PMA_Message::affected_rows($num_rows);
715 // Ok, here is an explanation for the !$is_select.
716 // The form generated by sql_query_form.lib.php
717 // and db_sql.php has many submit buttons
718 // on the same form, and some confusion arises from the
719 // fact that $message_to_show is sent for every case.
720 // The $message_to_show containing a success message and sent with
721 // the form should not have priority over errors
722 } elseif (! empty($message_to_show) && ! $is_select) {
723 $message = PMA_Message::rawSuccess(htmlspecialchars($message_to_show));
724 } elseif (! empty($GLOBALS['show_as_php'])) {
725 $message = PMA_Message::success(__('Showing as PHP code'));
726 } elseif (isset($GLOBALS['show_as_php'])) {
727 /* User disable showing as PHP, query is only displayed */
728 $message = PMA_Message::notice(__('Showing SQL query'));
729 } elseif (! empty($GLOBALS['validatequery'])) {
730 $message = PMA_Message::notice(__('Validated SQL'));
731 } else {
732 $message = PMA_Message::success(__('MySQL returned an empty result set (i.e. zero rows).'));
735 if (isset($GLOBALS['querytime'])) {
736 $_querytime = PMA_Message::notice(__('Query took %01.4f sec'));
737 $_querytime->addParam($GLOBALS['querytime']);
738 $message->addMessage('(');
739 $message->addMessage($_querytime);
740 $message->addMessage(')');
743 if ($GLOBALS['is_ajax_request'] == true) {
744 if ($cfg['ShowSQL']) {
745 $extra_data['sql_query'] = PMA_showMessage($message, $GLOBALS['sql_query'], 'success');
747 if (isset($GLOBALS['reload']) && $GLOBALS['reload'] == 1) {
748 $extra_data['reload'] = 1;
749 $extra_data['db'] = $GLOBALS['db'];
751 PMA_ajaxResponse($message, $message->isSuccess(), (isset($extra_data) ? $extra_data : ''));
754 if ($is_gotofile) {
755 $goto = PMA_securePath($goto);
756 // Checks for a valid target script
757 $is_db = $is_table = false;
758 if (isset($_REQUEST['purge']) && $_REQUEST['purge'] == '1') {
759 $table = '';
760 unset($url_params['table']);
762 include 'libraries/db_table_exists.lib.php';
764 if (strpos($goto, 'tbl_') === 0 && ! $is_table) {
765 if (strlen($table)) {
766 $table = '';
768 $goto = 'db_sql.php';
770 if (strpos($goto, 'db_') === 0 && ! $is_db) {
771 if (strlen($db)) {
772 $db = '';
774 $goto = 'main.php';
776 // Loads to target script
777 if ($goto != 'main.php') {
778 include_once './libraries/header.inc.php';
780 $active_page = $goto;
781 include './' . $goto;
782 } else {
783 // avoid a redirect loop when last record was deleted
784 if (0 == $num_rows && 'sql.php' == $cfg['DefaultTabTable']) {
785 $goto = str_replace('sql.php', 'tbl_structure.php', $goto);
787 PMA_sendHeaderLocation($cfg['PmaAbsoluteUri'] . str_replace('&amp;', '&', $goto) . '&message=' . urlencode($message));
788 } // end else
789 exit();
790 // end no rows returned
791 } else {
792 // At least one row is returned -> displays a table with results
793 //If we are retrieving the full value of a truncated field or the original
794 // value of a transformed field, show it here and exit
795 if ($GLOBALS['grid_edit'] == true && $GLOBALS['cfg']['AjaxEnable']) {
796 $row = PMA_DBI_fetch_row($result);
797 $extra_data = array();
798 $extra_data['value'] = $row[0];
799 PMA_ajaxResponse(null, true, $extra_data);
802 if (isset($_REQUEST['ajax_request']) && isset($_REQUEST['table_maintenance'])) {
803 $GLOBALS['js_include'][] = 'functions.js';
804 $GLOBALS['js_include'][] = 'makegrid.js';
805 $GLOBALS['js_include'][] = 'sql.js';
807 // Gets the list of fields properties
808 if (isset($result) && $result) {
809 $fields_meta = PMA_DBI_get_fields_meta($result);
810 $fields_cnt = count($fields_meta);
813 if (empty($disp_mode)) {
814 // see the "PMA_setDisplayMode()" function in
815 // libraries/display_tbl.lib.php
816 $disp_mode = 'urdr111101';
819 // hide edit and delete links for information_schema
820 if (PMA_is_system_schema($db)) {
821 $disp_mode = 'nnnn110111';
824 $message = PMA_Message::success($message);
825 echo PMA_showMessage($message, $GLOBALS['sql_query'], 'success');
826 PMA_displayTable($result, $disp_mode, $analyzed_sql);
827 exit();
830 // Displays the headers
831 if (isset($show_query)) {
832 unset($show_query);
834 if (isset($printview) && $printview == '1') {
835 include_once './libraries/header_printview.inc.php';
836 } else {
838 $GLOBALS['js_include'][] = 'functions.js';
839 $GLOBALS['js_include'][] = 'makegrid.js';
840 $GLOBALS['js_include'][] = 'sql.js';
842 unset($message);
844 if (! $GLOBALS['is_ajax_request'] || ! $GLOBALS['cfg']['AjaxEnable']) {
845 if (strlen($table)) {
846 include './libraries/tbl_common.php';
847 $url_query .= '&amp;goto=tbl_sql.php&amp;back=tbl_sql.php';
848 include './libraries/tbl_info.inc.php';
849 include './libraries/tbl_links.inc.php';
850 } elseif (strlen($db)) {
851 include './libraries/db_common.inc.php';
852 include './libraries/db_info.inc.php';
853 } else {
854 include './libraries/server_common.inc.php';
855 include './libraries/server_links.inc.php';
857 } else {
858 include_once './libraries/header.inc.php';
859 //we don't need to buffer the output in PMA_showMessage here.
860 //set a global variable and check against it in the function
861 $GLOBALS['buffer_message'] = false;
865 if (strlen($db)) {
866 $cfgRelation = PMA_getRelationsParam();
869 // Gets the list of fields properties
870 if (isset($result) && $result) {
871 $fields_meta = PMA_DBI_get_fields_meta($result);
872 $fields_cnt = count($fields_meta);
875 if (! $GLOBALS['is_ajax_request']) {
876 //begin the sqlqueryresults div here. container div
877 echo '<div id="sqlqueryresults"';
878 if ($GLOBALS['cfg']['AjaxEnable']) {
879 echo ' class="ajax"';
881 echo '>';
884 // Display previous update query (from tbl_replace)
885 if (isset($disp_query) && $cfg['ShowSQL'] == true) {
886 PMA_showMessage($disp_message, $disp_query, 'success');
889 if (isset($profiling_results)) {
890 // pma_token/url_query needed for chart export
892 <script type="text/javascript">
893 pma_token = '<?php echo $_SESSION[' PMA_token ']; ?>';
894 url_query = '<?php echo isset($url_query)?$url_query:PMA_generate_common_url($db);?>';
895 $(document).ready(makeProfilingChart);
896 </script>
897 <?php
898 echo '<fieldset><legend>' . __('Profiling') . '</legend>' . "\n";
899 echo '<div style="float: left;">';
900 echo '<table>' . "\n";
901 echo ' <tr>' . "\n";
902 echo ' <th>' . __('Status') . PMA_showMySQLDocu('general-thread-states', 'general-thread-states') . '</th>' . "\n";
903 echo ' <th>' . __('Time') . '</th>' . "\n";
904 echo ' </tr>' . "\n";
906 $chart_json = Array();
907 foreach ($profiling_results as $one_result) {
908 echo ' <tr>' . "\n";
909 echo '<td>' . ucwords($one_result['Status']) . '</td>' . "\n";
910 echo '<td align="right">' . (PMA_formatNumber($one_result['Duration'], 3, 1)) . 's</td>' . "\n";
911 $chart_json[ucwords($one_result['Status'])] = $one_result['Duration'];
914 echo '</table>' . "\n";
915 echo '</div>';
916 //require_once './libraries/chart.lib.php';
917 echo '<div id="profilingchart" style="display:none;">';
918 //PMA_chart_profiling($profiling_results);
919 echo json_encode($chart_json);
920 echo '</div>';
921 echo '</fieldset>' . "\n";
924 // Displays the results in a table
925 if (empty($disp_mode)) {
926 // see the "PMA_setDisplayMode()" function in
927 // libraries/display_tbl.lib.php
928 $disp_mode = 'urdr111101';
931 // hide edit and delete links for information_schema
932 if (PMA_is_system_schema($db)) {
933 $disp_mode = 'nnnn110111';
936 if (isset($label)) {
937 $message = PMA_message::success(__('Bookmark %s created'));
938 $message->addParam($label);
939 $message->display();
942 PMA_displayTable($result, $disp_mode, $analyzed_sql);
943 PMA_DBI_free_result($result);
945 // BEGIN INDEX CHECK See if indexes should be checked.
946 if (isset($query_type) && $query_type == 'check_tbl' && isset($selected) && is_array($selected)) {
947 foreach ($selected as $idx => $tbl_name) {
948 $check = PMA_Index::findDuplicates($tbl_name, $db);
949 if (! empty($check)) {
950 printf(__('Problems with indexes of table `%s`'), $tbl_name);
951 echo $check;
954 } // End INDEX CHECK
956 // Bookmark support if required
957 if ($disp_mode[7] == '1'
958 && (! empty($cfg['Bookmark']) && empty($id_bookmark))
959 && ! empty($sql_query)
961 echo "\n";
963 $goto = 'sql.php?'
964 . PMA_generate_common_url($db, $table)
965 . '&amp;sql_query=' . urlencode($sql_query)
966 . '&amp;id_bookmark=1';
969 <form action="sql.php" method="post" onsubmit="return emptyFormElements(this, 'fields[label]');">
970 <?php echo PMA_generate_common_hidden_inputs(); ?>
971 <input type="hidden" name="goto" value="<?php echo $goto; ?>" />
972 <input type="hidden" name="fields[dbase]" value="<?php echo htmlspecialchars($db); ?>" />
973 <input type="hidden" name="fields[user]" value="<?php echo $cfg['Bookmark']['user']; ?>" />
974 <input type="hidden" name="fields[query]" value="<?php echo urlencode(isset($complete_query) ? $complete_query : $sql_query); ?>" />
975 <fieldset>
976 <legend><?php
977 echo PMA_getIcon('b_bookmark.png', __('Bookmark this SQL query'), true);
979 </legend>
981 <div class="formelement">
982 <label for="fields_label_"><?php echo __('Label'); ?>:</label>
983 <input type="text" id="fields_label_" name="fields[label]" value="" />
984 </div>
986 <div class="formelement">
987 <input type="checkbox" name="bkm_all_users" id="bkm_all_users" value="true" />
988 <label for="bkm_all_users"><?php echo __('Let every user access this bookmark'); ?></label>
989 </div>
991 <div class="clearfloat"></div>
992 </fieldset>
993 <fieldset class="tblFooters">
994 <input type="submit" name="store_bkm" value="<?php echo __('Bookmark this SQL query'); ?>" />
995 </fieldset>
996 </form>
997 <?php
998 } // end bookmark support
1000 // Do print the page if required
1001 if (isset($printview) && $printview == '1') {
1002 PMA_printButton();
1003 } // end print case
1005 if ($GLOBALS['is_ajax_request'] != true) {
1006 echo '</div>'; // end sqlqueryresults div
1008 } // end rows returned
1011 * Displays the footer
1013 if (! isset($_REQUEST['table_maintenance'])) {
1014 include './libraries/footer.inc.php';