Translation update done using Pootle.
[phpmyadmin.git] / sql.php
blob3e6e6d445fefb40836eb5db68f5b4e64d3bee090
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';
24 if (isset($_SESSION['profiling'])) {
25 $GLOBALS['js_include'][] = 'highcharts/highcharts.js';
26 /* Files required for chart exporting */
27 $GLOBALS['js_include'][] = 'highcharts/exporting.js';
28 /* < IE 9 doesn't support canvas natively */
29 if (PMA_USR_BROWSER_AGENT == 'IE' && PMA_USR_BROWSER_VER < 9) {
30 $GLOBALS['js_include'][] = 'canvg/flashcanvas.js';
32 $GLOBALS['js_include'][] = 'canvg/canvg.js';
35 /**
36 * Defines the url to return to in case of error in a sql statement
38 // Security checkings
39 if (! empty($goto)) {
40 $is_gotofile = preg_replace('@^([^?]+).*$@s', '\\1', $goto);
41 if (! @file_exists('./' . $is_gotofile)) {
42 unset($goto);
43 } else {
44 $is_gotofile = ($is_gotofile == $goto);
46 } else {
47 $goto = (! strlen($table)) ? $cfg['DefaultTabDatabase'] : $cfg['DefaultTabTable'];
48 $is_gotofile = true;
49 } // end if
51 if (! isset($err_url)) {
52 $err_url = (! empty($back) ? $back : $goto)
53 . '?' . PMA_generate_common_url($db)
54 . ((strpos(' ' . $goto, 'db_') != 1 && strlen($table)) ? '&amp;table=' . urlencode($table) : '');
55 } // end if
57 // Coming from a bookmark dialog
58 if (isset($fields['query'])) {
59 $sql_query = $fields['query'];
62 // This one is just to fill $db
63 if (isset($fields['dbase'])) {
64 $db = $fields['dbase'];
67 /**
68 * During grid edit, if we have a relational field, show the dropdown for it
70 * Logic taken from libraries/display_tbl_lib.php
72 * This doesn't seem to be the right place to do this, but I can't think of any
73 * better place either.
75 if (isset($_REQUEST['get_relational_values']) && $_REQUEST['get_relational_values'] == true) {
76 include_once 'libraries/relation.lib.php';
78 $column = $_REQUEST['column'];
79 $foreigners = PMA_getForeigners($db, $table, $column);
81 $display_field = PMA_getDisplayField($foreigners[$column]['foreign_db'], $foreigners[$column]['foreign_table']);
83 $foreignData = PMA_getForeignData($foreigners, $column, false, '', '');
85 if ($_SESSION['tmp_user_values']['relational_display'] == 'D'
86 && isset($display_field)
87 && strlen($display_field)
88 && isset($_REQUEST['relation_key_or_display_column'])
89 && $_REQUEST['relation_key_or_display_column']
90 ) {
91 $curr_value = $_REQUEST['relation_key_or_display_column'];
92 } else {
93 $curr_value = $_REQUEST['curr_value'];
95 if ($foreignData['disp_row'] == null) {
96 //Handle the case when number of values is more than $cfg['ForeignKeyMaxLimit']
97 $_url_params = array(
98 'db' => $db,
99 'table' => $table,
100 'field' => $column
103 $dropdown = '<span class="curr_value">' . htmlspecialchars($_REQUEST['curr_value']) . '</span> <a href="browse_foreigners.php' . PMA_generate_common_url($_url_params) . '"'
104 . ' target="_blank" class="browse_foreign" '
105 .'>' . __('Browse foreign values') . '</a>';
106 } else {
107 $dropdown = PMA_foreignDropdown($foreignData['disp_row'], $foreignData['foreign_field'], $foreignData['foreign_display'], $curr_value, $cfg['ForeignKeyMaxLimit']);
108 $dropdown = '<select>' . $dropdown . '</select>';
111 $extra_data['dropdown'] = $dropdown;
112 PMA_ajaxResponse(null, true, $extra_data);
116 * Just like above, find possible values for enum fields during grid edit.
118 * Logic taken from libraries/display_tbl_lib.php
120 if (isset($_REQUEST['get_enum_values']) && $_REQUEST['get_enum_values'] == true) {
121 $field_info_query = PMA_DBI_get_columns_sql($db, $table, $_REQUEST['column']);
123 $field_info_result = PMA_DBI_fetch_result($field_info_query, null, null, null, PMA_DBI_QUERY_STORE);
125 $search = array('enum', '(', ')', "'");
127 $values = explode(',', str_replace($search, '', $field_info_result[0]['Type']));
129 $dropdown = '<option value="">&nbsp;</option>';
130 foreach ($values as $value) {
131 $dropdown .= '<option value="' . htmlspecialchars($value) . '"';
132 if ($value == $_REQUEST['curr_value']) {
133 $dropdown .= ' selected="selected"';
135 $dropdown .= '>' . $value . '</option>';
138 $dropdown = '<select>' . $dropdown . '</select>';
140 $extra_data['dropdown'] = $dropdown;
141 PMA_ajaxResponse(null, true, $extra_data);
145 * Find possible values for set fields during grid edit.
147 if (isset($_REQUEST['get_set_values']) && $_REQUEST['get_set_values'] == true) {
148 $field_info_query = PMA_DBI_get_columns_sql($db, $table, $_REQUEST['column']);
150 $field_info_result = PMA_DBI_fetch_result($field_info_query, null, null, null, PMA_DBI_QUERY_STORE);
152 $selected_values = explode(',', $_REQUEST['curr_value']);
154 $search = array('set', '(', ')', "'");
155 $values = explode(',', str_replace($search, '', $field_info_result[0]['Type']));
157 $select = '';
158 foreach ($values as $value) {
159 $select .= '<option value="' . htmlspecialchars($value) . '"';
160 if (in_array($value, $selected_values, true)) {
161 $select .= ' selected="selected"';
163 $select .= '>' . $value . '</option>';
166 $select_size = (sizeof($values) > 10) ? 10 : sizeof($values);
167 $select = '<select multiple="multiple" size="' . $select_size . '">' . $select . '</select>';
169 $extra_data['select'] = $select;
170 PMA_ajaxResponse(null, true, $extra_data);
174 * Check ajax request to set the column order
176 if (isset($_REQUEST['set_col_prefs']) && $_REQUEST['set_col_prefs'] == true) {
177 $pmatable = new PMA_Table($table, $db);
178 $retval = false;
180 // set column order
181 if (isset($_REQUEST['col_order'])) {
182 $col_order = explode(',', $_REQUEST['col_order']);
183 $retval = $pmatable->setUiProp(PMA_Table::PROP_COLUMN_ORDER, $col_order, $_REQUEST['table_create_time']);
184 if (gettype($retval) != 'boolean') {
185 PMA_ajaxResponse($retval->getString(), false);
189 // set column visibility
190 if ($retval === true && isset($_REQUEST['col_visib'])) {
191 $col_visib = explode(',', $_REQUEST['col_visib']);
192 $retval = $pmatable->setUiProp(PMA_Table::PROP_COLUMN_VISIB, $col_visib, $_REQUEST['table_create_time']);
193 if (gettype($retval) != 'boolean') {
194 PMA_ajaxResponse($retval->getString(), false);
198 PMA_ajaxResponse(null, ($retval == true));
201 // Default to browse if no query set and we have table
202 // (needed for browsing from DefaultTabTable)
203 if (empty($sql_query) && strlen($table) && strlen($db)) {
204 include_once './libraries/bookmark.lib.php';
205 $book_sql_query = PMA_Bookmark_get(
206 $db,
207 '\'' . PMA_sqlAddSlashes($table) . '\'',
208 'label',
209 false,
210 true
213 if (! empty($book_sql_query)) {
214 $GLOBALS['using_bookmark_message'] = PMA_message::notice(__('Using bookmark "%s" as default browse query.'));
215 $GLOBALS['using_bookmark_message']->addParam($table);
216 $GLOBALS['using_bookmark_message']->addMessage(PMA_showDocu('faq6_22'));
217 $sql_query = $book_sql_query;
218 } else {
219 $sql_query = 'SELECT * FROM ' . PMA_backquote($table);
221 unset($book_sql_query);
223 // set $goto to what will be displayed if query returns 0 rows
224 $goto = 'tbl_structure.php';
225 } else {
226 // Now we can check the parameters
227 PMA_checkParameters(array('sql_query'));
230 // instead of doing the test twice
231 $is_drop_database = preg_match(
232 '/DROP[[:space:]]+(DATABASE|SCHEMA)[[:space:]]+/i',
233 $sql_query
237 * Check rights in case of DROP DATABASE
239 * This test may be bypassed if $is_js_confirmed = 1 (already checked with js)
240 * but since a malicious user may pass this variable by url/form, we don't take
241 * into account this case.
243 if (! defined('PMA_CHK_DROP')
244 && ! $cfg['AllowUserDropDatabase']
245 && $is_drop_database
246 && ! $is_superuser
248 include_once './libraries/header.inc.php';
249 PMA_mysqlDie(__('"DROP DATABASE" statements are disabled.'), '', '', $err_url);
250 } // end if
252 require_once './libraries/display_tbl.lib.php';
253 PMA_displayTable_checkConfigParams();
256 * Need to find the real end of rows?
258 if (isset($find_real_end) && $find_real_end) {
259 $unlim_num_rows = PMA_Table::countRecords($db, $table, $force_exact = true);
260 $_SESSION['tmp_user_values']['pos'] = @((ceil($unlim_num_rows / $_SESSION['tmp_user_values']['max_rows']) - 1) * $_SESSION['tmp_user_values']['max_rows']);
265 * Bookmark add
267 if (isset($store_bkm)) {
268 PMA_Bookmark_save($fields, (isset($bkm_all_users) && $bkm_all_users == 'true' ? true : false));
269 // go back to sql.php to redisplay query; do not use &amp; in this case:
270 PMA_sendHeaderLocation($cfg['PmaAbsoluteUri'] . $goto . '&label=' . $fields['label']);
271 } // end if
274 * Parse and analyze the query
276 require_once './libraries/parse_analyze.lib.php';
279 * Sets or modifies the $goto variable if required
281 if ($goto == 'sql.php') {
282 $is_gotofile = false;
283 $goto = 'sql.php?'
284 . PMA_generate_common_url($db, $table)
285 . '&amp;sql_query=' . urlencode($sql_query);
286 } // end if
290 * Go back to further page if table should not be dropped
292 if (isset($btnDrop) && $btnDrop == __('No')) {
293 if (! empty($back)) {
294 $goto = $back;
296 if ($is_gotofile) {
297 if (strpos($goto, 'db_') === 0 && strlen($table)) {
298 $table = '';
300 $active_page = $goto;
301 include './' . PMA_securePath($goto);
302 } else {
303 PMA_sendHeaderLocation($cfg['PmaAbsoluteUri'] . str_replace('&amp;', '&', $goto));
305 exit();
306 } // end if
310 * Displays the confirm page if required
312 * This part of the script is bypassed if $is_js_confirmed = 1 (already checked
313 * with js) because possible security issue is not so important here: at most,
314 * the confirm message isn't displayed.
316 * Also bypassed if only showing php code.or validating a SQL query
318 if (! $cfg['Confirm']
319 || isset($_REQUEST['is_js_confirmed'])
320 || isset($btnDrop)
321 // if we are coming from a "Create PHP code" or a "Without PHP Code"
322 // dialog, we won't execute the query anyway, so don't confirm
323 || isset($GLOBALS['show_as_php'])
324 || ! empty($GLOBALS['validatequery'])
326 $do_confirm = false;
327 } else {
328 $do_confirm = isset($analyzed_sql[0]['queryflags']['need_confirm']);
331 if ($do_confirm) {
332 $stripped_sql_query = $sql_query;
333 include_once './libraries/header.inc.php';
334 if ($is_drop_database) {
335 echo '<h1 class="error">' . __('You are about to DESTROY a complete database!') . '</h1>';
337 echo '<form action="sql.php" method="post">' . "\n"
338 .PMA_generate_common_hidden_inputs($db, $table);
340 <input type="hidden" name="sql_query" value="<?php echo htmlspecialchars($sql_query); ?>" />
341 <input type="hidden" name="message_to_show" value="<?php echo isset($message_to_show) ? PMA_sanitize($message_to_show, true) : ''; ?>" />
342 <input type="hidden" name="goto" value="<?php echo $goto; ?>" />
343 <input type="hidden" name="back" value="<?php echo isset($back) ? PMA_sanitize($back, true) : ''; ?>" />
344 <input type="hidden" name="reload" value="<?php echo isset($reload) ? PMA_sanitize($reload, true) : 0; ?>" />
345 <input type="hidden" name="purge" value="<?php echo isset($purge) ? PMA_sanitize($purge, true) : ''; ?>" />
346 <input type="hidden" name="dropped_column" value="<?php echo isset($dropped_column) ? PMA_sanitize($dropped_column, true) : ''; ?>" />
347 <input type="hidden" name="show_query" value="<?php echo isset($show_query) ? PMA_sanitize($show_query, true) : ''; ?>" />
348 <?php
349 echo '<fieldset class="confirmation">' . "\n"
350 .' <legend>' . __('Do you really want to ') . '</legend>'
351 .' <tt>' . htmlspecialchars($stripped_sql_query) . '</tt>' . "\n"
352 .'</fieldset>' . "\n"
353 .'<fieldset class="tblFooters">' . "\n";
355 <input type="submit" name="btnDrop" value="<?php echo __('Yes'); ?>" id="buttonYes" />
356 <input type="submit" name="btnDrop" value="<?php echo __('No'); ?>" id="buttonNo" />
357 <?php
358 echo '</fieldset>' . "\n"
359 . '</form>' . "\n";
362 * Displays the footer and exit
364 include './libraries/footer.inc.php';
365 } // end if $do_confirm
368 // Defines some variables
369 // A table has to be created, renamed, dropped -> navi frame should be reloaded
371 * @todo use the parser/analyzer
374 if (empty($reload)
375 && preg_match('/^(CREATE|ALTER|DROP)\s+(VIEW|TABLE|DATABASE|SCHEMA)\s+/i', $sql_query)
377 $reload = 1;
380 // SK -- Patch: $is_group added for use in calculation of total number of
381 // rows.
382 // $is_count is changed for more correct "LIMIT" clause
383 // appending in queries like
384 // "SELECT COUNT(...) FROM ... GROUP BY ..."
387 * @todo detect all this with the parser, to avoid problems finding
388 * those strings in comments or backquoted identifiers
391 $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;
392 if ($is_select) { // see line 141
393 $is_group = preg_match('@(GROUP[[:space:]]+BY|HAVING|SELECT[[:space:]]+DISTINCT)[[:space:]]+@i', $sql_query);
394 $is_func = ! $is_group && (preg_match('@[[:space:]]+(SUM|AVG|STD|STDDEV|MIN|MAX|BIT_OR|BIT_AND)\s*\(@i', $sql_query));
395 $is_count = ! $is_group && (preg_match('@^SELECT[[:space:]]+COUNT\((.*\.+)?.*\)@i', $sql_query));
396 $is_export = (preg_match('@[[:space:]]+INTO[[:space:]]+OUTFILE[[:space:]]+@i', $sql_query));
397 $is_analyse = (preg_match('@[[:space:]]+PROCEDURE[[:space:]]+ANALYSE@i', $sql_query));
398 } elseif (preg_match('@^EXPLAIN[[:space:]]+@i', $sql_query)) {
399 $is_explain = true;
400 } elseif (preg_match('@^DELETE[[:space:]]+@i', $sql_query)) {
401 $is_delete = true;
402 $is_affected = true;
403 } elseif (preg_match('@^(INSERT|LOAD[[:space:]]+DATA|REPLACE)[[:space:]]+@i', $sql_query)) {
404 $is_insert = true;
405 $is_affected = true;
406 if (preg_match('@^(REPLACE)[[:space:]]+@i', $sql_query)) {
407 $is_replace = true;
409 } elseif (preg_match('@^UPDATE[[:space:]]+@i', $sql_query)) {
410 $is_affected = true;
411 } elseif (preg_match('@^[[:space:]]*SHOW[[:space:]]+@i', $sql_query)) {
412 $is_show = true;
413 } elseif (preg_match('@^(CHECK|ANALYZE|REPAIR|OPTIMIZE)[[:space:]]+TABLE[[:space:]]+@i', $sql_query)) {
414 $is_maint = true;
417 // assign default full_sql_query
418 $full_sql_query = $sql_query;
420 // Handle remembered sorting order, only for single table query
421 if ($GLOBALS['cfg']['RememberSorting']
422 && ! ($is_count || $is_export || $is_func || $is_analyse)
423 && count($analyzed_sql[0]['select_expr']) == 0
424 && isset($analyzed_sql[0]['queryflags']['select_from'])
425 && count($analyzed_sql[0]['table_ref']) == 1
427 $pmatable = new PMA_Table($table, $db);
428 if (empty($analyzed_sql[0]['order_by_clause'])) {
429 $sorted_col = $pmatable->getUiProp(PMA_Table::PROP_SORTED_COLUMN);
430 if ($sorted_col) {
431 // retrieve the remembered sorting order for current table
432 $sql_order_to_append = ' ORDER BY ' . $sorted_col . ' ';
433 $full_sql_query = $analyzed_sql[0]['section_before_limit'] . $sql_order_to_append
434 . $analyzed_sql[0]['section_after_limit'];
436 // update the $analyzed_sql
437 $analyzed_sql[0]['section_before_limit'] .= $sql_order_to_append;
438 $analyzed_sql[0]['order_by_clause'] = $sorted_col;
440 } else {
441 // store the remembered table into session
442 $pmatable->setUiProp(PMA_Table::PROP_SORTED_COLUMN, $analyzed_sql[0]['order_by_clause']);
446 // Do append a "LIMIT" clause?
447 if ((! $cfg['ShowAll'] || $_SESSION['tmp_user_values']['max_rows'] != 'all')
448 && ! ($is_count || $is_export || $is_func || $is_analyse)
449 && isset($analyzed_sql[0]['queryflags']['select_from'])
450 && ! isset($analyzed_sql[0]['queryflags']['offset'])
451 && empty($analyzed_sql[0]['limit_clause'])
453 $sql_limit_to_append = ' LIMIT ' . $_SESSION['tmp_user_values']['pos']
454 . ', ' . $_SESSION['tmp_user_values']['max_rows'] . " ";
456 $full_sql_query = $analyzed_sql[0]['section_before_limit'] . "\n"
457 . $sql_limit_to_append . $analyzed_sql[0]['section_after_limit'];
459 * @todo pretty printing of this modified query
461 if (isset($display_query)) {
462 // if the analysis of the original query revealed that we found
463 // a section_after_limit, we now have to analyze $display_query
464 // to display it correctly
466 if (! empty($analyzed_sql[0]['section_after_limit'])
467 && trim($analyzed_sql[0]['section_after_limit']) != ';'
469 $analyzed_display_query = PMA_SQP_analyze(PMA_SQP_parse($display_query));
470 $display_query = $analyzed_display_query[0]['section_before_limit']
471 . "\n" . $sql_limit_to_append . $analyzed_display_query[0]['section_after_limit'];
477 if (strlen($db)) {
478 PMA_DBI_select_db($db);
481 // E x e c u t e t h e q u e r y
483 // Only if we didn't ask to see the php code (mikebeck)
484 if (isset($GLOBALS['show_as_php']) || ! empty($GLOBALS['validatequery'])) {
485 unset($result);
486 $num_rows = 0;
487 $unlim_num_rows = 0;
488 } else {
489 if (isset($_SESSION['profiling']) && PMA_profilingSupported()) {
490 PMA_DBI_query('SET PROFILING=1;');
493 // Measure query time.
494 $querytime_before = array_sum(explode(' ', microtime()));
496 $result = @PMA_DBI_try_query($full_sql_query, null, PMA_DBI_QUERY_STORE);
498 // If a stored procedure was called, there may be more results that are
499 // queued up and waiting to be flushed from the buffer. So let's do that.
500 while (true) {
501 if (! PMA_DBI_more_results()) {
502 break;
504 PMA_DBI_next_result();
507 $querytime_after = array_sum(explode(' ', microtime()));
509 $GLOBALS['querytime'] = $querytime_after - $querytime_before;
511 // Displays an error message if required and stop parsing the script
512 if ($error = PMA_DBI_getError()) {
513 if ($is_gotofile) {
514 if (strpos($goto, 'db_') === 0 && strlen($table)) {
515 $table = '';
517 $active_page = $goto;
518 $message = PMA_Message::rawError($error);
520 if ($GLOBALS['is_ajax_request'] == true) {
521 PMA_ajaxResponse($message, false);
525 * Go to target path.
527 include './' . PMA_securePath($goto);
528 } else {
529 $full_err_url = (preg_match('@^(db|tbl)_@', $err_url))
530 ? $err_url . '&amp;show_query=1&amp;sql_query=' . urlencode($sql_query)
531 : $err_url;
532 PMA_mysqlDie($error, $full_sql_query, '', $full_err_url);
534 exit;
536 unset($error);
538 // Gets the number of rows affected/returned
539 // (This must be done immediately after the query because
540 // mysql_affected_rows() reports about the last query done)
542 if (! $is_affected) {
543 $num_rows = ($result) ? @PMA_DBI_num_rows($result) : 0;
544 } elseif (! isset($num_rows)) {
545 $num_rows = @PMA_DBI_affected_rows();
548 // Grabs the profiling results
549 if (isset($_SESSION['profiling']) && PMA_profilingSupported()) {
550 $profiling_results = PMA_DBI_fetch_result('SHOW PROFILE;');
553 // Checks if the current database has changed
554 // This could happen if the user sends a query like "USE `database`;"
556 * commented out auto-switching to active database - really required?
557 * bug #1814718 win: table list disappears (mixed case db names)
558 * https://sourceforge.net/support/tracker.php?aid=1814718
559 * @todo RELEASE test and comit or rollback before release
560 $current_db = PMA_DBI_fetch_value('SELECT DATABASE()');
561 if ($db !== $current_db) {
562 $db = $current_db;
563 $reload = 1;
565 unset($current_db);
568 // tmpfile remove after convert encoding appended by Y.Kawada
569 if (function_exists('PMA_kanji_file_conv')
570 && (isset($textfile) && file_exists($textfile))
572 unlink($textfile);
575 // Counts the total number of rows for the same 'SELECT' query without the
576 // 'LIMIT' clause that may have been programatically added
578 if (empty($sql_limit_to_append)) {
579 $unlim_num_rows = $num_rows;
580 // if we did not append a limit, set this to get a correct
581 // "Showing rows..." message
582 //$_SESSION['tmp_user_values']['max_rows'] = 'all';
583 } elseif ($is_select) {
585 // c o u n t q u e r y
587 // If we are "just browsing", there is only one table,
588 // and no WHERE clause (or just 'WHERE 1 '),
589 // we do a quick count (which uses MaxExactCount) because
590 // SQL_CALC_FOUND_ROWS is not quick on large InnoDB tables
592 // However, do not count again if we did it previously
593 // due to $find_real_end == true
595 if (! $is_group
596 && ! isset($analyzed_sql[0]['queryflags']['union'])
597 && ! isset($analyzed_sql[0]['queryflags']['distinct'])
598 && ! isset($analyzed_sql[0]['table_ref'][1]['table_name'])
599 && (empty($analyzed_sql[0]['where_clause']) || $analyzed_sql[0]['where_clause'] == '1 ')
600 && ! isset($find_real_end)
603 // "j u s t b r o w s i n g"
604 $unlim_num_rows = PMA_Table::countRecords($db, $table);
606 } else { // n o t " j u s t b r o w s i n g "
608 // add select expression after the SQL_CALC_FOUND_ROWS
610 // for UNION, just adding SQL_CALC_FOUND_ROWS
611 // after the first SELECT works.
613 // take the left part, could be:
614 // SELECT
615 // (SELECT
616 $count_query = PMA_SQP_formatHtml($parsed_sql, 'query_only', 0, $analyzed_sql[0]['position_of_first_select'] + 1);
617 $count_query .= ' SQL_CALC_FOUND_ROWS ';
618 // add everything that was after the first SELECT
619 $count_query .= PMA_SQP_formatHtml($parsed_sql, 'query_only', $analyzed_sql[0]['position_of_first_select'] + 1);
620 // ensure there is no semicolon at the end of the
621 // count query because we'll probably add
622 // a LIMIT 1 clause after it
623 $count_query = rtrim($count_query);
624 $count_query = rtrim($count_query, ';');
626 // if using SQL_CALC_FOUND_ROWS, add a LIMIT to avoid
627 // long delays. Returned count will be complete anyway.
628 // (but a LIMIT would disrupt results in an UNION)
630 if (! isset($analyzed_sql[0]['queryflags']['union'])) {
631 $count_query .= ' LIMIT 1';
634 // run the count query
636 PMA_DBI_try_query($count_query);
637 // if (mysql_error()) {
638 // void.
639 // I tried the case
640 // (SELECT `User`, `Host`, `Db`, `Select_priv` FROM `db`)
641 // UNION (SELECT `User`, `Host`, "%" AS "Db",
642 // `Select_priv`
643 // FROM `user`) ORDER BY `User`, `Host`, `Db`;
644 // and although the generated count_query is wrong
645 // the SELECT FOUND_ROWS() work! (maybe it gets the
646 // count from the latest query that worked)
648 // another case where the count_query is wrong:
649 // SELECT COUNT(*), f1 from t1 group by f1
650 // and you click to sort on count(*)
651 // }
652 $unlim_num_rows = PMA_DBI_fetch_value('SELECT FOUND_ROWS()');
653 } // end else "just browsing"
655 } else { // not $is_select
656 $unlim_num_rows = 0;
657 } // end rows total count
659 // if a table or database gets dropped, check column comments.
660 if (isset($purge) && $purge == '1') {
662 * Cleanup relations.
664 include_once './libraries/relation_cleanup.lib.php';
666 if (strlen($table) && strlen($db)) {
667 PMA_relationsCleanupTable($db, $table);
668 } elseif (strlen($db)) {
669 PMA_relationsCleanupDatabase($db);
670 } else {
671 // VOID. No DB/Table gets deleted.
672 } // end if relation-stuff
673 } // end if ($purge)
675 // If a column gets dropped, do relation magic.
676 if (isset($dropped_column) && strlen($db) && strlen($table) && ! empty($dropped_column)) {
677 include_once './libraries/relation_cleanup.lib.php';
678 PMA_relationsCleanupColumn($db, $table, $dropped_column);
679 // to refresh the list of indexes (Ajax mode)
680 $extra_data['indexes_list'] = PMA_Index::getView($table, $db);
681 } // end if column was dropped
682 } // end else "didn't ask to see php code"
684 // No rows returned -> move back to the calling page
685 if ((0 == $num_rows && 0 == $unlim_num_rows) || $is_affected) {
686 if ($is_delete) {
687 $message = PMA_Message::deleted_rows($num_rows);
688 } elseif ($is_insert) {
689 if ($is_replace) {
690 /* For replace we get DELETED + INSERTED row count, so we have to call it affected */
691 $message = PMA_Message::affected_rows($num_rows);
692 } else {
693 $message = PMA_Message::inserted_rows($num_rows);
695 $insert_id = PMA_DBI_insert_id();
696 if ($insert_id != 0) {
697 // insert_id is id of FIRST record inserted in one insert, so if we inserted multiple rows, we had to increment this
698 $message->addMessage('[br]');
699 // need to use a temporary because the Message class
700 // currently supports adding parameters only to the first
701 // message
702 $_inserted = PMA_Message::notice(__('Inserted row id: %1$d'));
703 $_inserted->addParam($insert_id + $num_rows - 1);
704 $message->addMessage($_inserted);
706 } elseif ($is_affected) {
707 $message = PMA_Message::affected_rows($num_rows);
709 // Ok, here is an explanation for the !$is_select.
710 // The form generated by sql_query_form.lib.php
711 // and db_sql.php has many submit buttons
712 // on the same form, and some confusion arises from the
713 // fact that $message_to_show is sent for every case.
714 // The $message_to_show containing a success message and sent with
715 // the form should not have priority over errors
716 } elseif (! empty($message_to_show) && ! $is_select) {
717 $message = PMA_Message::rawSuccess(htmlspecialchars($message_to_show));
718 } elseif (! empty($GLOBALS['show_as_php'])) {
719 $message = PMA_Message::success(__('Showing as PHP code'));
720 } elseif (isset($GLOBALS['show_as_php'])) {
721 /* User disable showing as PHP, query is only displayed */
722 $message = PMA_Message::notice(__('Showing SQL query'));
723 } elseif (! empty($GLOBALS['validatequery'])) {
724 $message = PMA_Message::notice(__('Validated SQL'));
725 } else {
726 $message = PMA_Message::success(__('MySQL returned an empty result set (i.e. zero rows).'));
729 if (isset($GLOBALS['querytime'])) {
730 $_querytime = PMA_Message::notice(__('Query took %01.4f sec'));
731 $_querytime->addParam($GLOBALS['querytime']);
732 $message->addMessage('(');
733 $message->addMessage($_querytime);
734 $message->addMessage(')');
737 if ($GLOBALS['is_ajax_request'] == true) {
738 if ($cfg['ShowSQL']) {
739 $extra_data['sql_query'] = PMA_showMessage($message, $GLOBALS['sql_query'], 'success');
741 if (isset($GLOBALS['reload']) && $GLOBALS['reload'] == 1) {
742 $extra_data['reload'] = 1;
743 $extra_data['db'] = $GLOBALS['db'];
745 PMA_ajaxResponse($message, $message->isSuccess(), (isset($extra_data) ? $extra_data : ''));
748 if ($is_gotofile) {
749 $goto = PMA_securePath($goto);
750 // Checks for a valid target script
751 $is_db = $is_table = false;
752 if (isset($_REQUEST['purge']) && $_REQUEST['purge'] == '1') {
753 $table = '';
754 unset($url_params['table']);
756 include 'libraries/db_table_exists.lib.php';
758 if (strpos($goto, 'tbl_') === 0 && ! $is_table) {
759 if (strlen($table)) {
760 $table = '';
762 $goto = 'db_sql.php';
764 if (strpos($goto, 'db_') === 0 && ! $is_db) {
765 if (strlen($db)) {
766 $db = '';
768 $goto = 'main.php';
770 // Loads to target script
771 if ($goto != 'main.php') {
772 include_once './libraries/header.inc.php';
774 $active_page = $goto;
775 include './' . $goto;
776 } else {
777 // avoid a redirect loop when last record was deleted
778 if (0 == $num_rows && 'sql.php' == $cfg['DefaultTabTable']) {
779 $goto = str_replace('sql.php', 'tbl_structure.php', $goto);
781 PMA_sendHeaderLocation($cfg['PmaAbsoluteUri'] . str_replace('&amp;', '&', $goto) . '&message=' . urlencode($message));
782 } // end else
783 exit();
784 // end no rows returned
785 } else {
786 // At least one row is returned -> displays a table with results
787 //If we are retrieving the full value of a truncated field or the original
788 // value of a transformed field, show it here and exit
789 if ($GLOBALS['grid_edit'] == true && $GLOBALS['cfg']['AjaxEnable']) {
790 $row = PMA_DBI_fetch_row($result);
791 $extra_data = array();
792 $extra_data['value'] = $row[0];
793 PMA_ajaxResponse(null, true, $extra_data);
796 if (isset($_REQUEST['ajax_request']) && isset($_REQUEST['table_maintenance'])) {
797 $GLOBALS['js_include'][] = 'functions.js';
798 $GLOBALS['js_include'][] = 'makegrid.js';
799 $GLOBALS['js_include'][] = 'sql.js';
801 // Gets the list of fields properties
802 if (isset($result) && $result) {
803 $fields_meta = PMA_DBI_get_fields_meta($result);
804 $fields_cnt = count($fields_meta);
807 if (empty($disp_mode)) {
808 // see the "PMA_setDisplayMode()" function in
809 // libraries/display_tbl.lib.php
810 $disp_mode = 'urdr111101';
813 // hide edit and delete links for information_schema
814 if (PMA_is_system_schema($db)) {
815 $disp_mode = 'nnnn110111';
818 $message = PMA_Message::success($message);
819 echo PMA_showMessage($message, $GLOBALS['sql_query'], 'success');
820 PMA_displayTable($result, $disp_mode, $analyzed_sql);
821 exit();
824 // Displays the headers
825 if (isset($show_query)) {
826 unset($show_query);
828 if (isset($printview) && $printview == '1') {
829 include_once './libraries/header_printview.inc.php';
830 } else {
832 $GLOBALS['js_include'][] = 'functions.js';
833 $GLOBALS['js_include'][] = 'makegrid.js';
834 $GLOBALS['js_include'][] = 'sql.js';
836 unset($message);
838 if (! $GLOBALS['is_ajax_request'] || ! $GLOBALS['cfg']['AjaxEnable']) {
839 if (strlen($table)) {
840 include './libraries/tbl_common.php';
841 $url_query .= '&amp;goto=tbl_sql.php&amp;back=tbl_sql.php';
842 include './libraries/tbl_info.inc.php';
843 include './libraries/tbl_links.inc.php';
844 } elseif (strlen($db)) {
845 include './libraries/db_common.inc.php';
846 include './libraries/db_info.inc.php';
847 } else {
848 include './libraries/server_common.inc.php';
849 include './libraries/server_links.inc.php';
851 } else {
852 include_once './libraries/header.inc.php';
853 //we don't need to buffer the output in PMA_showMessage here.
854 //set a global variable and check against it in the function
855 $GLOBALS['buffer_message'] = false;
859 if (strlen($db)) {
860 $cfgRelation = PMA_getRelationsParam();
863 // Gets the list of fields properties
864 if (isset($result) && $result) {
865 $fields_meta = PMA_DBI_get_fields_meta($result);
866 $fields_cnt = count($fields_meta);
869 if (! $GLOBALS['is_ajax_request']) {
870 //begin the sqlqueryresults div here. container div
871 echo '<div id="sqlqueryresults"';
872 if ($GLOBALS['cfg']['AjaxEnable']) {
873 echo ' class="ajax"';
875 echo '>';
878 // Display previous update query (from tbl_replace)
879 if (isset($disp_query) && $cfg['ShowSQL'] == true) {
880 PMA_showMessage($disp_message, $disp_query, 'success');
883 if (isset($profiling_results)) {
884 // pma_token/url_query needed for chart export
886 <script type="text/javascript">
887 pma_token = '<?php echo $_SESSION[' PMA_token ']; ?>';
888 url_query = '<?php echo isset($url_query)?$url_query:PMA_generate_common_url($db);?>';
889 $(document).ready(makeProfilingChart);
890 </script>
891 <?php
892 echo '<fieldset><legend>' . __('Profiling') . '</legend>' . "\n";
893 echo '<div style="float: left;">';
894 echo '<table>' . "\n";
895 echo ' <tr>' . "\n";
896 echo ' <th>' . __('Status') . PMA_showMySQLDocu('general-thread-states', 'general-thread-states') . '</th>' . "\n";
897 echo ' <th>' . __('Time') . '</th>' . "\n";
898 echo ' </tr>' . "\n";
900 $chart_json = Array();
901 foreach ($profiling_results as $one_result) {
902 echo ' <tr>' . "\n";
903 echo '<td>' . ucwords($one_result['Status']) . '</td>' . "\n";
904 echo '<td align="right">' . (PMA_formatNumber($one_result['Duration'], 3, 1)) . 's</td>' . "\n";
905 $chart_json[ucwords($one_result['Status'])] = $one_result['Duration'];
908 echo '</table>' . "\n";
909 echo '</div>';
910 //require_once './libraries/chart.lib.php';
911 echo '<div id="profilingchart" style="display:none;">';
912 //PMA_chart_profiling($profiling_results);
913 echo json_encode($chart_json);
914 echo '</div>';
915 echo '</fieldset>' . "\n";
918 // Displays the results in a table
919 if (empty($disp_mode)) {
920 // see the "PMA_setDisplayMode()" function in
921 // libraries/display_tbl.lib.php
922 $disp_mode = 'urdr111101';
925 // hide edit and delete links for information_schema
926 if (PMA_is_system_schema($db)) {
927 $disp_mode = 'nnnn110111';
930 if (isset($label)) {
931 $message = PMA_message::success(__('Bookmark %s created'));
932 $message->addParam($label);
933 $message->display();
936 PMA_displayTable($result, $disp_mode, $analyzed_sql);
937 PMA_DBI_free_result($result);
939 // BEGIN INDEX CHECK See if indexes should be checked.
940 if (isset($query_type) && $query_type == 'check_tbl' && isset($selected) && is_array($selected)) {
941 foreach ($selected as $idx => $tbl_name) {
942 $check = PMA_Index::findDuplicates($tbl_name, $db);
943 if (! empty($check)) {
944 printf(__('Problems with indexes of table `%s`'), $tbl_name);
945 echo $check;
948 } // End INDEX CHECK
950 // Bookmark support if required
951 if ($disp_mode[7] == '1'
952 && (! empty($cfg['Bookmark']) && empty($id_bookmark))
953 && ! empty($sql_query)
955 echo "\n";
957 $goto = 'sql.php?'
958 . PMA_generate_common_url($db, $table)
959 . '&amp;sql_query=' . urlencode($sql_query)
960 . '&amp;id_bookmark=1';
963 <form action="sql.php" method="post" onsubmit="return emptyFormElements(this, 'fields[label]');">
964 <?php echo PMA_generate_common_hidden_inputs(); ?>
965 <input type="hidden" name="goto" value="<?php echo $goto; ?>" />
966 <input type="hidden" name="fields[dbase]" value="<?php echo htmlspecialchars($db); ?>" />
967 <input type="hidden" name="fields[user]" value="<?php echo $cfg['Bookmark']['user']; ?>" />
968 <input type="hidden" name="fields[query]" value="<?php echo urlencode(isset($complete_query) ? $complete_query : $sql_query); ?>" />
969 <fieldset>
970 <legend><?php
971 echo PMA_getIcon('b_bookmark.png', __('Bookmark this SQL query'), true);
973 </legend>
975 <div class="formelement">
976 <label for="fields_label_"><?php echo __('Label'); ?>:</label>
977 <input type="text" id="fields_label_" name="fields[label]" value="" />
978 </div>
980 <div class="formelement">
981 <input type="checkbox" name="bkm_all_users" id="bkm_all_users" value="true" />
982 <label for="bkm_all_users"><?php echo __('Let every user access this bookmark'); ?></label>
983 </div>
985 <div class="clearfloat"></div>
986 </fieldset>
987 <fieldset class="tblFooters">
988 <input type="submit" name="store_bkm" value="<?php echo __('Bookmark this SQL query'); ?>" />
989 </fieldset>
990 </form>
991 <?php
992 } // end bookmark support
994 // Do print the page if required
995 if (isset($printview) && $printview == '1') {
996 PMA_printButton();
997 } // end print case
999 if ($GLOBALS['is_ajax_request'] != true) {
1000 echo '</div>'; // end sqlqueryresults div
1002 } // end rows returned
1005 * Displays the footer
1007 if (! isset($_REQUEST['table_maintenance'])) {
1008 include './libraries/footer.inc.php';