Translation update done using Pootle.
[phpmyadmin.git] / sql.php
blob41d4504909dbdd37eb50a9df02dc7999dcf2e95e
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.custom.js';
18 $GLOBALS['js_include'][] = 'jquery/timepicker.js';
19 $GLOBALS['js_include'][] = 'tbl_change.js';
20 $GLOBALS['js_include'][] = 'gis_data_editor.js';
22 if (isset($_SESSION['profiling'])) {
23 $GLOBALS['js_include'][] = 'highcharts/highcharts.js';
24 /* Files required for chart exporting */
25 $GLOBALS['js_include'][] = 'highcharts/exporting.js';
26 /* < IE 9 doesn't support canvas natively */
27 if (PMA_USR_BROWSER_AGENT == 'IE' && PMA_USR_BROWSER_VER < 9) {
28 $GLOBALS['js_include'][] = 'canvg/flashcanvas.js';
30 $GLOBALS['js_include'][] = 'canvg/canvg.js';
33 /**
34 * Defines the url to return to in case of error in a sql statement
36 // Security checkings
37 if (! empty($goto)) {
38 $is_gotofile = preg_replace('@^([^?]+).*$@s', '\\1', $goto);
39 if (! @file_exists('./' . $is_gotofile)) {
40 unset($goto);
41 } else {
42 $is_gotofile = ($is_gotofile == $goto);
44 } else {
45 $goto = (! strlen($table)) ? $cfg['DefaultTabDatabase'] : $cfg['DefaultTabTable'];
46 $is_gotofile = true;
47 } // end if
49 if (! isset($err_url)) {
50 $err_url = (!empty($back) ? $back : $goto)
51 . '?' . PMA_generate_common_url($db)
52 . ((strpos(' ' . $goto, 'db_') != 1 && strlen($table)) ? '&amp;table=' . urlencode($table) : '');
53 } // end if
55 // Coming from a bookmark dialog
56 if (isset($fields['query'])) {
57 $sql_query = $fields['query'];
60 // This one is just to fill $db
61 if (isset($fields['dbase'])) {
62 $db = $fields['dbase'];
65 /**
66 * During grid edit, if we have a relational field, show the dropdown for it
68 * Logic taken from libraries/display_tbl_lib.php
70 * This doesn't seem to be the right place to do this, but I can't think of any
71 * better place either.
73 if (isset($_REQUEST['get_relational_values']) && $_REQUEST['get_relational_values'] == true) {
74 require_once 'libraries/relation.lib.php';
76 $column = $_REQUEST['column'];
77 $foreigners = PMA_getForeigners($db, $table, $column);
79 $display_field = PMA_getDisplayField($foreigners[$column]['foreign_db'], $foreigners[$column]['foreign_table']);
81 $foreignData = PMA_getForeignData($foreigners, $column, false, '', '');
83 if ($_SESSION['tmp_user_values']['relational_display'] == 'D'
84 && (isset($display_field) && strlen($display_field)
85 && (isset($_REQUEST['relation_key_or_display_column']) && $_REQUEST['relation_key_or_display_column']))) {
86 $curr_value = $_REQUEST['relation_key_or_display_column'];
87 } else {
88 $curr_value = $_REQUEST['curr_value'];
90 if ($foreignData['disp_row'] == null) {
91 //Handle the case when number of values is more than $cfg['ForeignKeyMaxLimit']
92 $_url_params = array(
93 'db' => $db,
94 'table' => $table,
95 'field' => $column
98 $dropdown = '<span class="curr_value">' . htmlspecialchars($_REQUEST['curr_value']) . '</span> <a href="browse_foreigners.php' . PMA_generate_common_url($_url_params) . '"'
99 . ' target="_blank" class="browse_foreign" '
100 .'>' . __('Browse foreign values') . '</a>';
101 } else {
102 $dropdown = PMA_foreignDropdown($foreignData['disp_row'], $foreignData['foreign_field'], $foreignData['foreign_display'], $curr_value, $cfg['ForeignKeyMaxLimit']);
103 $dropdown = '<select>' . $dropdown . '</select>';
106 $extra_data['dropdown'] = $dropdown;
107 PMA_ajaxResponse(NULL, true, $extra_data);
111 * Just like above, find possible values for enum fields during grid edit.
113 * Logic taken from libraries/display_tbl_lib.php
115 if (isset($_REQUEST['get_enum_values']) && $_REQUEST['get_enum_values'] == true) {
116 $field_info_query = PMA_DBI_get_columns_sql($db, $table, $_REQUEST['column']);
118 $field_info_result = PMA_DBI_fetch_result($field_info_query, null, null, null, PMA_DBI_QUERY_STORE);
120 $search = array('enum', '(', ')', "'");
122 $values = explode(',', str_replace($search, '', $field_info_result[0]['Type']));
124 $dropdown = '<option value="">&nbsp;</option>';
125 foreach ($values as $value) {
126 $dropdown .= '<option value="' . htmlspecialchars($value) . '"';
127 if ($value == $_REQUEST['curr_value']) {
128 $dropdown .= ' selected="selected"';
130 $dropdown .= '>' . $value . '</option>';
133 $dropdown = '<select>' . $dropdown . '</select>';
135 $extra_data['dropdown'] = $dropdown;
136 PMA_ajaxResponse(NULL, true, $extra_data);
140 * Find possible values for set fields during grid edit.
142 if (isset($_REQUEST['get_set_values']) && $_REQUEST['get_set_values'] == true) {
143 $field_info_query = PMA_DBI_get_columns_sql($db, $table, $_REQUEST['column']);
145 $field_info_result = PMA_DBI_fetch_result($field_info_query, null, null, null, PMA_DBI_QUERY_STORE);
147 $selected_values = explode(',', $_REQUEST['curr_value']);
149 $search = array('set', '(', ')', "'");
150 $values = explode(',', str_replace($search, '', $field_info_result[0]['Type']));
152 $select = '';
153 foreach ($values as $value) {
154 $select .= '<option value="' . htmlspecialchars($value) . '"';
155 if (in_array($value, $selected_values, true)) {
156 $select .= ' selected="selected"';
158 $select .= '>' . $value . '</option>';
161 $select_size = (sizeof($values) > 10) ? 10 : sizeof($values);
162 $select = '<select multiple="multiple" size="' . $select_size . '">' . $select . '</select>';
164 $extra_data['select'] = $select;
165 PMA_ajaxResponse(NULL, true, $extra_data);
169 * Check ajax request to set the column order
171 if (isset($_REQUEST['set_col_prefs']) && $_REQUEST['set_col_prefs'] == true) {
172 $pmatable = new PMA_Table($table, $db);
173 $retval = false;
175 // set column order
176 if (isset($_REQUEST['col_order'])) {
177 $col_order = explode(',', $_REQUEST['col_order']);
178 $retval = $pmatable->setUiProp(PMA_Table::PROP_COLUMN_ORDER, $col_order, $_REQUEST['table_create_time']);
179 if (gettype($retval) != 'boolean') {
180 PMA_ajaxResponse($retval->getString(), false);
185 // set column visibility
186 if ($retval === true && isset($_REQUEST['col_visib'])) {
187 $col_visib = explode(',', $_REQUEST['col_visib']);
188 $retval = $pmatable->setUiProp(PMA_Table::PROP_COLUMN_VISIB, $col_visib, $_REQUEST['table_create_time']);
189 if (gettype($retval) != 'boolean') {
190 PMA_ajaxResponse($retval->getString(), false);
194 PMA_ajaxResponse(NULL, ($retval == true));
197 // Default to browse if no query set and we have table
198 // (needed for browsing from DefaultTabTable)
199 if (empty($sql_query) && strlen($table) && strlen($db)) {
200 require_once './libraries/bookmark.lib.php';
201 $book_sql_query = PMA_Bookmark_get($db, '\'' . PMA_sqlAddSlashes($table) . '\'',
202 'label', false, true);
204 if (! empty($book_sql_query)) {
205 $GLOBALS['using_bookmark_message'] = PMA_message::notice(__('Using bookmark "%s" as default browse query.'));
206 $GLOBALS['using_bookmark_message']->addParam($table);
207 $GLOBALS['using_bookmark_message']->addMessage(PMA_showDocu('faq6_22'));
208 $sql_query = $book_sql_query;
209 } else {
210 $sql_query = 'SELECT * FROM ' . PMA_backquote($table);
212 unset($book_sql_query);
214 // set $goto to what will be displayed if query returns 0 rows
215 $goto = 'tbl_structure.php';
216 } else {
217 // Now we can check the parameters
218 PMA_checkParameters(array('sql_query'));
221 // instead of doing the test twice
222 $is_drop_database = preg_match('/DROP[[:space:]]+(DATABASE|SCHEMA)[[:space:]]+/i',
223 $sql_query);
226 * Check rights in case of DROP DATABASE
228 * This test may be bypassed if $is_js_confirmed = 1 (already checked with js)
229 * but since a malicious user may pass this variable by url/form, we don't take
230 * into account this case.
232 if (!defined('PMA_CHK_DROP')
233 && !$cfg['AllowUserDropDatabase']
234 && $is_drop_database
235 && !$is_superuser) {
236 require_once './libraries/header.inc.php';
237 PMA_mysqlDie(__('"DROP DATABASE" statements are disabled.'), '', '', $err_url);
238 } // end if
240 require_once './libraries/display_tbl.lib.php';
241 PMA_displayTable_checkConfigParams();
244 * Need to find the real end of rows?
246 if (isset($find_real_end) && $find_real_end) {
247 $unlim_num_rows = PMA_Table::countRecords($db, $table, $force_exact = true);
248 $_SESSION['tmp_user_values']['pos'] = @((ceil($unlim_num_rows / $_SESSION['tmp_user_values']['max_rows']) - 1) * $_SESSION['tmp_user_values']['max_rows']);
253 * Bookmark add
255 if (isset($store_bkm)) {
256 PMA_Bookmark_save($fields, (isset($bkm_all_users) && $bkm_all_users == 'true' ? true : false));
257 // go back to sql.php to redisplay query; do not use &amp; in this case:
258 PMA_sendHeaderLocation($cfg['PmaAbsoluteUri'] . $goto . '&label=' . $fields['label']);
259 } // end if
262 * Parse and analyze the query
264 require_once './libraries/parse_analyze.lib.php';
267 * Sets or modifies the $goto variable if required
269 if ($goto == 'sql.php') {
270 $is_gotofile = false;
271 $goto = 'sql.php?'
272 . PMA_generate_common_url($db, $table)
273 . '&amp;sql_query=' . urlencode($sql_query);
274 } // end if
278 * Go back to further page if table should not be dropped
280 if (isset($btnDrop) && $btnDrop == __('No')) {
281 if (!empty($back)) {
282 $goto = $back;
284 if ($is_gotofile) {
285 if (strpos($goto, 'db_') === 0 && strlen($table)) {
286 $table = '';
288 $active_page = $goto;
289 require './' . PMA_securePath($goto);
290 } else {
291 PMA_sendHeaderLocation($cfg['PmaAbsoluteUri'] . str_replace('&amp;', '&', $goto));
293 exit();
294 } // end if
298 * Displays the confirm page if required
300 * This part of the script is bypassed if $is_js_confirmed = 1 (already checked
301 * with js) because possible security issue is not so important here: at most,
302 * the confirm message isn't displayed.
304 * Also bypassed if only showing php code.or validating a SQL query
306 if (! $cfg['Confirm'] || isset($_REQUEST['is_js_confirmed']) || isset($btnDrop)
307 // if we are coming from a "Create PHP code" or a "Without PHP Code"
308 // dialog, we won't execute the query anyway, so don't confirm
309 || isset($GLOBALS['show_as_php'])
310 || !empty($GLOBALS['validatequery'])) {
311 $do_confirm = false;
312 } else {
313 $do_confirm = isset($analyzed_sql[0]['queryflags']['need_confirm']);
316 if ($do_confirm) {
317 $stripped_sql_query = $sql_query;
318 require_once './libraries/header.inc.php';
319 if ($is_drop_database) {
320 echo '<h1 class="error">' . __('You are about to DESTROY a complete database!') . '</h1>';
322 echo '<form action="sql.php" method="post">' . "\n"
323 .PMA_generate_common_hidden_inputs($db, $table);
325 <input type="hidden" name="sql_query" value="<?php echo htmlspecialchars($sql_query); ?>" />
326 <input type="hidden" name="message_to_show" value="<?php echo isset($message_to_show) ? PMA_sanitize($message_to_show, true) : ''; ?>" />
327 <input type="hidden" name="goto" value="<?php echo $goto; ?>" />
328 <input type="hidden" name="back" value="<?php echo isset($back) ? PMA_sanitize($back, true) : ''; ?>" />
329 <input type="hidden" name="reload" value="<?php echo isset($reload) ? PMA_sanitize($reload, true) : 0; ?>" />
330 <input type="hidden" name="purge" value="<?php echo isset($purge) ? PMA_sanitize($purge, true) : ''; ?>" />
331 <input type="hidden" name="dropped_column" value="<?php echo isset($dropped_column) ? PMA_sanitize($dropped_column, true) : ''; ?>" />
332 <input type="hidden" name="show_query" value="<?php echo isset($show_query) ? PMA_sanitize($show_query, true) : ''; ?>" />
333 <?php
334 echo '<fieldset class="confirmation">' . "\n"
335 .' <legend>' . __('Do you really want to ') . '</legend>'
336 .' <tt>' . htmlspecialchars($stripped_sql_query) . '</tt>' . "\n"
337 .'</fieldset>' . "\n"
338 .'<fieldset class="tblFooters">' . "\n";
340 <input type="submit" name="btnDrop" value="<?php echo __('Yes'); ?>" id="buttonYes" />
341 <input type="submit" name="btnDrop" value="<?php echo __('No'); ?>" id="buttonNo" />
342 <?php
343 echo '</fieldset>' . "\n"
344 . '</form>' . "\n";
347 * Displays the footer and exit
349 require './libraries/footer.inc.php';
350 } // end if $do_confirm
353 // Defines some variables
354 // A table has to be created, renamed, dropped -> navi frame should be reloaded
356 * @todo use the parser/analyzer
359 if (empty($reload)
360 && preg_match('/^(CREATE|ALTER|DROP)\s+(VIEW|TABLE|DATABASE|SCHEMA)\s+/i', $sql_query)) {
361 $reload = 1;
364 // SK -- Patch: $is_group added for use in calculation of total number of
365 // rows.
366 // $is_count is changed for more correct "LIMIT" clause
367 // appending in queries like
368 // "SELECT COUNT(...) FROM ... GROUP BY ..."
371 * @todo detect all this with the parser, to avoid problems finding
372 * those strings in comments or backquoted identifiers
375 $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;
376 if ($is_select) { // see line 141
377 $is_group = preg_match('@(GROUP[[:space:]]+BY|HAVING|SELECT[[:space:]]+DISTINCT)[[:space:]]+@i', $sql_query);
378 $is_func = !$is_group && (preg_match('@[[:space:]]+(SUM|AVG|STD|STDDEV|MIN|MAX|BIT_OR|BIT_AND)\s*\(@i', $sql_query));
379 $is_count = !$is_group && (preg_match('@^SELECT[[:space:]]+COUNT\((.*\.+)?.*\)@i', $sql_query));
380 $is_export = (preg_match('@[[:space:]]+INTO[[:space:]]+OUTFILE[[:space:]]+@i', $sql_query));
381 $is_analyse = (preg_match('@[[:space:]]+PROCEDURE[[:space:]]+ANALYSE@i', $sql_query));
382 } elseif (preg_match('@^EXPLAIN[[:space:]]+@i', $sql_query)) {
383 $is_explain = true;
384 } elseif (preg_match('@^DELETE[[:space:]]+@i', $sql_query)) {
385 $is_delete = true;
386 $is_affected = true;
387 } elseif (preg_match('@^(INSERT|LOAD[[:space:]]+DATA|REPLACE)[[:space:]]+@i', $sql_query)) {
388 $is_insert = true;
389 $is_affected = true;
390 if (preg_match('@^(REPLACE)[[:space:]]+@i', $sql_query)) {
391 $is_replace = true;
393 } elseif (preg_match('@^UPDATE[[:space:]]+@i', $sql_query)) {
394 $is_affected = true;
395 } elseif (preg_match('@^[[:space:]]*SHOW[[:space:]]+@i', $sql_query)) {
396 $is_show = true;
397 } elseif (preg_match('@^(CHECK|ANALYZE|REPAIR|OPTIMIZE)[[:space:]]+TABLE[[:space:]]+@i', $sql_query)) {
398 $is_maint = true;
401 // assign default full_sql_query
402 $full_sql_query = $sql_query;
404 // Handle remembered sorting order, only for single table query
405 if ($GLOBALS['cfg']['RememberSorting']
406 && ! ($is_count || $is_export || $is_func || $is_analyse)
407 && count($analyzed_sql[0]['select_expr']) == 0
408 && isset($analyzed_sql[0]['queryflags']['select_from'])
409 && count($analyzed_sql[0]['table_ref']) == 1
411 $pmatable = new PMA_Table($table, $db);
412 if (empty($analyzed_sql[0]['order_by_clause'])) {
413 $sorted_col = $pmatable->getUiProp(PMA_Table::PROP_SORTED_COLUMN);
414 if ($sorted_col) {
415 // retrieve the remembered sorting order for current table
416 $sql_order_to_append = ' ORDER BY ' . $sorted_col . ' ';
417 $full_sql_query = $analyzed_sql[0]['section_before_limit'] . $sql_order_to_append . $analyzed_sql[0]['section_after_limit'];
419 // update the $analyzed_sql
420 $analyzed_sql[0]['section_before_limit'] .= $sql_order_to_append;
421 $analyzed_sql[0]['order_by_clause'] = $sorted_col;
423 } else {
424 // store the remembered table into session
425 $pmatable->setUiProp(PMA_Table::PROP_SORTED_COLUMN, $analyzed_sql[0]['order_by_clause']);
429 // Do append a "LIMIT" clause?
430 if ((! $cfg['ShowAll'] || $_SESSION['tmp_user_values']['max_rows'] != 'all')
431 && ! ($is_count || $is_export || $is_func || $is_analyse)
432 && isset($analyzed_sql[0]['queryflags']['select_from'])
433 && ! isset($analyzed_sql[0]['queryflags']['offset'])
434 && empty($analyzed_sql[0]['limit_clause'])
436 $sql_limit_to_append = ' LIMIT ' . $_SESSION['tmp_user_values']['pos'] . ', ' . $_SESSION['tmp_user_values']['max_rows'] . " ";
438 $full_sql_query = $analyzed_sql[0]['section_before_limit'] . "\n" . $sql_limit_to_append . $analyzed_sql[0]['section_after_limit'];
440 * @todo pretty printing of this modified query
442 if (isset($display_query)) {
443 // if the analysis of the original query revealed that we found
444 // a section_after_limit, we now have to analyze $display_query
445 // to display it correctly
447 if (!empty($analyzed_sql[0]['section_after_limit']) && trim($analyzed_sql[0]['section_after_limit']) != ';') {
448 $analyzed_display_query = PMA_SQP_analyze(PMA_SQP_parse($display_query));
449 $display_query = $analyzed_display_query[0]['section_before_limit'] . "\n" . $sql_limit_to_append . $analyzed_display_query[0]['section_after_limit'];
455 if (strlen($db)) {
456 PMA_DBI_select_db($db);
459 // E x e c u t e t h e q u e r y
461 // Only if we didn't ask to see the php code (mikebeck)
462 if (isset($GLOBALS['show_as_php']) || !empty($GLOBALS['validatequery'])) {
463 unset($result);
464 $num_rows = 0;
465 } else {
466 if (isset($_SESSION['profiling']) && PMA_profilingSupported()) {
467 PMA_DBI_query('SET PROFILING=1;');
470 // Measure query time.
471 $querytime_before = array_sum(explode(' ', microtime()));
473 $result = @PMA_DBI_try_query($full_sql_query, null, PMA_DBI_QUERY_STORE);
475 // If a stored procedure was called, there may be more results that are
476 // queued up and waiting to be flushed from the buffer. So let's do that.
477 while (true) {
478 if (! PMA_DBI_more_results()) {
479 break;
481 PMA_DBI_next_result();
484 $querytime_after = array_sum(explode(' ', microtime()));
486 $GLOBALS['querytime'] = $querytime_after - $querytime_before;
488 // Displays an error message if required and stop parsing the script
489 if ($error = PMA_DBI_getError()) {
490 if ($is_gotofile) {
491 if (strpos($goto, 'db_') === 0 && strlen($table)) {
492 $table = '';
494 $active_page = $goto;
495 $message = PMA_Message::rawError($error);
497 if ($GLOBALS['is_ajax_request'] == true) {
498 PMA_ajaxResponse($message, false);
502 * Go to target path.
504 require './' . PMA_securePath($goto);
505 } else {
506 $full_err_url = (preg_match('@^(db|tbl)_@', $err_url))
507 ? $err_url . '&amp;show_query=1&amp;sql_query=' . urlencode($sql_query)
508 : $err_url;
509 PMA_mysqlDie($error, $full_sql_query, '', $full_err_url);
511 exit;
513 unset($error);
515 // Gets the number of rows affected/returned
516 // (This must be done immediately after the query because
517 // mysql_affected_rows() reports about the last query done)
519 if (!$is_affected) {
520 $num_rows = ($result) ? @PMA_DBI_num_rows($result) : 0;
521 } elseif (! isset($num_rows)) {
522 $num_rows = @PMA_DBI_affected_rows();
525 // Grabs the profiling results
526 if (isset($_SESSION['profiling']) && PMA_profilingSupported()) {
527 $profiling_results = PMA_DBI_fetch_result('SHOW PROFILE;');
530 // Checks if the current database has changed
531 // This could happen if the user sends a query like "USE `database`;"
533 * commented out auto-switching to active database - really required?
534 * bug #1814718 win: table list disappears (mixed case db names)
535 * https://sourceforge.net/support/tracker.php?aid=1814718
536 * @todo RELEASE test and comit or rollback before release
537 $current_db = PMA_DBI_fetch_value('SELECT DATABASE()');
538 if ($db !== $current_db) {
539 $db = $current_db;
540 $reload = 1;
542 unset($current_db);
545 // tmpfile remove after convert encoding appended by Y.Kawada
546 if (function_exists('PMA_kanji_file_conv')
547 && (isset($textfile) && file_exists($textfile))) {
548 unlink($textfile);
551 // Counts the total number of rows for the same 'SELECT' query without the
552 // 'LIMIT' clause that may have been programatically added
554 if (empty($sql_limit_to_append)) {
555 $unlim_num_rows = $num_rows;
556 // if we did not append a limit, set this to get a correct
557 // "Showing rows..." message
558 //$_SESSION['tmp_user_values']['max_rows'] = 'all';
559 } elseif ($is_select) {
561 // c o u n t q u e r y
563 // If we are "just browsing", there is only one table,
564 // and no WHERE clause (or just 'WHERE 1 '),
565 // we do a quick count (which uses MaxExactCount) because
566 // SQL_CALC_FOUND_ROWS is not quick on large InnoDB tables
568 // However, do not count again if we did it previously
569 // due to $find_real_end == true
571 if (!$is_group
572 && ! isset($analyzed_sql[0]['queryflags']['union'])
573 && ! isset($analyzed_sql[0]['table_ref'][1]['table_name'])
574 && (empty($analyzed_sql[0]['where_clause'])
575 || $analyzed_sql[0]['where_clause'] == '1 ')
576 && ! isset($find_real_end)
579 // "j u s t b r o w s i n g"
580 $unlim_num_rows = PMA_Table::countRecords($db, $table);
582 } else { // n o t " j u s t b r o w s i n g "
584 // add select expression after the SQL_CALC_FOUND_ROWS
586 // for UNION, just adding SQL_CALC_FOUND_ROWS
587 // after the first SELECT works.
589 // take the left part, could be:
590 // SELECT
591 // (SELECT
592 $count_query = PMA_SQP_formatHtml($parsed_sql, 'query_only', 0, $analyzed_sql[0]['position_of_first_select'] + 1);
593 $count_query .= ' SQL_CALC_FOUND_ROWS ';
594 // add everything that was after the first SELECT
595 $count_query .= PMA_SQP_formatHtml($parsed_sql, 'query_only', $analyzed_sql[0]['position_of_first_select']+1);
596 // ensure there is no semicolon at the end of the
597 // count query because we'll probably add
598 // a LIMIT 1 clause after it
599 $count_query = rtrim($count_query);
600 $count_query = rtrim($count_query, ';');
602 // if using SQL_CALC_FOUND_ROWS, add a LIMIT to avoid
603 // long delays. Returned count will be complete anyway.
604 // (but a LIMIT would disrupt results in an UNION)
606 if (! isset($analyzed_sql[0]['queryflags']['union'])) {
607 $count_query .= ' LIMIT 1';
610 // run the count query
612 PMA_DBI_try_query($count_query);
613 // if (mysql_error()) {
614 // void.
615 // I tried the case
616 // (SELECT `User`, `Host`, `Db`, `Select_priv` FROM `db`)
617 // UNION (SELECT `User`, `Host`, "%" AS "Db",
618 // `Select_priv`
619 // FROM `user`) ORDER BY `User`, `Host`, `Db`;
620 // and although the generated count_query is wrong
621 // the SELECT FOUND_ROWS() work! (maybe it gets the
622 // count from the latest query that worked)
624 // another case where the count_query is wrong:
625 // SELECT COUNT(*), f1 from t1 group by f1
626 // and you click to sort on count(*)
627 // }
628 $unlim_num_rows = PMA_DBI_fetch_value('SELECT FOUND_ROWS()');
629 } // end else "just browsing"
631 } else { // not $is_select
632 $unlim_num_rows = 0;
633 } // end rows total count
635 // if a table or database gets dropped, check column comments.
636 if (isset($purge) && $purge == '1') {
638 * Cleanup relations.
640 require_once './libraries/relation_cleanup.lib.php';
642 if (strlen($table) && strlen($db)) {
643 PMA_relationsCleanupTable($db, $table);
644 } elseif (strlen($db)) {
645 PMA_relationsCleanupDatabase($db);
646 } else {
647 // VOID. No DB/Table gets deleted.
648 } // end if relation-stuff
649 } // end if ($purge)
651 // If a column gets dropped, do relation magic.
652 if (isset($dropped_column) && strlen($db) && strlen($table) && !empty($dropped_column)) {
653 require_once './libraries/relation_cleanup.lib.php';
654 PMA_relationsCleanupColumn($db, $table, $dropped_column);
656 } // end if column was dropped
657 } // end else "didn't ask to see php code"
659 // No rows returned -> move back to the calling page
660 if (0 == $num_rows || $is_affected) {
661 if ($is_delete) {
662 $message = PMA_Message::deleted_rows($num_rows);
663 } elseif ($is_insert) {
664 if ($is_replace) {
665 /* For replace we get DELETED + INSERTED row count, so we have to call it affected */
666 $message = PMA_Message::affected_rows($num_rows);
667 } else {
668 $message = PMA_Message::inserted_rows($num_rows);
670 $insert_id = PMA_DBI_insert_id();
671 if ($insert_id != 0) {
672 // insert_id is id of FIRST record inserted in one insert, so if we inserted multiple rows, we had to increment this
673 $message->addMessage('[br]');
674 // need to use a temporary because the Message class
675 // currently supports adding parameters only to the first
676 // message
677 $_inserted = PMA_Message::notice(__('Inserted row id: %1$d'));
678 $_inserted->addParam($insert_id + $num_rows - 1);
679 $message->addMessage($_inserted);
681 } elseif ($is_affected) {
682 $message = PMA_Message::affected_rows($num_rows);
684 // Ok, here is an explanation for the !$is_select.
685 // The form generated by sql_query_form.lib.php
686 // and db_sql.php has many submit buttons
687 // on the same form, and some confusion arises from the
688 // fact that $message_to_show is sent for every case.
689 // The $message_to_show containing a success message and sent with
690 // the form should not have priority over errors
691 } elseif (!empty($message_to_show) && !$is_select) {
692 $message = PMA_Message::rawSuccess(htmlspecialchars($message_to_show));
693 } elseif (!empty($GLOBALS['show_as_php'])) {
694 $message = PMA_Message::success(__('Showing as PHP code'));
695 } elseif (isset($GLOBALS['show_as_php'])) {
696 /* User disable showing as PHP, query is only displayed */
697 $message = PMA_Message::notice(__('Showing SQL query'));
698 } elseif (!empty($GLOBALS['validatequery'])) {
699 $message = PMA_Message::notice(__('Validated SQL'));
700 } else {
701 $message = PMA_Message::success(__('MySQL returned an empty result set (i.e. zero rows).'));
704 if (isset($GLOBALS['querytime'])) {
705 $_querytime = PMA_Message::notice(__('Query took %01.4f sec'));
706 $_querytime->addParam($GLOBALS['querytime']);
707 $message->addMessage('(');
708 $message->addMessage($_querytime);
709 $message->addMessage(')');
712 if ($GLOBALS['is_ajax_request'] == true) {
713 if ($cfg['ShowSQL']) {
714 $extra_data['sql_query'] = PMA_showMessage($message, $GLOBALS['sql_query'], 'success');
716 if (isset($GLOBALS['reload']) && $GLOBALS['reload'] == 1) {
717 $extra_data['reload'] = 1;
718 $extra_data['db'] = $GLOBALS['db'];
720 PMA_ajaxResponse($message, $message->isSuccess(), (isset($extra_data) ? $extra_data : ''));
723 if ($is_gotofile) {
724 $goto = PMA_securePath($goto);
725 // Checks for a valid target script
726 $is_db = $is_table = false;
727 if (isset($_REQUEST['purge']) && $_REQUEST['purge'] == '1') {
728 $table = '';
729 unset($url_params['table']);
731 include 'libraries/db_table_exists.lib.php';
733 if (strpos($goto, 'tbl_') === 0 && ! $is_table) {
734 if (strlen($table)) {
735 $table = '';
737 $goto = 'db_sql.php';
739 if (strpos($goto, 'db_') === 0 && ! $is_db) {
740 if (strlen($db)) {
741 $db = '';
743 $goto = 'main.php';
745 // Loads to target script
746 if ($goto != 'main.php') {
747 require_once './libraries/header.inc.php';
749 $active_page = $goto;
750 require './' . $goto;
751 } else {
752 // avoid a redirect loop when last record was deleted
753 if (0 == $num_rows && 'sql.php' == $cfg['DefaultTabTable']) {
754 $goto = str_replace('sql.php','tbl_structure.php',$goto);
756 PMA_sendHeaderLocation($cfg['PmaAbsoluteUri'] . str_replace('&amp;', '&', $goto) . '&message=' . urlencode($message));
757 } // end else
758 exit();
759 } // end no rows returned
761 // At least one row is returned -> displays a table with results
762 else {
763 //If we are retrieving the full value of a truncated field or the original
764 // value of a transformed field, show it here and exit
765 if ($GLOBALS['grid_edit'] == true && $GLOBALS['cfg']['AjaxEnable']) {
766 $row = PMA_DBI_fetch_row($result);
767 $extra_data = array();
768 $extra_data['value'] = $row[0];
769 PMA_ajaxResponse(NULL, true, $extra_data);
772 if (isset($_REQUEST['ajax_request']) && isset($_REQUEST['table_maintenance'])) {
773 $GLOBALS['js_include'][] = 'functions.js';
774 $GLOBALS['js_include'][] = 'makegrid.js';
775 $GLOBALS['js_include'][] = 'sql.js';
777 // Gets the list of fields properties
778 if (isset($result) && $result) {
779 $fields_meta = PMA_DBI_get_fields_meta($result);
780 $fields_cnt = count($fields_meta);
783 if (empty($disp_mode)) {
784 // see the "PMA_setDisplayMode()" function in
785 // libraries/display_tbl.lib.php
786 $disp_mode = 'urdr111101';
789 // hide edit and delete links for information_schema
790 if (PMA_is_system_schema($db)) {
791 $disp_mode = 'nnnn110111';
794 $message = PMA_Message::success($message);
795 echo PMA_showMessage($message, $GLOBALS['sql_query'], 'success');
796 PMA_displayTable($result, $disp_mode, $analyzed_sql);
797 exit();
800 // Displays the headers
801 if (isset($show_query)) {
802 unset($show_query);
804 if (isset($printview) && $printview == '1') {
805 require_once './libraries/header_printview.inc.php';
806 } else {
808 $GLOBALS['js_include'][] = 'functions.js';
809 $GLOBALS['js_include'][] = 'makegrid.js';
810 $GLOBALS['js_include'][] = 'sql.js';
812 unset($message);
814 if (! $GLOBALS['is_ajax_request'] || ! $GLOBALS['cfg']['AjaxEnable']) {
815 if (strlen($table)) {
816 require './libraries/tbl_common.php';
817 $url_query .= '&amp;goto=tbl_sql.php&amp;back=tbl_sql.php';
818 require './libraries/tbl_info.inc.php';
819 require './libraries/tbl_links.inc.php';
820 } elseif (strlen($db)) {
821 require './libraries/db_common.inc.php';
822 require './libraries/db_info.inc.php';
823 } else {
824 require './libraries/server_common.inc.php';
825 require './libraries/server_links.inc.php';
827 } else {
828 require_once './libraries/header.inc.php';
829 //we don't need to buffer the output in PMA_showMessage here.
830 //set a global variable and check against it in the function
831 $GLOBALS['buffer_message'] = false;
835 if (strlen($db)) {
836 $cfgRelation = PMA_getRelationsParam();
839 // Gets the list of fields properties
840 if (isset($result) && $result) {
841 $fields_meta = PMA_DBI_get_fields_meta($result);
842 $fields_cnt = count($fields_meta);
845 if (! $GLOBALS['is_ajax_request']) {
846 //begin the sqlqueryresults div here. container div
847 echo '<div id="sqlqueryresults"';
848 if ($GLOBALS['cfg']['AjaxEnable']) {
849 echo ' class="ajax"';
851 echo '>';
854 // Display previous update query (from tbl_replace)
855 if (isset($disp_query) && $cfg['ShowSQL'] == true) {
856 PMA_showMessage($disp_message, $disp_query, 'success');
859 if (isset($profiling_results)) {
860 // pma_token/url_query needed for chart export
862 <script type="text/javascript">
863 pma_token = '<?php echo $_SESSION[' PMA_token ']; ?>';
864 url_query = '<?php echo isset($url_query)?$url_query:PMA_generate_common_url($db);?>';
865 $(document).ready(makeProfilingChart);
866 </script>
867 <?php
868 echo '<fieldset><legend>' . __('Profiling') . '</legend>' . "\n";
869 echo '<div style="float: left;">';
870 echo '<table>' . "\n";
871 echo ' <tr>' . "\n";
872 echo ' <th>' . __('Status') . PMA_showMySQLDocu('general-thread-states','general-thread-states') . '</th>' . "\n";
873 echo ' <th>' . __('Time') . '</th>' . "\n";
874 echo ' </tr>' . "\n";
876 $chart_json = Array();
877 foreach ($profiling_results as $one_result) {
878 echo ' <tr>' . "\n";
879 echo '<td>' . ucwords($one_result['Status']) . '</td>' . "\n";
880 echo '<td align="right">' . (PMA_formatNumber($one_result['Duration'],3,1)) . 's</td>' . "\n";
881 $chart_json[ucwords($one_result['Status'])] = $one_result['Duration'];
884 echo '</table>' . "\n";
885 echo '</div>';
886 //require_once './libraries/chart.lib.php';
887 echo '<div id="profilingchart" style="display:none;">';
888 //PMA_chart_profiling($profiling_results);
889 echo json_encode($chart_json);
890 echo '</div>';
891 echo '</fieldset>' . "\n";
894 // Displays the results in a table
895 if (empty($disp_mode)) {
896 // see the "PMA_setDisplayMode()" function in
897 // libraries/display_tbl.lib.php
898 $disp_mode = 'urdr111101';
901 // hide edit and delete links for information_schema
902 if (PMA_is_system_schema($db)) {
903 $disp_mode = 'nnnn110111';
906 if (isset($label)) {
907 $message = PMA_message::success(__('Bookmark %s created'));
908 $message->addParam($label);
909 $message->display();
912 PMA_displayTable($result, $disp_mode, $analyzed_sql);
913 PMA_DBI_free_result($result);
915 // BEGIN INDEX CHECK See if indexes should be checked.
916 if (isset($query_type) && $query_type == 'check_tbl' && isset($selected) && is_array($selected)) {
917 foreach ($selected as $idx => $tbl_name) {
918 $check = PMA_Index::findDuplicates($tbl_name, $db);
919 if (! empty($check)) {
920 printf(__('Problems with indexes of table `%s`'), $tbl_name);
921 echo $check;
924 } // End INDEX CHECK
926 // Bookmark support if required
927 if ($disp_mode[7] == '1'
928 && (! empty($cfg['Bookmark']) && empty($id_bookmark))
929 && !empty($sql_query)) {
930 echo "\n";
932 $goto = 'sql.php?'
933 . PMA_generate_common_url($db, $table)
934 . '&amp;sql_query=' . urlencode($sql_query)
935 . '&amp;id_bookmark=1';
938 <form action="sql.php" method="post" onsubmit="return emptyFormElements(this, 'fields[label]');">
939 <?php echo PMA_generate_common_hidden_inputs(); ?>
940 <input type="hidden" name="goto" value="<?php echo $goto; ?>" />
941 <input type="hidden" name="fields[dbase]" value="<?php echo htmlspecialchars($db); ?>" />
942 <input type="hidden" name="fields[user]" value="<?php echo $cfg['Bookmark']['user']; ?>" />
943 <input type="hidden" name="fields[query]" value="<?php echo urlencode(isset($complete_query) ? $complete_query : $sql_query); ?>" />
944 <fieldset>
945 <legend><?php
946 echo PMA_getIcon('b_bookmark.png', __('Bookmark this SQL query'), true);
948 </legend>
950 <div class="formelement">
951 <label for="fields_label_"><?php echo __('Label'); ?>:</label>
952 <input type="text" id="fields_label_" name="fields[label]" value="" />
953 </div>
955 <div class="formelement">
956 <input type="checkbox" name="bkm_all_users" id="bkm_all_users" value="true" />
957 <label for="bkm_all_users"><?php echo __('Let every user access this bookmark'); ?></label>
958 </div>
960 <div class="clearfloat"></div>
961 </fieldset>
962 <fieldset class="tblFooters">
963 <input type="submit" name="store_bkm" value="<?php echo __('Bookmark this SQL query'); ?>" />
964 </fieldset>
965 </form>
966 <?php
967 } // end bookmark support
969 // Do print the page if required
970 if (isset($printview) && $printview == '1') {
972 <script type="text/javascript">
973 //<![CDATA[
974 // Do print the page
975 window.onload = function()
977 if (typeof(window.print) != 'undefined') {
978 window.print();
981 //]]>
982 </script>
983 <?php
984 } // end print case
986 if ($GLOBALS['is_ajax_request'] != true) {
987 echo '</div>'; // end sqlqueryresults div
989 } // end rows returned
992 * Displays the footer
994 if (! isset($_REQUEST['table_maintenance'])) {
995 require './libraries/footer.inc.php';