Translation update done using Pootle.
[phpmyadmin.git] / sql.php
blob42d72caae25ca59cf9cd009c7a7c32b23dce803d
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';
28 if (isset($_SESSION['profiling'])) {
29 $GLOBALS['js_include'][] = 'highcharts/highcharts.js';
30 /* Files required for chart exporting */
31 $GLOBALS['js_include'][] = 'highcharts/exporting.js';
32 /* < IE 9 doesn't support canvas natively */
33 if (PMA_USR_BROWSER_AGENT == 'IE' && PMA_USR_BROWSER_VER < 9) {
34 $GLOBALS['js_include'][] = 'canvg/flashcanvas.js';
36 $GLOBALS['js_include'][] = 'canvg/canvg.js';
39 /**
40 * Defines the url to return to in case of error in a sql statement
42 // Security checkings
43 if (! empty($goto)) {
44 $is_gotofile = preg_replace('@^([^?]+).*$@s', '\\1', $goto);
45 if (! @file_exists('./' . $is_gotofile)) {
46 unset($goto);
47 } else {
48 $is_gotofile = ($is_gotofile == $goto);
50 } else {
51 $goto = (! strlen($table)) ? $cfg['DefaultTabDatabase'] : $cfg['DefaultTabTable'];
52 $is_gotofile = true;
53 } // end if
55 if (! isset($err_url)) {
56 $err_url = (! empty($back) ? $back : $goto)
57 . '?' . PMA_generate_common_url($db)
58 . ((strpos(' ' . $goto, 'db_') != 1 && strlen($table)) ? '&amp;table=' . urlencode($table) : '');
59 } // end if
61 // Coming from a bookmark dialog
62 if (isset($fields['query'])) {
63 $sql_query = $fields['query'];
66 // This one is just to fill $db
67 if (isset($fields['dbase'])) {
68 $db = $fields['dbase'];
71 /**
72 * During grid edit, if we have a relational field, show the dropdown for it
74 * Logic taken from libraries/display_tbl_lib.php
76 * This doesn't seem to be the right place to do this, but I can't think of any
77 * better place either.
79 if (isset($_REQUEST['get_relational_values']) && $_REQUEST['get_relational_values'] == true) {
80 include_once 'libraries/relation.lib.php';
82 $column = $_REQUEST['column'];
83 $foreigners = PMA_getForeigners($db, $table, $column);
85 $display_field = PMA_getDisplayField($foreigners[$column]['foreign_db'], $foreigners[$column]['foreign_table']);
87 $foreignData = PMA_getForeignData($foreigners, $column, false, '', '');
89 if ($_SESSION['tmp_user_values']['relational_display'] == 'D'
90 && isset($display_field)
91 && strlen($display_field)
92 && isset($_REQUEST['relation_key_or_display_column'])
93 && $_REQUEST['relation_key_or_display_column']
94 ) {
95 $curr_value = $_REQUEST['relation_key_or_display_column'];
96 } else {
97 $curr_value = $_REQUEST['curr_value'];
99 if ($foreignData['disp_row'] == null) {
100 //Handle the case when number of values is more than $cfg['ForeignKeyMaxLimit']
101 $_url_params = array(
102 'db' => $db,
103 'table' => $table,
104 'field' => $column
107 $dropdown = '<span class="curr_value">' . htmlspecialchars($_REQUEST['curr_value']) . '</span> <a href="browse_foreigners.php' . PMA_generate_common_url($_url_params) . '"'
108 . ' target="_blank" class="browse_foreign" '
109 .'>' . __('Browse foreign values') . '</a>';
110 } else {
111 $dropdown = PMA_foreignDropdown($foreignData['disp_row'], $foreignData['foreign_field'], $foreignData['foreign_display'], $curr_value, $cfg['ForeignKeyMaxLimit']);
112 $dropdown = '<select>' . $dropdown . '</select>';
115 $extra_data['dropdown'] = $dropdown;
116 PMA_ajaxResponse(null, true, $extra_data);
120 * Just like above, find possible values for enum fields during grid edit.
122 * Logic taken from libraries/display_tbl_lib.php
124 if (isset($_REQUEST['get_enum_values']) && $_REQUEST['get_enum_values'] == true) {
125 $field_info_query = PMA_DBI_get_columns_sql($db, $table, $_REQUEST['column']);
127 $field_info_result = PMA_DBI_fetch_result($field_info_query, null, null, null, PMA_DBI_QUERY_STORE);
129 $search = array('enum', '(', ')', "'");
131 $values = explode(',', str_replace($search, '', $field_info_result[0]['Type']));
133 $dropdown = '<option value="">&nbsp;</option>';
134 foreach ($values as $value) {
135 $dropdown .= '<option value="' . htmlspecialchars($value) . '"';
136 if ($value == $_REQUEST['curr_value']) {
137 $dropdown .= ' selected="selected"';
139 $dropdown .= '>' . $value . '</option>';
142 $dropdown = '<select>' . $dropdown . '</select>';
144 $extra_data['dropdown'] = $dropdown;
145 PMA_ajaxResponse(null, true, $extra_data);
149 * Find possible values for set fields during grid edit.
151 if (isset($_REQUEST['get_set_values']) && $_REQUEST['get_set_values'] == true) {
152 $field_info_query = PMA_DBI_get_columns_sql($db, $table, $_REQUEST['column']);
154 $field_info_result = PMA_DBI_fetch_result($field_info_query, null, null, null, PMA_DBI_QUERY_STORE);
156 $selected_values = explode(',', $_REQUEST['curr_value']);
158 $search = array('set', '(', ')', "'");
159 $values = explode(',', str_replace($search, '', $field_info_result[0]['Type']));
161 $select = '';
162 foreach ($values as $value) {
163 $select .= '<option value="' . htmlspecialchars($value) . '"';
164 if (in_array($value, $selected_values, true)) {
165 $select .= ' selected="selected"';
167 $select .= '>' . $value . '</option>';
170 $select_size = (sizeof($values) > 10) ? 10 : sizeof($values);
171 $select = '<select multiple="multiple" size="' . $select_size . '">' . $select . '</select>';
173 $extra_data['select'] = $select;
174 PMA_ajaxResponse(null, true, $extra_data);
178 * Check ajax request to set the column order
180 if (isset($_REQUEST['set_col_prefs']) && $_REQUEST['set_col_prefs'] == true) {
181 $pmatable = new PMA_Table($table, $db);
182 $retval = false;
184 // set column order
185 if (isset($_REQUEST['col_order'])) {
186 $col_order = explode(',', $_REQUEST['col_order']);
187 $retval = $pmatable->setUiProp(PMA_Table::PROP_COLUMN_ORDER, $col_order, $_REQUEST['table_create_time']);
188 if (gettype($retval) != 'boolean') {
189 PMA_ajaxResponse($retval->getString(), false);
193 // set column visibility
194 if ($retval === true && isset($_REQUEST['col_visib'])) {
195 $col_visib = explode(',', $_REQUEST['col_visib']);
196 $retval = $pmatable->setUiProp(PMA_Table::PROP_COLUMN_VISIB, $col_visib, $_REQUEST['table_create_time']);
197 if (gettype($retval) != 'boolean') {
198 PMA_ajaxResponse($retval->getString(), false);
202 PMA_ajaxResponse(null, ($retval == true));
205 // Default to browse if no query set and we have table
206 // (needed for browsing from DefaultTabTable)
207 if (empty($sql_query) && strlen($table) && strlen($db)) {
208 include_once './libraries/bookmark.lib.php';
209 $book_sql_query = PMA_Bookmark_get(
210 $db,
211 '\'' . PMA_sqlAddSlashes($table) . '\'',
212 'label',
213 false,
214 true
217 if (! empty($book_sql_query)) {
218 $GLOBALS['using_bookmark_message'] = PMA_message::notice(__('Using bookmark "%s" as default browse query.'));
219 $GLOBALS['using_bookmark_message']->addParam($table);
220 $GLOBALS['using_bookmark_message']->addMessage(PMA_showDocu('faq6_22'));
221 $sql_query = $book_sql_query;
222 } else {
223 $sql_query = 'SELECT * FROM ' . PMA_backquote($table);
225 unset($book_sql_query);
227 // set $goto to what will be displayed if query returns 0 rows
228 $goto = 'tbl_structure.php';
229 } else {
230 // Now we can check the parameters
231 PMA_checkParameters(array('sql_query'));
234 // instead of doing the test twice
235 $is_drop_database = preg_match(
236 '/DROP[[:space:]]+(DATABASE|SCHEMA)[[:space:]]+/i',
237 $sql_query
241 * Check rights in case of DROP DATABASE
243 * This test may be bypassed if $is_js_confirmed = 1 (already checked with js)
244 * but since a malicious user may pass this variable by url/form, we don't take
245 * into account this case.
247 if (! defined('PMA_CHK_DROP')
248 && ! $cfg['AllowUserDropDatabase']
249 && $is_drop_database
250 && ! $is_superuser
252 include_once './libraries/header.inc.php';
253 PMA_mysqlDie(__('"DROP DATABASE" statements are disabled.'), '', '', $err_url);
254 } // end if
256 require_once './libraries/display_tbl.lib.php';
257 PMA_displayTable_checkConfigParams();
260 * Need to find the real end of rows?
262 if (isset($find_real_end) && $find_real_end) {
263 $unlim_num_rows = PMA_Table::countRecords($db, $table, $force_exact = true);
264 $_SESSION['tmp_user_values']['pos'] = @((ceil($unlim_num_rows / $_SESSION['tmp_user_values']['max_rows']) - 1) * $_SESSION['tmp_user_values']['max_rows']);
269 * Bookmark add
271 if (isset($store_bkm)) {
272 PMA_Bookmark_save($fields, (isset($bkm_all_users) && $bkm_all_users == 'true' ? true : false));
273 // go back to sql.php to redisplay query; do not use &amp; in this case:
274 PMA_sendHeaderLocation($cfg['PmaAbsoluteUri'] . $goto . '&label=' . $fields['label']);
275 } // end if
278 * Parse and analyze the query
280 require_once './libraries/parse_analyze.lib.php';
283 * Sets or modifies the $goto variable if required
285 if ($goto == 'sql.php') {
286 $is_gotofile = false;
287 $goto = 'sql.php?'
288 . PMA_generate_common_url($db, $table)
289 . '&amp;sql_query=' . urlencode($sql_query);
290 } // end if
294 * Go back to further page if table should not be dropped
296 if (isset($btnDrop) && $btnDrop == __('No')) {
297 if (! empty($back)) {
298 $goto = $back;
300 if ($is_gotofile) {
301 if (strpos($goto, 'db_') === 0 && strlen($table)) {
302 $table = '';
304 $active_page = $goto;
305 include './' . PMA_securePath($goto);
306 } else {
307 PMA_sendHeaderLocation($cfg['PmaAbsoluteUri'] . str_replace('&amp;', '&', $goto));
309 exit();
310 } // end if
314 * Displays the confirm page if required
316 * This part of the script is bypassed if $is_js_confirmed = 1 (already checked
317 * with js) because possible security issue is not so important here: at most,
318 * the confirm message isn't displayed.
320 * Also bypassed if only showing php code.or validating a SQL query
322 if (! $cfg['Confirm']
323 || isset($_REQUEST['is_js_confirmed'])
324 || isset($btnDrop)
325 // if we are coming from a "Create PHP code" or a "Without PHP Code"
326 // dialog, we won't execute the query anyway, so don't confirm
327 || isset($GLOBALS['show_as_php'])
328 || ! empty($GLOBALS['validatequery'])
330 $do_confirm = false;
331 } else {
332 $do_confirm = isset($analyzed_sql[0]['queryflags']['need_confirm']);
335 if ($do_confirm) {
336 $stripped_sql_query = $sql_query;
337 include_once './libraries/header.inc.php';
338 if ($is_drop_database) {
339 echo '<h1 class="error">' . __('You are about to DESTROY a complete database!') . '</h1>';
341 echo '<form action="sql.php" method="post">' . "\n"
342 .PMA_generate_common_hidden_inputs($db, $table);
344 <input type="hidden" name="sql_query" value="<?php echo htmlspecialchars($sql_query); ?>" />
345 <input type="hidden" name="message_to_show" value="<?php echo isset($message_to_show) ? PMA_sanitize($message_to_show, true) : ''; ?>" />
346 <input type="hidden" name="goto" value="<?php echo $goto; ?>" />
347 <input type="hidden" name="back" value="<?php echo isset($back) ? PMA_sanitize($back, true) : ''; ?>" />
348 <input type="hidden" name="reload" value="<?php echo isset($reload) ? PMA_sanitize($reload, true) : 0; ?>" />
349 <input type="hidden" name="purge" value="<?php echo isset($purge) ? PMA_sanitize($purge, true) : ''; ?>" />
350 <input type="hidden" name="dropped_column" value="<?php echo isset($dropped_column) ? PMA_sanitize($dropped_column, true) : ''; ?>" />
351 <input type="hidden" name="show_query" value="<?php echo isset($show_query) ? PMA_sanitize($show_query, true) : ''; ?>" />
352 <?php
353 echo '<fieldset class="confirmation">' . "\n"
354 .' <legend>' . __('Do you really want to ') . '</legend>'
355 .' <tt>' . htmlspecialchars($stripped_sql_query) . '</tt>' . "\n"
356 .'</fieldset>' . "\n"
357 .'<fieldset class="tblFooters">' . "\n";
359 <input type="submit" name="btnDrop" value="<?php echo __('Yes'); ?>" id="buttonYes" />
360 <input type="submit" name="btnDrop" value="<?php echo __('No'); ?>" id="buttonNo" />
361 <?php
362 echo '</fieldset>' . "\n"
363 . '</form>' . "\n";
366 * Displays the footer and exit
368 include './libraries/footer.inc.php';
369 } // end if $do_confirm
372 // Defines some variables
373 // A table has to be created, renamed, dropped -> navi frame should be reloaded
375 * @todo use the parser/analyzer
378 if (empty($reload)
379 && preg_match('/^(CREATE|ALTER|DROP)\s+(VIEW|TABLE|DATABASE|SCHEMA)\s+/i', $sql_query)
381 $reload = 1;
384 // SK -- Patch: $is_group added for use in calculation of total number of
385 // rows.
386 // $is_count is changed for more correct "LIMIT" clause
387 // appending in queries like
388 // "SELECT COUNT(...) FROM ... GROUP BY ..."
391 * @todo detect all this with the parser, to avoid problems finding
392 * those strings in comments or backquoted identifiers
395 $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;
396 if ($is_select) { // see line 141
397 $is_group = preg_match('@(GROUP[[:space:]]+BY|HAVING|SELECT[[:space:]]+DISTINCT)[[:space:]]+@i', $sql_query);
398 $is_func = ! $is_group && (preg_match('@[[:space:]]+(SUM|AVG|STD|STDDEV|MIN|MAX|BIT_OR|BIT_AND)\s*\(@i', $sql_query));
399 $is_count = ! $is_group && (preg_match('@^SELECT[[:space:]]+COUNT\((.*\.+)?.*\)@i', $sql_query));
400 $is_export = (preg_match('@[[:space:]]+INTO[[:space:]]+OUTFILE[[:space:]]+@i', $sql_query));
401 $is_analyse = (preg_match('@[[:space:]]+PROCEDURE[[:space:]]+ANALYSE@i', $sql_query));
402 } elseif (preg_match('@^EXPLAIN[[:space:]]+@i', $sql_query)) {
403 $is_explain = true;
404 } elseif (preg_match('@^DELETE[[:space:]]+@i', $sql_query)) {
405 $is_delete = true;
406 $is_affected = true;
407 } elseif (preg_match('@^(INSERT|LOAD[[:space:]]+DATA|REPLACE)[[:space:]]+@i', $sql_query)) {
408 $is_insert = true;
409 $is_affected = true;
410 if (preg_match('@^(REPLACE)[[:space:]]+@i', $sql_query)) {
411 $is_replace = true;
413 } elseif (preg_match('@^UPDATE[[:space:]]+@i', $sql_query)) {
414 $is_affected = true;
415 } elseif (preg_match('@^[[:space:]]*SHOW[[:space:]]+@i', $sql_query)) {
416 $is_show = true;
417 } elseif (preg_match('@^(CHECK|ANALYZE|REPAIR|OPTIMIZE)[[:space:]]+TABLE[[:space:]]+@i', $sql_query)) {
418 $is_maint = true;
421 // assign default full_sql_query
422 $full_sql_query = $sql_query;
424 // Handle remembered sorting order, only for single table query
425 if ($GLOBALS['cfg']['RememberSorting']
426 && ! ($is_count || $is_export || $is_func || $is_analyse)
427 && count($analyzed_sql[0]['select_expr']) == 0
428 && isset($analyzed_sql[0]['queryflags']['select_from'])
429 && count($analyzed_sql[0]['table_ref']) == 1
431 $pmatable = new PMA_Table($table, $db);
432 if (empty($analyzed_sql[0]['order_by_clause'])) {
433 $sorted_col = $pmatable->getUiProp(PMA_Table::PROP_SORTED_COLUMN);
434 if ($sorted_col) {
435 // retrieve the remembered sorting order for current table
436 $sql_order_to_append = ' ORDER BY ' . $sorted_col . ' ';
437 $full_sql_query = $analyzed_sql[0]['section_before_limit'] . $sql_order_to_append
438 . $analyzed_sql[0]['section_after_limit'];
440 // update the $analyzed_sql
441 $analyzed_sql[0]['section_before_limit'] .= $sql_order_to_append;
442 $analyzed_sql[0]['order_by_clause'] = $sorted_col;
444 } else {
445 // store the remembered table into session
446 $pmatable->setUiProp(PMA_Table::PROP_SORTED_COLUMN, $analyzed_sql[0]['order_by_clause']);
450 // Do append a "LIMIT" clause?
451 if (($_SESSION['tmp_user_values']['max_rows'] != 'all')
452 && ! ($is_count || $is_export || $is_func || $is_analyse)
453 && isset($analyzed_sql[0]['queryflags']['select_from'])
454 && ! isset($analyzed_sql[0]['queryflags']['offset'])
455 && empty($analyzed_sql[0]['limit_clause'])
457 $sql_limit_to_append = ' LIMIT ' . $_SESSION['tmp_user_values']['pos']
458 . ', ' . $_SESSION['tmp_user_values']['max_rows'] . " ";
460 $full_sql_query = $analyzed_sql[0]['section_before_limit'] . "\n"
461 . $sql_limit_to_append . $analyzed_sql[0]['section_after_limit'];
463 * @todo pretty printing of this modified query
465 if (isset($display_query)) {
466 // if the analysis of the original query revealed that we found
467 // a section_after_limit, we now have to analyze $display_query
468 // to display it correctly
470 if (! empty($analyzed_sql[0]['section_after_limit'])
471 && trim($analyzed_sql[0]['section_after_limit']) != ';'
473 $analyzed_display_query = PMA_SQP_analyze(PMA_SQP_parse($display_query));
474 $display_query = $analyzed_display_query[0]['section_before_limit']
475 . "\n" . $sql_limit_to_append . $analyzed_display_query[0]['section_after_limit'];
481 if (strlen($db)) {
482 PMA_DBI_select_db($db);
485 // E x e c u t e t h e q u e r y
487 // Only if we didn't ask to see the php code (mikebeck)
488 if (isset($GLOBALS['show_as_php']) || ! empty($GLOBALS['validatequery'])) {
489 unset($result);
490 $num_rows = 0;
491 $unlim_num_rows = 0;
492 } else {
493 if (isset($_SESSION['profiling']) && PMA_profilingSupported()) {
494 PMA_DBI_query('SET PROFILING=1;');
497 // Measure query time.
498 $querytime_before = array_sum(explode(' ', microtime()));
500 $result = @PMA_DBI_try_query($full_sql_query, null, PMA_DBI_QUERY_STORE);
502 // If a stored procedure was called, there may be more results that are
503 // queued up and waiting to be flushed from the buffer. So let's do that.
504 while (true) {
505 if (! PMA_DBI_more_results()) {
506 break;
508 PMA_DBI_next_result();
511 $querytime_after = array_sum(explode(' ', microtime()));
513 $GLOBALS['querytime'] = $querytime_after - $querytime_before;
515 // Displays an error message if required and stop parsing the script
516 if ($error = PMA_DBI_getError()) {
517 if ($is_gotofile) {
518 if (strpos($goto, 'db_') === 0 && strlen($table)) {
519 $table = '';
521 $active_page = $goto;
522 $message = PMA_Message::rawError($error);
524 if ($GLOBALS['is_ajax_request'] == true) {
525 PMA_ajaxResponse($message, false);
529 * Go to target path.
531 include './' . PMA_securePath($goto);
532 } else {
533 $full_err_url = (preg_match('@^(db|tbl)_@', $err_url))
534 ? $err_url . '&amp;show_query=1&amp;sql_query=' . urlencode($sql_query)
535 : $err_url;
536 PMA_mysqlDie($error, $full_sql_query, '', $full_err_url);
538 exit;
540 unset($error);
542 // Gets the number of rows affected/returned
543 // (This must be done immediately after the query because
544 // mysql_affected_rows() reports about the last query done)
546 if (! $is_affected) {
547 $num_rows = ($result) ? @PMA_DBI_num_rows($result) : 0;
548 } elseif (! isset($num_rows)) {
549 $num_rows = @PMA_DBI_affected_rows();
552 // Grabs the profiling results
553 if (isset($_SESSION['profiling']) && PMA_profilingSupported()) {
554 $profiling_results = PMA_DBI_fetch_result('SHOW PROFILE;');
557 // Checks if the current database has changed
558 // This could happen if the user sends a query like "USE `database`;"
560 * commented out auto-switching to active database - really required?
561 * bug #1814718 win: table list disappears (mixed case db names)
562 * https://sourceforge.net/support/tracker.php?aid=1814718
563 * @todo RELEASE test and comit or rollback before release
564 $current_db = PMA_DBI_fetch_value('SELECT DATABASE()');
565 if ($db !== $current_db) {
566 $db = $current_db;
567 $reload = 1;
569 unset($current_db);
572 // tmpfile remove after convert encoding appended by Y.Kawada
573 if (function_exists('PMA_kanji_file_conv')
574 && (isset($textfile) && file_exists($textfile))
576 unlink($textfile);
579 // Counts the total number of rows for the same 'SELECT' query without the
580 // 'LIMIT' clause that may have been programatically added
582 if (empty($sql_limit_to_append)) {
583 $unlim_num_rows = $num_rows;
584 // if we did not append a limit, set this to get a correct
585 // "Showing rows..." message
586 //$_SESSION['tmp_user_values']['max_rows'] = 'all';
587 } elseif ($is_select) {
589 // c o u n t q u e r y
591 // If we are "just browsing", there is only one table,
592 // and no WHERE clause (or just 'WHERE 1 '),
593 // we do a quick count (which uses MaxExactCount) because
594 // SQL_CALC_FOUND_ROWS is not quick on large InnoDB tables
596 // However, do not count again if we did it previously
597 // due to $find_real_end == true
599 if (! $is_group
600 && ! isset($analyzed_sql[0]['queryflags']['union'])
601 && ! isset($analyzed_sql[0]['queryflags']['distinct'])
602 && ! isset($analyzed_sql[0]['table_ref'][1]['table_name'])
603 && (empty($analyzed_sql[0]['where_clause']) || $analyzed_sql[0]['where_clause'] == '1 ')
604 && ! isset($find_real_end)
607 // "j u s t b r o w s i n g"
608 $unlim_num_rows = PMA_Table::countRecords($db, $table);
610 } else { // n o t " j u s t b r o w s i n g "
612 // add select expression after the SQL_CALC_FOUND_ROWS
614 // for UNION, just adding SQL_CALC_FOUND_ROWS
615 // after the first SELECT works.
617 // take the left part, could be:
618 // SELECT
619 // (SELECT
620 $count_query = PMA_SQP_formatHtml($parsed_sql, 'query_only', 0, $analyzed_sql[0]['position_of_first_select'] + 1);
621 $count_query .= ' SQL_CALC_FOUND_ROWS ';
622 // add everything that was after the first SELECT
623 $count_query .= PMA_SQP_formatHtml($parsed_sql, 'query_only', $analyzed_sql[0]['position_of_first_select'] + 1);
624 // ensure there is no semicolon at the end of the
625 // count query because we'll probably add
626 // a LIMIT 1 clause after it
627 $count_query = rtrim($count_query);
628 $count_query = rtrim($count_query, ';');
630 // if using SQL_CALC_FOUND_ROWS, add a LIMIT to avoid
631 // long delays. Returned count will be complete anyway.
632 // (but a LIMIT would disrupt results in an UNION)
634 if (! isset($analyzed_sql[0]['queryflags']['union'])) {
635 $count_query .= ' LIMIT 1';
638 // run the count query
640 PMA_DBI_try_query($count_query);
641 // if (mysql_error()) {
642 // void.
643 // I tried the case
644 // (SELECT `User`, `Host`, `Db`, `Select_priv` FROM `db`)
645 // UNION (SELECT `User`, `Host`, "%" AS "Db",
646 // `Select_priv`
647 // FROM `user`) ORDER BY `User`, `Host`, `Db`;
648 // and although the generated count_query is wrong
649 // the SELECT FOUND_ROWS() work! (maybe it gets the
650 // count from the latest query that worked)
652 // another case where the count_query is wrong:
653 // SELECT COUNT(*), f1 from t1 group by f1
654 // and you click to sort on count(*)
655 // }
656 $unlim_num_rows = PMA_DBI_fetch_value('SELECT FOUND_ROWS()');
657 } // end else "just browsing"
659 } else { // not $is_select
660 $unlim_num_rows = 0;
661 } // end rows total count
663 // if a table or database gets dropped, check column comments.
664 if (isset($purge) && $purge == '1') {
666 * Cleanup relations.
668 include_once './libraries/relation_cleanup.lib.php';
670 if (strlen($table) && strlen($db)) {
671 PMA_relationsCleanupTable($db, $table);
672 } elseif (strlen($db)) {
673 PMA_relationsCleanupDatabase($db);
674 } else {
675 // VOID. No DB/Table gets deleted.
676 } // end if relation-stuff
677 } // end if ($purge)
679 // If a column gets dropped, do relation magic.
680 if (isset($dropped_column) && strlen($db) && strlen($table) && ! empty($dropped_column)) {
681 include_once './libraries/relation_cleanup.lib.php';
682 PMA_relationsCleanupColumn($db, $table, $dropped_column);
683 // to refresh the list of indexes (Ajax mode)
684 $extra_data['indexes_list'] = PMA_Index::getView($table, $db);
685 } // end if column was dropped
686 } // end else "didn't ask to see php code"
688 // No rows returned -> move back to the calling page
689 if ((0 == $num_rows && 0 == $unlim_num_rows) || $is_affected) {
690 if ($is_delete) {
691 $message = PMA_Message::deleted_rows($num_rows);
692 } elseif ($is_insert) {
693 if ($is_replace) {
694 /* For replace we get DELETED + INSERTED row count, so we have to call it affected */
695 $message = PMA_Message::affected_rows($num_rows);
696 } else {
697 $message = PMA_Message::inserted_rows($num_rows);
699 $insert_id = PMA_DBI_insert_id();
700 if ($insert_id != 0) {
701 // insert_id is id of FIRST record inserted in one insert, so if we inserted multiple rows, we had to increment this
702 $message->addMessage('[br]');
703 // need to use a temporary because the Message class
704 // currently supports adding parameters only to the first
705 // message
706 $_inserted = PMA_Message::notice(__('Inserted row id: %1$d'));
707 $_inserted->addParam($insert_id + $num_rows - 1);
708 $message->addMessage($_inserted);
710 } elseif ($is_affected) {
711 $message = PMA_Message::affected_rows($num_rows);
713 // Ok, here is an explanation for the !$is_select.
714 // The form generated by sql_query_form.lib.php
715 // and db_sql.php has many submit buttons
716 // on the same form, and some confusion arises from the
717 // fact that $message_to_show is sent for every case.
718 // The $message_to_show containing a success message and sent with
719 // the form should not have priority over errors
720 } elseif (! empty($message_to_show) && ! $is_select) {
721 $message = PMA_Message::rawSuccess(htmlspecialchars($message_to_show));
722 } elseif (! empty($GLOBALS['show_as_php'])) {
723 $message = PMA_Message::success(__('Showing as PHP code'));
724 } elseif (isset($GLOBALS['show_as_php'])) {
725 /* User disable showing as PHP, query is only displayed */
726 $message = PMA_Message::notice(__('Showing SQL query'));
727 } elseif (! empty($GLOBALS['validatequery'])) {
728 $message = PMA_Message::notice(__('Validated SQL'));
729 } else {
730 $message = PMA_Message::success(__('MySQL returned an empty result set (i.e. zero rows).'));
733 if (isset($GLOBALS['querytime'])) {
734 $_querytime = PMA_Message::notice(__('Query took %01.4f sec'));
735 $_querytime->addParam($GLOBALS['querytime']);
736 $message->addMessage('(');
737 $message->addMessage($_querytime);
738 $message->addMessage(')');
741 if ($GLOBALS['is_ajax_request'] == true) {
742 if ($cfg['ShowSQL']) {
743 $extra_data['sql_query'] = PMA_showMessage($message, $GLOBALS['sql_query'], 'success');
745 if (isset($GLOBALS['reload']) && $GLOBALS['reload'] == 1) {
746 $extra_data['reload'] = 1;
747 $extra_data['db'] = $GLOBALS['db'];
749 PMA_ajaxResponse($message, $message->isSuccess(), (isset($extra_data) ? $extra_data : ''));
752 if ($is_gotofile) {
753 $goto = PMA_securePath($goto);
754 // Checks for a valid target script
755 $is_db = $is_table = false;
756 if (isset($_REQUEST['purge']) && $_REQUEST['purge'] == '1') {
757 $table = '';
758 unset($url_params['table']);
760 include 'libraries/db_table_exists.lib.php';
762 if (strpos($goto, 'tbl_') === 0 && ! $is_table) {
763 if (strlen($table)) {
764 $table = '';
766 $goto = 'db_sql.php';
768 if (strpos($goto, 'db_') === 0 && ! $is_db) {
769 if (strlen($db)) {
770 $db = '';
772 $goto = 'main.php';
774 // Loads to target script
775 if ($goto != 'main.php') {
776 include_once './libraries/header.inc.php';
778 $active_page = $goto;
779 include './' . $goto;
780 } else {
781 // avoid a redirect loop when last record was deleted
782 if (0 == $num_rows && 'sql.php' == $cfg['DefaultTabTable']) {
783 $goto = str_replace('sql.php', 'tbl_structure.php', $goto);
785 PMA_sendHeaderLocation($cfg['PmaAbsoluteUri'] . str_replace('&amp;', '&', $goto) . '&message=' . urlencode($message));
786 } // end else
787 exit();
788 // end no rows returned
789 } else {
790 // At least one row is returned -> displays a table with results
791 //If we are retrieving the full value of a truncated field or the original
792 // value of a transformed field, show it here and exit
793 if ($GLOBALS['grid_edit'] == true && $GLOBALS['cfg']['AjaxEnable']) {
794 $row = PMA_DBI_fetch_row($result);
795 $extra_data = array();
796 $extra_data['value'] = $row[0];
797 PMA_ajaxResponse(null, true, $extra_data);
800 if (isset($_REQUEST['ajax_request']) && isset($_REQUEST['table_maintenance'])) {
801 $GLOBALS['js_include'][] = 'functions.js';
802 $GLOBALS['js_include'][] = 'makegrid.js';
803 $GLOBALS['js_include'][] = 'sql.js';
805 // Gets the list of fields properties
806 if (isset($result) && $result) {
807 $fields_meta = PMA_DBI_get_fields_meta($result);
808 $fields_cnt = count($fields_meta);
811 if (empty($disp_mode)) {
812 // see the "PMA_setDisplayMode()" function in
813 // libraries/display_tbl.lib.php
814 $disp_mode = 'urdr111101';
817 // hide edit and delete links for information_schema
818 if (PMA_is_system_schema($db)) {
819 $disp_mode = 'nnnn110111';
822 $message = PMA_Message::success($message);
823 echo PMA_showMessage($message, $GLOBALS['sql_query'], 'success');
824 PMA_displayTable($result, $disp_mode, $analyzed_sql);
825 exit();
828 // Displays the headers
829 if (isset($show_query)) {
830 unset($show_query);
832 if (isset($printview) && $printview == '1') {
833 include_once './libraries/header_printview.inc.php';
834 } else {
836 $GLOBALS['js_include'][] = 'functions.js';
837 $GLOBALS['js_include'][] = 'makegrid.js';
838 $GLOBALS['js_include'][] = 'sql.js';
840 unset($message);
842 if (! $GLOBALS['is_ajax_request'] || ! $GLOBALS['cfg']['AjaxEnable']) {
843 if (strlen($table)) {
844 include './libraries/tbl_common.php';
845 $url_query .= '&amp;goto=tbl_sql.php&amp;back=tbl_sql.php';
846 include './libraries/tbl_info.inc.php';
847 include './libraries/tbl_links.inc.php';
848 } elseif (strlen($db)) {
849 include './libraries/db_common.inc.php';
850 include './libraries/db_info.inc.php';
851 } else {
852 include './libraries/server_common.inc.php';
853 include './libraries/server_links.inc.php';
855 } else {
856 include_once './libraries/header.inc.php';
857 //we don't need to buffer the output in PMA_showMessage here.
858 //set a global variable and check against it in the function
859 $GLOBALS['buffer_message'] = false;
863 if (strlen($db)) {
864 $cfgRelation = PMA_getRelationsParam();
867 // Gets the list of fields properties
868 if (isset($result) && $result) {
869 $fields_meta = PMA_DBI_get_fields_meta($result);
870 $fields_cnt = count($fields_meta);
873 if (! $GLOBALS['is_ajax_request']) {
874 //begin the sqlqueryresults div here. container div
875 echo '<div id="sqlqueryresults"';
876 if ($GLOBALS['cfg']['AjaxEnable']) {
877 echo ' class="ajax"';
879 echo '>';
882 // Display previous update query (from tbl_replace)
883 if (isset($disp_query) && $cfg['ShowSQL'] == true) {
884 PMA_showMessage($disp_message, $disp_query, 'success');
887 if (isset($profiling_results)) {
888 // pma_token/url_query needed for chart export
890 <script type="text/javascript">
891 pma_token = '<?php echo $_SESSION[' PMA_token ']; ?>';
892 url_query = '<?php echo isset($url_query)?$url_query:PMA_generate_common_url($db);?>';
893 $(document).ready(makeProfilingChart);
894 </script>
895 <?php
896 echo '<fieldset><legend>' . __('Profiling') . '</legend>' . "\n";
897 echo '<div style="float: left;">';
898 echo '<table>' . "\n";
899 echo ' <tr>' . "\n";
900 echo ' <th>' . __('Status') . PMA_showMySQLDocu('general-thread-states', 'general-thread-states') . '</th>' . "\n";
901 echo ' <th>' . __('Time') . '</th>' . "\n";
902 echo ' </tr>' . "\n";
904 $chart_json = Array();
905 foreach ($profiling_results as $one_result) {
906 echo ' <tr>' . "\n";
907 echo '<td>' . ucwords($one_result['Status']) . '</td>' . "\n";
908 echo '<td align="right">' . (PMA_formatNumber($one_result['Duration'], 3, 1)) . 's</td>' . "\n";
909 $chart_json[ucwords($one_result['Status'])] = $one_result['Duration'];
912 echo '</table>' . "\n";
913 echo '</div>';
914 //require_once './libraries/chart.lib.php';
915 echo '<div id="profilingchart" style="display:none;">';
916 //PMA_chart_profiling($profiling_results);
917 echo json_encode($chart_json);
918 echo '</div>';
919 echo '</fieldset>' . "\n";
922 // Displays the results in a table
923 if (empty($disp_mode)) {
924 // see the "PMA_setDisplayMode()" function in
925 // libraries/display_tbl.lib.php
926 $disp_mode = 'urdr111101';
929 // hide edit and delete links for information_schema
930 if (PMA_is_system_schema($db)) {
931 $disp_mode = 'nnnn110111';
934 if (isset($label)) {
935 $message = PMA_message::success(__('Bookmark %s created'));
936 $message->addParam($label);
937 $message->display();
940 PMA_displayTable($result, $disp_mode, $analyzed_sql);
941 PMA_DBI_free_result($result);
943 // BEGIN INDEX CHECK See if indexes should be checked.
944 if (isset($query_type) && $query_type == 'check_tbl' && isset($selected) && is_array($selected)) {
945 foreach ($selected as $idx => $tbl_name) {
946 $check = PMA_Index::findDuplicates($tbl_name, $db);
947 if (! empty($check)) {
948 printf(__('Problems with indexes of table `%s`'), $tbl_name);
949 echo $check;
952 } // End INDEX CHECK
954 // Bookmark support if required
955 if ($disp_mode[7] == '1'
956 && (! empty($cfg['Bookmark']) && empty($id_bookmark))
957 && ! empty($sql_query)
959 echo "\n";
961 $goto = 'sql.php?'
962 . PMA_generate_common_url($db, $table)
963 . '&amp;sql_query=' . urlencode($sql_query)
964 . '&amp;id_bookmark=1';
967 <form action="sql.php" method="post" onsubmit="return emptyFormElements(this, 'fields[label]');">
968 <?php echo PMA_generate_common_hidden_inputs(); ?>
969 <input type="hidden" name="goto" value="<?php echo $goto; ?>" />
970 <input type="hidden" name="fields[dbase]" value="<?php echo htmlspecialchars($db); ?>" />
971 <input type="hidden" name="fields[user]" value="<?php echo $cfg['Bookmark']['user']; ?>" />
972 <input type="hidden" name="fields[query]" value="<?php echo urlencode(isset($complete_query) ? $complete_query : $sql_query); ?>" />
973 <fieldset>
974 <legend><?php
975 echo PMA_getIcon('b_bookmark.png', __('Bookmark this SQL query'), true);
977 </legend>
979 <div class="formelement">
980 <label for="fields_label_"><?php echo __('Label'); ?>:</label>
981 <input type="text" id="fields_label_" name="fields[label]" value="" />
982 </div>
984 <div class="formelement">
985 <input type="checkbox" name="bkm_all_users" id="bkm_all_users" value="true" />
986 <label for="bkm_all_users"><?php echo __('Let every user access this bookmark'); ?></label>
987 </div>
989 <div class="clearfloat"></div>
990 </fieldset>
991 <fieldset class="tblFooters">
992 <input type="submit" name="store_bkm" value="<?php echo __('Bookmark this SQL query'); ?>" />
993 </fieldset>
994 </form>
995 <?php
996 } // end bookmark support
998 // Do print the page if required
999 if (isset($printview) && $printview == '1') {
1000 PMA_printButton();
1001 } // end print case
1003 if ($GLOBALS['is_ajax_request'] != true) {
1004 echo '</div>'; // end sqlqueryresults div
1006 } // end rows returned
1009 * Displays the footer
1011 if (! isset($_REQUEST['table_maintenance'])) {
1012 include './libraries/footer.inc.php';