Advisor: don't run 'MyISAM concurrent inserts' on Drizzle
[phpmyadmin.git] / sql.php
blob6b67b96561dd057b78a25fc97b919d59db9980ef
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';
21 // required for GIS editor loaded via AJAX
22 $GLOBALS['js_include'][] = 'gis_data_editor.js';
23 $GLOBALS['js_include'][] = 'jquery/jquery.svg.js';
24 $GLOBALS['js_include'][] = 'jquery/jquery.mousewheel.js';
25 $GLOBALS['js_include'][] = 'jquery/jquery.event.drag-2.0.min.js';
26 $GLOBALS['js_include'][] = 'tbl_gis_visualization.js';
27 $GLOBALS['js_include'][] = 'openlayers/OpenLayers.js';
28 $GLOBALS['js_include'][] = 'OpenStreetMap.js';
30 if (isset($_SESSION['profiling'])) {
31 $GLOBALS['js_include'][] = 'highcharts/highcharts.js';
32 /* Files required for chart exporting */
33 $GLOBALS['js_include'][] = 'highcharts/exporting.js';
34 /* < IE 9 doesn't support canvas natively */
35 if (PMA_USR_BROWSER_AGENT == 'IE' && PMA_USR_BROWSER_VER < 9) {
36 $GLOBALS['js_include'][] = 'canvg/flashcanvas.js';
38 $GLOBALS['js_include'][] = 'canvg/canvg.js';
41 /**
42 * Defines the url to return to in case of error in a sql statement
44 // Security checkings
45 if (! empty($goto)) {
46 $is_gotofile = preg_replace('@^([^?]+).*$@s', '\\1', $goto);
47 if (! @file_exists('./' . $is_gotofile)) {
48 unset($goto);
49 } else {
50 $is_gotofile = ($is_gotofile == $goto);
52 } else {
53 $goto = (! strlen($table)) ? $cfg['DefaultTabDatabase'] : $cfg['DefaultTabTable'];
54 $is_gotofile = true;
55 } // end if
57 if (! isset($err_url)) {
58 $err_url = (!empty($back) ? $back : $goto)
59 . '?' . PMA_generate_common_url($db)
60 . ((strpos(' ' . $goto, 'db_') != 1 && strlen($table)) ? '&amp;table=' . urlencode($table) : '');
61 } // end if
63 // Coming from a bookmark dialog
64 if (isset($fields['query'])) {
65 $sql_query = $fields['query'];
68 // This one is just to fill $db
69 if (isset($fields['dbase'])) {
70 $db = $fields['dbase'];
73 /**
74 * During grid edit, if we have a relational field, show the dropdown for it
76 * Logic taken from libraries/display_tbl_lib.php
78 * This doesn't seem to be the right place to do this, but I can't think of any
79 * better place either.
81 if (isset($_REQUEST['get_relational_values']) && $_REQUEST['get_relational_values'] == true) {
82 require_once 'libraries/relation.lib.php';
84 $column = $_REQUEST['column'];
85 $foreigners = PMA_getForeigners($db, $table, $column);
87 $display_field = PMA_getDisplayField($foreigners[$column]['foreign_db'], $foreigners[$column]['foreign_table']);
89 $foreignData = PMA_getForeignData($foreigners, $column, false, '', '');
91 if ($_SESSION['tmp_user_values']['relational_display'] == 'D'
92 && (isset($display_field) && strlen($display_field)
93 && (isset($_REQUEST['relation_key_or_display_column']) && $_REQUEST['relation_key_or_display_column']))) {
94 $curr_value = $_REQUEST['relation_key_or_display_column'];
95 } else {
96 $curr_value = $_REQUEST['curr_value'];
98 if ($foreignData['disp_row'] == null) {
99 //Handle the case when number of values is more than $cfg['ForeignKeyMaxLimit']
100 $_url_params = array(
101 'db' => $db,
102 'table' => $table,
103 'field' => $column
106 $dropdown = '<span class="curr_value">' . htmlspecialchars($_REQUEST['curr_value']) . '</span> <a href="browse_foreigners.php' . PMA_generate_common_url($_url_params) . '"'
107 . ' target="_blank" class="browse_foreign" '
108 .'>' . __('Browse foreign values') . '</a>';
109 } else {
110 $dropdown = PMA_foreignDropdown($foreignData['disp_row'], $foreignData['foreign_field'], $foreignData['foreign_display'], $curr_value, $cfg['ForeignKeyMaxLimit']);
111 $dropdown = '<select>' . $dropdown . '</select>';
114 $extra_data['dropdown'] = $dropdown;
115 PMA_ajaxResponse(NULL, true, $extra_data);
119 * Just like above, find possible values for enum fields during grid edit.
121 * Logic taken from libraries/display_tbl_lib.php
123 if (isset($_REQUEST['get_enum_values']) && $_REQUEST['get_enum_values'] == true) {
124 $field_info_query = PMA_DBI_get_columns_sql($db, $table, $_REQUEST['column']);
126 $field_info_result = PMA_DBI_fetch_result($field_info_query, null, null, null, PMA_DBI_QUERY_STORE);
128 $search = array('enum', '(', ')', "'");
130 $values = explode(',', str_replace($search, '', $field_info_result[0]['Type']));
132 $dropdown = '<option value="">&nbsp;</option>';
133 foreach ($values as $value) {
134 $dropdown .= '<option value="' . htmlspecialchars($value) . '"';
135 if ($value == $_REQUEST['curr_value']) {
136 $dropdown .= ' selected="selected"';
138 $dropdown .= '>' . $value . '</option>';
141 $dropdown = '<select>' . $dropdown . '</select>';
143 $extra_data['dropdown'] = $dropdown;
144 PMA_ajaxResponse(NULL, true, $extra_data);
148 * Find possible values for set fields during grid edit.
150 if (isset($_REQUEST['get_set_values']) && $_REQUEST['get_set_values'] == true) {
151 $field_info_query = PMA_DBI_get_columns_sql($db, $table, $_REQUEST['column']);
153 $field_info_result = PMA_DBI_fetch_result($field_info_query, null, null, null, PMA_DBI_QUERY_STORE);
155 $selected_values = explode(',', $_REQUEST['curr_value']);
157 $search = array('set', '(', ')', "'");
158 $values = explode(',', str_replace($search, '', $field_info_result[0]['Type']));
160 $select = '';
161 foreach ($values as $value) {
162 $select .= '<option value="' . htmlspecialchars($value) . '"';
163 if (in_array($value, $selected_values, true)) {
164 $select .= ' selected="selected"';
166 $select .= '>' . $value . '</option>';
169 $select_size = (sizeof($values) > 10) ? 10 : sizeof($values);
170 $select = '<select multiple="multiple" size="' . $select_size . '">' . $select . '</select>';
172 $extra_data['select'] = $select;
173 PMA_ajaxResponse(NULL, true, $extra_data);
177 * Check ajax request to set the column order
179 if (isset($_REQUEST['set_col_prefs']) && $_REQUEST['set_col_prefs'] == true) {
180 $pmatable = new PMA_Table($table, $db);
181 $retval = false;
183 // set column order
184 if (isset($_REQUEST['col_order'])) {
185 $col_order = explode(',', $_REQUEST['col_order']);
186 $retval = $pmatable->setUiProp(PMA_Table::PROP_COLUMN_ORDER, $col_order, $_REQUEST['table_create_time']);
187 if ($retval !== true) {
188 PMA_ajaxResponse($retval->getString(), false);
193 // set column visibility
194 if (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 ($retval !== true) {
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 require_once './libraries/bookmark.lib.php';
209 $book_sql_query = PMA_Bookmark_get($db, '\'' . PMA_sqlAddSlashes($table) . '\'',
210 'label', false, true);
212 if (! empty($book_sql_query)) {
213 $GLOBALS['using_bookmark_message'] = PMA_message::notice(__('Using bookmark "%s" as default browse query.'));
214 $GLOBALS['using_bookmark_message']->addParam($table);
215 $GLOBALS['using_bookmark_message']->addMessage(PMA_showDocu('faq6_22'));
216 $sql_query = $book_sql_query;
217 } else {
218 $sql_query = 'SELECT * FROM ' . PMA_backquote($table);
220 unset($book_sql_query);
222 // set $goto to what will be displayed if query returns 0 rows
223 $goto = 'tbl_structure.php';
224 } else {
225 // Now we can check the parameters
226 PMA_checkParameters(array('sql_query'));
229 // instead of doing the test twice
230 $is_drop_database = preg_match('/DROP[[:space:]]+(DATABASE|SCHEMA)[[:space:]]+/i',
231 $sql_query);
234 * Check rights in case of DROP DATABASE
236 * This test may be bypassed if $is_js_confirmed = 1 (already checked with js)
237 * but since a malicious user may pass this variable by url/form, we don't take
238 * into account this case.
240 if (!defined('PMA_CHK_DROP')
241 && !$cfg['AllowUserDropDatabase']
242 && $is_drop_database
243 && !$is_superuser) {
244 require_once './libraries/header.inc.php';
245 PMA_mysqlDie(__('"DROP DATABASE" statements are disabled.'), '', '', $err_url);
246 } // end if
248 require_once './libraries/display_tbl.lib.php';
249 PMA_displayTable_checkConfigParams();
252 * Need to find the real end of rows?
254 if (isset($find_real_end) && $find_real_end) {
255 $unlim_num_rows = PMA_Table::countRecords($db, $table, $force_exact = true);
256 $_SESSION['tmp_user_values']['pos'] = @((ceil($unlim_num_rows / $_SESSION['tmp_user_values']['max_rows']) - 1) * $_SESSION['tmp_user_values']['max_rows']);
261 * Bookmark add
263 if (isset($store_bkm)) {
264 PMA_Bookmark_save($fields, (isset($bkm_all_users) && $bkm_all_users == 'true' ? true : false));
265 // go back to sql.php to redisplay query; do not use &amp; in this case:
266 PMA_sendHeaderLocation($cfg['PmaAbsoluteUri'] . $goto . '&label=' . $fields['label']);
267 } // end if
270 * Parse and analyze the query
272 require_once './libraries/parse_analyze.lib.php';
275 * Sets or modifies the $goto variable if required
277 if ($goto == 'sql.php') {
278 $is_gotofile = false;
279 $goto = 'sql.php?'
280 . PMA_generate_common_url($db, $table)
281 . '&amp;sql_query=' . urlencode($sql_query);
282 } // end if
286 * Go back to further page if table should not be dropped
288 if (isset($btnDrop) && $btnDrop == __('No')) {
289 if (!empty($back)) {
290 $goto = $back;
292 if ($is_gotofile) {
293 if (strpos($goto, 'db_') === 0 && strlen($table)) {
294 $table = '';
296 $active_page = $goto;
297 require './' . PMA_securePath($goto);
298 } else {
299 PMA_sendHeaderLocation($cfg['PmaAbsoluteUri'] . str_replace('&amp;', '&', $goto));
301 exit();
302 } // end if
306 * Displays the confirm page if required
308 * This part of the script is bypassed if $is_js_confirmed = 1 (already checked
309 * with js) because possible security issue is not so important here: at most,
310 * the confirm message isn't displayed.
312 * Also bypassed if only showing php code.or validating a SQL query
314 if (! $cfg['Confirm'] || isset($_REQUEST['is_js_confirmed']) || isset($btnDrop)
315 // if we are coming from a "Create PHP code" or a "Without PHP Code"
316 // dialog, we won't execute the query anyway, so don't confirm
317 || isset($GLOBALS['show_as_php'])
318 || !empty($GLOBALS['validatequery'])) {
319 $do_confirm = false;
320 } else {
321 $do_confirm = isset($analyzed_sql[0]['queryflags']['need_confirm']);
324 if ($do_confirm) {
325 $stripped_sql_query = $sql_query;
326 require_once './libraries/header.inc.php';
327 if ($is_drop_database) {
328 echo '<h1 class="error">' . __('You are about to DESTROY a complete database!') . '</h1>';
330 echo '<form action="sql.php" method="post">' . "\n"
331 .PMA_generate_common_hidden_inputs($db, $table);
333 <input type="hidden" name="sql_query" value="<?php echo htmlspecialchars($sql_query); ?>" />
334 <input type="hidden" name="message_to_show" value="<?php echo isset($message_to_show) ? PMA_sanitize($message_to_show, true) : ''; ?>" />
335 <input type="hidden" name="goto" value="<?php echo $goto; ?>" />
336 <input type="hidden" name="back" value="<?php echo isset($back) ? PMA_sanitize($back, true) : ''; ?>" />
337 <input type="hidden" name="reload" value="<?php echo isset($reload) ? PMA_sanitize($reload, true) : 0; ?>" />
338 <input type="hidden" name="purge" value="<?php echo isset($purge) ? PMA_sanitize($purge, true) : ''; ?>" />
339 <input type="hidden" name="dropped_column" value="<?php echo isset($dropped_column) ? PMA_sanitize($dropped_column, true) : ''; ?>" />
340 <input type="hidden" name="show_query" value="<?php echo isset($show_query) ? PMA_sanitize($show_query, true) : ''; ?>" />
341 <?php
342 echo '<fieldset class="confirmation">' . "\n"
343 .' <legend>' . __('Do you really want to ') . '</legend>'
344 .' <tt>' . htmlspecialchars($stripped_sql_query) . '</tt>' . "\n"
345 .'</fieldset>' . "\n"
346 .'<fieldset class="tblFooters">' . "\n";
348 <input type="submit" name="btnDrop" value="<?php echo __('Yes'); ?>" id="buttonYes" />
349 <input type="submit" name="btnDrop" value="<?php echo __('No'); ?>" id="buttonNo" />
350 <?php
351 echo '</fieldset>' . "\n"
352 . '</form>' . "\n";
355 * Displays the footer and exit
357 require './libraries/footer.inc.php';
358 } // end if $do_confirm
361 // Defines some variables
362 // A table has to be created, renamed, dropped -> navi frame should be reloaded
364 * @todo use the parser/analyzer
367 if (empty($reload)
368 && preg_match('/^(CREATE|ALTER|DROP)\s+(VIEW|TABLE|DATABASE|SCHEMA)\s+/i', $sql_query)) {
369 $reload = 1;
372 // SK -- Patch: $is_group added for use in calculation of total number of
373 // rows.
374 // $is_count is changed for more correct "LIMIT" clause
375 // appending in queries like
376 // "SELECT COUNT(...) FROM ... GROUP BY ..."
379 * @todo detect all this with the parser, to avoid problems finding
380 * those strings in comments or backquoted identifiers
383 $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;
384 if ($is_select) { // see line 141
385 $is_group = preg_match('@(GROUP[[:space:]]+BY|HAVING|SELECT[[:space:]]+DISTINCT)[[:space:]]+@i', $sql_query);
386 $is_func = !$is_group && (preg_match('@[[:space:]]+(SUM|AVG|STD|STDDEV|MIN|MAX|BIT_OR|BIT_AND)\s*\(@i', $sql_query));
387 $is_count = !$is_group && (preg_match('@^SELECT[[:space:]]+COUNT\((.*\.+)?.*\)@i', $sql_query));
388 $is_export = (preg_match('@[[:space:]]+INTO[[:space:]]+OUTFILE[[:space:]]+@i', $sql_query));
389 $is_analyse = (preg_match('@[[:space:]]+PROCEDURE[[:space:]]+ANALYSE@i', $sql_query));
390 } elseif (preg_match('@^EXPLAIN[[:space:]]+@i', $sql_query)) {
391 $is_explain = true;
392 } elseif (preg_match('@^DELETE[[:space:]]+@i', $sql_query)) {
393 $is_delete = true;
394 $is_affected = true;
395 } elseif (preg_match('@^(INSERT|LOAD[[:space:]]+DATA|REPLACE)[[:space:]]+@i', $sql_query)) {
396 $is_insert = true;
397 $is_affected = true;
398 if (preg_match('@^(REPLACE)[[:space:]]+@i', $sql_query)) {
399 $is_replace = true;
401 } elseif (preg_match('@^UPDATE[[:space:]]+@i', $sql_query)) {
402 $is_affected = true;
403 } elseif (preg_match('@^[[:space:]]*SHOW[[:space:]]+@i', $sql_query)) {
404 $is_show = true;
405 } elseif (preg_match('@^(CHECK|ANALYZE|REPAIR|OPTIMIZE)[[:space:]]+TABLE[[:space:]]+@i', $sql_query)) {
406 $is_maint = true;
409 // assign default full_sql_query
410 $full_sql_query = $sql_query;
412 // Handle remembered sorting order, only for single table query
413 if ($GLOBALS['cfg']['RememberSorting']
414 && ! ($is_count || $is_export || $is_func || $is_analyse)
415 && count($analyzed_sql[0]['select_expr']) == 0
416 && isset($analyzed_sql[0]['queryflags']['select_from'])
417 && count($analyzed_sql[0]['table_ref']) == 1
419 $pmatable = new PMA_Table($table, $db);
420 if (empty($analyzed_sql[0]['order_by_clause'])) {
421 $sorted_col = $pmatable->getUiProp(PMA_Table::PROP_SORTED_COLUMN);
422 if ($sorted_col) {
423 // retrieve the remembered sorting order for current table
424 $sql_order_to_append = ' ORDER BY ' . $sorted_col . ' ';
425 $full_sql_query = $analyzed_sql[0]['section_before_limit'] . $sql_order_to_append . $analyzed_sql[0]['section_after_limit'];
427 // update the $analyzed_sql
428 $analyzed_sql[0]['section_before_limit'] .= $sql_order_to_append;
429 $analyzed_sql[0]['order_by_clause'] = $sorted_col;
431 } else {
432 // store the remembered table into session
433 $pmatable->setUiProp(PMA_Table::PROP_SORTED_COLUMN, $analyzed_sql[0]['order_by_clause']);
437 // Do append a "LIMIT" clause?
438 if ((! $cfg['ShowAll'] || $_SESSION['tmp_user_values']['max_rows'] != 'all')
439 && ! ($is_count || $is_export || $is_func || $is_analyse)
440 && isset($analyzed_sql[0]['queryflags']['select_from'])
441 && ! isset($analyzed_sql[0]['queryflags']['offset'])
442 && empty($analyzed_sql[0]['limit_clause'])
444 $sql_limit_to_append = ' LIMIT ' . $_SESSION['tmp_user_values']['pos'] . ', ' . $_SESSION['tmp_user_values']['max_rows'] . " ";
446 $full_sql_query = $analyzed_sql[0]['section_before_limit'] . "\n" . $sql_limit_to_append . $analyzed_sql[0]['section_after_limit'];
448 * @todo pretty printing of this modified query
450 if (isset($display_query)) {
451 // if the analysis of the original query revealed that we found
452 // a section_after_limit, we now have to analyze $display_query
453 // to display it correctly
455 if (!empty($analyzed_sql[0]['section_after_limit']) && trim($analyzed_sql[0]['section_after_limit']) != ';') {
456 $analyzed_display_query = PMA_SQP_analyze(PMA_SQP_parse($display_query));
457 $display_query = $analyzed_display_query[0]['section_before_limit'] . "\n" . $sql_limit_to_append . $analyzed_display_query[0]['section_after_limit'];
463 if (strlen($db)) {
464 PMA_DBI_select_db($db);
467 // E x e c u t e t h e q u e r y
469 // Only if we didn't ask to see the php code (mikebeck)
470 if (isset($GLOBALS['show_as_php']) || !empty($GLOBALS['validatequery'])) {
471 unset($result);
472 $num_rows = 0;
473 } else {
474 if (isset($_SESSION['profiling']) && PMA_profilingSupported()) {
475 PMA_DBI_query('SET PROFILING=1;');
478 // Measure query time.
479 $querytime_before = array_sum(explode(' ', microtime()));
481 $result = @PMA_DBI_try_query($full_sql_query, null, PMA_DBI_QUERY_STORE);
483 // If a stored procedure was called, there may be more results that are
484 // queued up and waiting to be flushed from the buffer. So let's do that.
485 while (true) {
486 if (! PMA_DBI_more_results()) {
487 break;
489 PMA_DBI_next_result();
492 $querytime_after = array_sum(explode(' ', microtime()));
494 $GLOBALS['querytime'] = $querytime_after - $querytime_before;
496 // Displays an error message if required and stop parsing the script
497 if ($error = PMA_DBI_getError()) {
498 if ($is_gotofile) {
499 if (strpos($goto, 'db_') === 0 && strlen($table)) {
500 $table = '';
502 $active_page = $goto;
503 $message = PMA_Message::rawError($error);
505 if ($GLOBALS['is_ajax_request'] == true) {
506 PMA_ajaxResponse($message, false);
510 * Go to target path.
512 require './' . PMA_securePath($goto);
513 } else {
514 $full_err_url = (preg_match('@^(db|tbl)_@', $err_url))
515 ? $err_url . '&amp;show_query=1&amp;sql_query=' . urlencode($sql_query)
516 : $err_url;
517 PMA_mysqlDie($error, $full_sql_query, '', $full_err_url);
519 exit;
521 unset($error);
523 // Gets the number of rows affected/returned
524 // (This must be done immediately after the query because
525 // mysql_affected_rows() reports about the last query done)
527 if (!$is_affected) {
528 $num_rows = ($result) ? @PMA_DBI_num_rows($result) : 0;
529 } elseif (! isset($num_rows)) {
530 $num_rows = @PMA_DBI_affected_rows();
533 // Grabs the profiling results
534 if (isset($_SESSION['profiling']) && PMA_profilingSupported()) {
535 $profiling_results = PMA_DBI_fetch_result('SHOW PROFILE;');
538 // Checks if the current database has changed
539 // This could happen if the user sends a query like "USE `database`;"
541 * commented out auto-switching to active database - really required?
542 * bug #1814718 win: table list disappears (mixed case db names)
543 * https://sourceforge.net/support/tracker.php?aid=1814718
544 * @todo RELEASE test and comit or rollback before release
545 $current_db = PMA_DBI_fetch_value('SELECT DATABASE()');
546 if ($db !== $current_db) {
547 $db = $current_db;
548 $reload = 1;
550 unset($current_db);
553 // tmpfile remove after convert encoding appended by Y.Kawada
554 if (function_exists('PMA_kanji_file_conv')
555 && (isset($textfile) && file_exists($textfile))) {
556 unlink($textfile);
559 // Counts the total number of rows for the same 'SELECT' query without the
560 // 'LIMIT' clause that may have been programatically added
562 if (empty($sql_limit_to_append)) {
563 $unlim_num_rows = $num_rows;
564 // if we did not append a limit, set this to get a correct
565 // "Showing rows..." message
566 //$_SESSION['tmp_user_values']['max_rows'] = 'all';
567 } elseif ($is_select) {
569 // c o u n t q u e r y
571 // If we are "just browsing", there is only one table,
572 // and no WHERE clause (or just 'WHERE 1 '),
573 // we do a quick count (which uses MaxExactCount) because
574 // SQL_CALC_FOUND_ROWS is not quick on large InnoDB tables
576 // However, do not count again if we did it previously
577 // due to $find_real_end == true
579 if (!$is_group
580 && ! isset($analyzed_sql[0]['queryflags']['union'])
581 && ! isset($analyzed_sql[0]['table_ref'][1]['table_name'])
582 && (empty($analyzed_sql[0]['where_clause'])
583 || $analyzed_sql[0]['where_clause'] == '1 ')
584 && ! isset($find_real_end)
587 // "j u s t b r o w s i n g"
588 $unlim_num_rows = PMA_Table::countRecords($db, $table);
590 } else { // n o t " j u s t b r o w s i n g "
592 // add select expression after the SQL_CALC_FOUND_ROWS
594 // for UNION, just adding SQL_CALC_FOUND_ROWS
595 // after the first SELECT works.
597 // take the left part, could be:
598 // SELECT
599 // (SELECT
600 $count_query = PMA_SQP_formatHtml($parsed_sql, 'query_only', 0, $analyzed_sql[0]['position_of_first_select'] + 1);
601 $count_query .= ' SQL_CALC_FOUND_ROWS ';
602 // add everything that was after the first SELECT
603 $count_query .= PMA_SQP_formatHtml($parsed_sql, 'query_only', $analyzed_sql[0]['position_of_first_select']+1);
604 // ensure there is no semicolon at the end of the
605 // count query because we'll probably add
606 // a LIMIT 1 clause after it
607 $count_query = rtrim($count_query);
608 $count_query = rtrim($count_query, ';');
610 // if using SQL_CALC_FOUND_ROWS, add a LIMIT to avoid
611 // long delays. Returned count will be complete anyway.
612 // (but a LIMIT would disrupt results in an UNION)
614 if (! isset($analyzed_sql[0]['queryflags']['union'])) {
615 $count_query .= ' LIMIT 1';
618 // run the count query
620 PMA_DBI_try_query($count_query);
621 // if (mysql_error()) {
622 // void.
623 // I tried the case
624 // (SELECT `User`, `Host`, `Db`, `Select_priv` FROM `db`)
625 // UNION (SELECT `User`, `Host`, "%" AS "Db",
626 // `Select_priv`
627 // FROM `user`) ORDER BY `User`, `Host`, `Db`;
628 // and although the generated count_query is wrong
629 // the SELECT FOUND_ROWS() work! (maybe it gets the
630 // count from the latest query that worked)
632 // another case where the count_query is wrong:
633 // SELECT COUNT(*), f1 from t1 group by f1
634 // and you click to sort on count(*)
635 // }
636 $unlim_num_rows = PMA_DBI_fetch_value('SELECT FOUND_ROWS()');
637 } // end else "just browsing"
639 } else { // not $is_select
640 $unlim_num_rows = 0;
641 } // end rows total count
643 // if a table or database gets dropped, check column comments.
644 if (isset($purge) && $purge == '1') {
646 * Cleanup relations.
648 require_once './libraries/relation_cleanup.lib.php';
650 if (strlen($table) && strlen($db)) {
651 PMA_relationsCleanupTable($db, $table);
652 } elseif (strlen($db)) {
653 PMA_relationsCleanupDatabase($db);
654 } else {
655 // VOID. No DB/Table gets deleted.
656 } // end if relation-stuff
657 } // end if ($purge)
659 // If a column gets dropped, do relation magic.
660 if (isset($dropped_column) && strlen($db) && strlen($table) && !empty($dropped_column)) {
661 require_once './libraries/relation_cleanup.lib.php';
662 PMA_relationsCleanupColumn($db, $table, $dropped_column);
664 } // end if column was dropped
665 } // end else "didn't ask to see php code"
667 // No rows returned -> move back to the calling page
668 if (0 == $num_rows || $is_affected) {
669 if ($is_delete) {
670 $message = PMA_Message::deleted_rows($num_rows);
671 } elseif ($is_insert) {
672 if ($is_replace) {
673 /* For replace we get DELETED + INSERTED row count, so we have to call it affected */
674 $message = PMA_Message::affected_rows($num_rows);
675 } else {
676 $message = PMA_Message::inserted_rows($num_rows);
678 $insert_id = PMA_DBI_insert_id();
679 if ($insert_id != 0) {
680 // insert_id is id of FIRST record inserted in one insert, so if we inserted multiple rows, we had to increment this
681 $message->addMessage('[br]');
682 // need to use a temporary because the Message class
683 // currently supports adding parameters only to the first
684 // message
685 $_inserted = PMA_Message::notice(__('Inserted row id: %1$d'));
686 $_inserted->addParam($insert_id + $num_rows - 1);
687 $message->addMessage($_inserted);
689 } elseif ($is_affected) {
690 $message = PMA_Message::affected_rows($num_rows);
692 // Ok, here is an explanation for the !$is_select.
693 // The form generated by sql_query_form.lib.php
694 // and db_sql.php has many submit buttons
695 // on the same form, and some confusion arises from the
696 // fact that $message_to_show is sent for every case.
697 // The $message_to_show containing a success message and sent with
698 // the form should not have priority over errors
699 } elseif (!empty($message_to_show) && !$is_select) {
700 $message = PMA_Message::rawSuccess(htmlspecialchars($message_to_show));
701 } elseif (!empty($GLOBALS['show_as_php'])) {
702 $message = PMA_Message::success(__('Showing as PHP code'));
703 } elseif (isset($GLOBALS['show_as_php'])) {
704 /* User disable showing as PHP, query is only displayed */
705 $message = PMA_Message::notice(__('Showing SQL query'));
706 } elseif (!empty($GLOBALS['validatequery'])) {
707 $message = PMA_Message::notice(__('Validated SQL'));
708 } else {
709 $message = PMA_Message::success(__('MySQL returned an empty result set (i.e. zero rows).'));
712 if (isset($GLOBALS['querytime'])) {
713 $_querytime = PMA_Message::notice(__('Query took %01.4f sec'));
714 $_querytime->addParam($GLOBALS['querytime']);
715 $message->addMessage('(');
716 $message->addMessage($_querytime);
717 $message->addMessage(')');
720 if ($GLOBALS['is_ajax_request'] == true) {
721 if ($cfg['ShowSQL']) {
722 $extra_data['sql_query'] = PMA_showMessage($message, $GLOBALS['sql_query'], 'success');
724 if (isset($GLOBALS['reload']) && $GLOBALS['reload'] == 1) {
725 $extra_data['reload'] = 1;
726 $extra_data['db'] = $GLOBALS['db'];
728 PMA_ajaxResponse($message, $message->isSuccess(), (isset($extra_data) ? $extra_data : ''));
731 if ($is_gotofile) {
732 $goto = PMA_securePath($goto);
733 // Checks for a valid target script
734 $is_db = $is_table = false;
735 if (isset($_REQUEST['purge']) && $_REQUEST['purge'] == '1') {
736 $table = '';
737 unset($url_params['table']);
739 include 'libraries/db_table_exists.lib.php';
741 if (strpos($goto, 'tbl_') === 0 && ! $is_table) {
742 if (strlen($table)) {
743 $table = '';
745 $goto = 'db_sql.php';
747 if (strpos($goto, 'db_') === 0 && ! $is_db) {
748 if (strlen($db)) {
749 $db = '';
751 $goto = 'main.php';
753 // Loads to target script
754 if ($goto != 'main.php') {
755 require_once './libraries/header.inc.php';
757 $active_page = $goto;
758 require './' . $goto;
759 } else {
760 // avoid a redirect loop when last record was deleted
761 if (0 == $num_rows && 'sql.php' == $cfg['DefaultTabTable']) {
762 $goto = str_replace('sql.php','tbl_structure.php',$goto);
764 PMA_sendHeaderLocation($cfg['PmaAbsoluteUri'] . str_replace('&amp;', '&', $goto) . '&message=' . urlencode($message));
765 } // end else
766 exit();
767 } // end no rows returned
769 // At least one row is returned -> displays a table with results
770 else {
771 //If we are retrieving the full value of a truncated field or the original
772 // value of a transformed field, show it here and exit
773 if ($GLOBALS['grid_edit'] == true && $GLOBALS['cfg']['AjaxEnable']) {
774 $row = PMA_DBI_fetch_row($result);
775 $extra_data = array();
776 $extra_data['value'] = $row[0];
777 PMA_ajaxResponse(NULL, true, $extra_data);
780 if (isset($_REQUEST['ajax_request']) && isset($_REQUEST['table_maintenance'])) {
781 $GLOBALS['js_include'][] = 'functions.js';
782 $GLOBALS['js_include'][] = 'makegrid.js';
783 $GLOBALS['js_include'][] = 'sql.js';
785 // Gets the list of fields properties
786 if (isset($result) && $result) {
787 $fields_meta = PMA_DBI_get_fields_meta($result);
788 $fields_cnt = count($fields_meta);
791 if (empty($disp_mode)) {
792 // see the "PMA_setDisplayMode()" function in
793 // libraries/display_tbl.lib.php
794 $disp_mode = 'urdr111101';
797 // hide edit and delete links for information_schema
798 if ($db == 'information_schema') {
799 $disp_mode = 'nnnn110111';
802 $message = PMA_Message::success($message);
803 echo PMA_showMessage($message, $GLOBALS['sql_query'], 'success');
804 PMA_displayTable($result, $disp_mode, $analyzed_sql);
805 exit();
808 // Displays the headers
809 if (isset($show_query)) {
810 unset($show_query);
812 if (isset($printview) && $printview == '1') {
813 require_once './libraries/header_printview.inc.php';
814 } else {
816 $GLOBALS['js_include'][] = 'functions.js';
817 $GLOBALS['js_include'][] = 'makegrid.js';
818 $GLOBALS['js_include'][] = 'sql.js';
820 unset($message);
822 if (! $GLOBALS['is_ajax_request'] || ! $GLOBALS['cfg']['AjaxEnable']) {
823 if (strlen($table)) {
824 require './libraries/tbl_common.php';
825 $url_query .= '&amp;goto=tbl_sql.php&amp;back=tbl_sql.php';
826 require './libraries/tbl_info.inc.php';
827 require './libraries/tbl_links.inc.php';
828 } elseif (strlen($db)) {
829 require './libraries/db_common.inc.php';
830 require './libraries/db_info.inc.php';
831 } else {
832 require './libraries/server_common.inc.php';
833 require './libraries/server_links.inc.php';
835 } else {
836 require_once './libraries/header.inc.php';
837 //we don't need to buffer the output in PMA_showMessage here.
838 //set a global variable and check against it in the function
839 $GLOBALS['buffer_message'] = false;
843 if (strlen($db)) {
844 $cfgRelation = PMA_getRelationsParam();
847 // Gets the list of fields properties
848 if (isset($result) && $result) {
849 $fields_meta = PMA_DBI_get_fields_meta($result);
850 $fields_cnt = count($fields_meta);
853 if (! $GLOBALS['is_ajax_request']) {
854 //begin the sqlqueryresults div here. container div
855 echo '<div id="sqlqueryresults"';
856 if ($GLOBALS['cfg']['AjaxEnable']) {
857 echo ' class="ajax"';
859 echo '>';
862 // Display previous update query (from tbl_replace)
863 if (isset($disp_query) && $cfg['ShowSQL'] == true) {
864 PMA_showMessage($disp_message, $disp_query, 'success');
867 if (isset($profiling_results)) {
868 // pma_token/url_query needed for chart export
870 <script type="text/javascript">
871 pma_token = '<?php echo $_SESSION[' PMA_token ']; ?>';
872 url_query = '<?php echo isset($url_query)?$url_query:PMA_generate_common_url($db);?>';
873 $(document).ready(makeProfilingChart);
874 </script>
875 <?php
876 echo '<fieldset><legend>' . __('Profiling') . '</legend>' . "\n";
877 echo '<div style="float: left;">';
878 echo '<table>' . "\n";
879 echo ' <tr>' . "\n";
880 echo ' <th>' . __('Status') . PMA_showMySQLDocu('general-thread-states','general-thread-states') . '</th>' . "\n";
881 echo ' <th>' . __('Time') . '</th>' . "\n";
882 echo ' </tr>' . "\n";
884 $chart_json = Array();
885 foreach ($profiling_results as $one_result) {
886 echo ' <tr>' . "\n";
887 echo '<td>' . ucwords($one_result['Status']) . '</td>' . "\n";
888 echo '<td align="right">' . (PMA_formatNumber($one_result['Duration'],3,1)) . 's</td>' . "\n";
889 $chart_json[ucwords($one_result['Status'])] = $one_result['Duration'];
892 echo '</table>' . "\n";
893 echo '</div>';
894 //require_once './libraries/chart.lib.php';
895 echo '<div id="profilingchart" style="display:none;">';
896 //PMA_chart_profiling($profiling_results);
897 echo json_encode($chart_json);
898 echo '</div>';
899 echo '</fieldset>' . "\n";
902 // Displays the results in a table
903 if (empty($disp_mode)) {
904 // see the "PMA_setDisplayMode()" function in
905 // libraries/display_tbl.lib.php
906 $disp_mode = 'urdr111101';
909 // hide edit and delete links for information_schema
910 if (strtolower($db) == 'information_schema' || (PMA_DRIZZLE && strtolower($db) == 'data_dictionary')) {
911 $disp_mode = 'nnnn110111';
914 if (isset($label)) {
915 $message = PMA_message::success(__('Bookmark %s created'));
916 $message->addParam($label);
917 $message->display();
920 PMA_displayTable($result, $disp_mode, $analyzed_sql);
921 PMA_DBI_free_result($result);
923 // BEGIN INDEX CHECK See if indexes should be checked.
924 if (isset($query_type) && $query_type == 'check_tbl' && isset($selected) && is_array($selected)) {
925 foreach ($selected as $idx => $tbl_name) {
926 $check = PMA_Index::findDuplicates($tbl_name, $db);
927 if (! empty($check)) {
928 printf(__('Problems with indexes of table `%s`'), $tbl_name);
929 echo $check;
932 } // End INDEX CHECK
934 // Bookmark support if required
935 if ($disp_mode[7] == '1'
936 && (! empty($cfg['Bookmark']) && empty($id_bookmark))
937 && !empty($sql_query)) {
938 echo "\n";
940 $goto = 'sql.php?'
941 . PMA_generate_common_url($db, $table)
942 . '&amp;sql_query=' . urlencode($sql_query)
943 . '&amp;id_bookmark=1';
946 <form action="sql.php" method="post" onsubmit="return emptyFormElements(this, 'fields[label]');">
947 <?php echo PMA_generate_common_hidden_inputs(); ?>
948 <input type="hidden" name="goto" value="<?php echo $goto; ?>" />
949 <input type="hidden" name="fields[dbase]" value="<?php echo htmlspecialchars($db); ?>" />
950 <input type="hidden" name="fields[user]" value="<?php echo $cfg['Bookmark']['user']; ?>" />
951 <input type="hidden" name="fields[query]" value="<?php echo urlencode(isset($complete_query) ? $complete_query : $sql_query); ?>" />
952 <fieldset>
953 <legend><?php
954 echo PMA_getIcon('b_bookmark.png', __('Bookmark this SQL query'));
956 </legend>
958 <div class="formelement">
959 <label for="fields_label_"><?php echo __('Label'); ?>:</label>
960 <input type="text" id="fields_label_" name="fields[label]" value="" />
961 </div>
963 <div class="formelement">
964 <input type="checkbox" name="bkm_all_users" id="bkm_all_users" value="true" />
965 <label for="bkm_all_users"><?php echo __('Let every user access this bookmark'); ?></label>
966 </div>
968 <div class="clearfloat"></div>
969 </fieldset>
970 <fieldset class="tblFooters">
971 <input type="submit" name="store_bkm" value="<?php echo __('Bookmark this SQL query'); ?>" />
972 </fieldset>
973 </form>
974 <?php
975 } // end bookmark support
977 // Do print the page if required
978 if (isset($printview) && $printview == '1') {
980 <script type="text/javascript">
981 //<![CDATA[
982 // Do print the page
983 window.onload = function()
985 if (typeof(window.print) != 'undefined') {
986 window.print();
989 //]]>
990 </script>
991 <?php
992 } // end print case
994 if ($GLOBALS['is_ajax_request'] != true) {
995 echo '</div>'; // end sqlqueryresults div
997 } // end rows returned
1000 * Displays the footer
1002 if (! isset($_REQUEST['table_maintenance'])) {
1003 require './libraries/footer.inc.php';