Translation update done using Pootle.
[phpmyadmin.git] / sql.php
blobb233400fe49b28e5ff8c0f65fa233013b503c17d
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.sprintf.js';
24 $GLOBALS['js_include'][] = 'jquery/jquery.svg.js';
25 $GLOBALS['js_include'][] = 'jquery/jquery.mousewheel.js';
26 $GLOBALS['js_include'][] = 'jquery/jquery.event.drag-2.0.min.js';
27 $GLOBALS['js_include'][] = 'tbl_gis_visualization.js';
28 $GLOBALS['js_include'][] = 'openlayers/OpenLayers.js';
29 $GLOBALS['js_include'][] = 'OpenStreetMap.js';
31 if (isset($_SESSION['profiling'])) {
32 $GLOBALS['js_include'][] = 'highcharts/highcharts.js';
33 /* Files required for chart exporting */
34 $GLOBALS['js_include'][] = 'highcharts/exporting.js';
35 /* < IE 9 doesn't support canvas natively */
36 if (PMA_USR_BROWSER_AGENT == 'IE' && PMA_USR_BROWSER_VER < 9) {
37 $GLOBALS['js_include'][] = 'canvg/flashcanvas.js';
39 $GLOBALS['js_include'][] = 'canvg/canvg.js';
42 /**
43 * Defines the url to return to in case of error in a sql statement
45 // Security checkings
46 if (! empty($goto)) {
47 $is_gotofile = preg_replace('@^([^?]+).*$@s', '\\1', $goto);
48 if (! @file_exists('./' . $is_gotofile)) {
49 unset($goto);
50 } else {
51 $is_gotofile = ($is_gotofile == $goto);
53 } else {
54 $goto = (! strlen($table)) ? $cfg['DefaultTabDatabase'] : $cfg['DefaultTabTable'];
55 $is_gotofile = true;
56 } // end if
58 if (! isset($err_url)) {
59 $err_url = (!empty($back) ? $back : $goto)
60 . '?' . PMA_generate_common_url($db)
61 . ((strpos(' ' . $goto, 'db_') != 1 && strlen($table)) ? '&amp;table=' . urlencode($table) : '');
62 } // end if
64 // Coming from a bookmark dialog
65 if (isset($fields['query'])) {
66 $sql_query = $fields['query'];
69 // This one is just to fill $db
70 if (isset($fields['dbase'])) {
71 $db = $fields['dbase'];
74 /**
75 * During grid edit, if we have a relational field, show the dropdown for it
77 * Logic taken from libraries/display_tbl_lib.php
79 * This doesn't seem to be the right place to do this, but I can't think of any
80 * better place either.
82 if (isset($_REQUEST['get_relational_values']) && $_REQUEST['get_relational_values'] == true) {
83 require_once 'libraries/relation.lib.php';
85 $column = $_REQUEST['column'];
86 $foreigners = PMA_getForeigners($db, $table, $column);
88 $display_field = PMA_getDisplayField($foreigners[$column]['foreign_db'], $foreigners[$column]['foreign_table']);
90 $foreignData = PMA_getForeignData($foreigners, $column, false, '', '');
92 if ($_SESSION['tmp_user_values']['relational_display'] == 'D'
93 && (isset($display_field) && strlen($display_field)
94 && (isset($_REQUEST['relation_key_or_display_column']) && $_REQUEST['relation_key_or_display_column']))) {
95 $curr_value = $_REQUEST['relation_key_or_display_column'];
96 } else {
97 $curr_value = $_REQUEST['curr_value'];
99 if ($foreignData['disp_row'] == null) {
100 //Handle the case when number of values is more than $cfg['ForeignKeyMaxLimit']
101 $_url_params = array(
102 'db' => $db,
103 'table' => $table,
104 'field' => $column
107 $dropdown = '<span class="curr_value">' . htmlspecialchars($_REQUEST['curr_value']) . '</span> <a href="browse_foreigners.php' . PMA_generate_common_url($_url_params) . '"'
108 . ' target="_blank" class="browse_foreign" '
109 .'>' . __('Browse foreign values') . '</a>';
110 } else {
111 $dropdown = PMA_foreignDropdown($foreignData['disp_row'], $foreignData['foreign_field'], $foreignData['foreign_display'], $curr_value, $cfg['ForeignKeyMaxLimit']);
112 $dropdown = '<select>' . $dropdown . '</select>';
115 $extra_data['dropdown'] = $dropdown;
116 PMA_ajaxResponse(NULL, true, $extra_data);
120 * Just like above, find possible values for enum fields during grid edit.
122 * Logic taken from libraries/display_tbl_lib.php
124 if (isset($_REQUEST['get_enum_values']) && $_REQUEST['get_enum_values'] == true) {
125 $field_info_query = PMA_DBI_get_columns_sql($db, $table, $_REQUEST['column']);
127 $field_info_result = PMA_DBI_fetch_result($field_info_query, null, null, null, PMA_DBI_QUERY_STORE);
129 $search = array('enum', '(', ')', "'");
131 $values = explode(',', str_replace($search, '', $field_info_result[0]['Type']));
133 $dropdown = '<option value="">&nbsp;</option>';
134 foreach ($values as $value) {
135 $dropdown .= '<option value="' . htmlspecialchars($value) . '"';
136 if ($value == $_REQUEST['curr_value']) {
137 $dropdown .= ' selected="selected"';
139 $dropdown .= '>' . $value . '</option>';
142 $dropdown = '<select>' . $dropdown . '</select>';
144 $extra_data['dropdown'] = $dropdown;
145 PMA_ajaxResponse(NULL, true, $extra_data);
149 * Find possible values for set fields during grid edit.
151 if (isset($_REQUEST['get_set_values']) && $_REQUEST['get_set_values'] == true) {
152 $field_info_query = PMA_DBI_get_columns_sql($db, $table, $_REQUEST['column']);
154 $field_info_result = PMA_DBI_fetch_result($field_info_query, null, null, null, PMA_DBI_QUERY_STORE);
156 $selected_values = explode(',', $_REQUEST['curr_value']);
158 $search = array('set', '(', ')', "'");
159 $values = explode(',', str_replace($search, '', $field_info_result[0]['Type']));
161 $select = '';
162 foreach ($values as $value) {
163 $select .= '<option value="' . htmlspecialchars($value) . '"';
164 if (in_array($value, $selected_values, true)) {
165 $select .= ' selected="selected"';
167 $select .= '>' . $value . '</option>';
170 $select_size = (sizeof($values) > 10) ? 10 : sizeof($values);
171 $select = '<select multiple="multiple" size="' . $select_size . '">' . $select . '</select>';
173 $extra_data['select'] = $select;
174 PMA_ajaxResponse(NULL, true, $extra_data);
178 * Check ajax request to set the column order
180 if (isset($_REQUEST['set_col_prefs']) && $_REQUEST['set_col_prefs'] == true) {
181 $pmatable = new PMA_Table($table, $db);
182 $retval = false;
184 // set column order
185 if (isset($_REQUEST['col_order'])) {
186 $col_order = explode(',', $_REQUEST['col_order']);
187 $retval = $pmatable->setUiProp(PMA_Table::PROP_COLUMN_ORDER, $col_order, $_REQUEST['table_create_time']);
188 if ($retval !== true) {
189 PMA_ajaxResponse($retval->getString(), false);
194 // set column visibility
195 if (isset($_REQUEST['col_visib'])) {
196 $col_visib = explode(',', $_REQUEST['col_visib']);
197 $retval = $pmatable->setUiProp(PMA_Table::PROP_COLUMN_VISIB, $col_visib, $_REQUEST['table_create_time']);
198 if ($retval !== true) {
199 PMA_ajaxResponse($retval->getString(), false);
203 PMA_ajaxResponse(NULL, ($retval == true));
206 // Default to browse if no query set and we have table
207 // (needed for browsing from DefaultTabTable)
208 if (empty($sql_query) && strlen($table) && strlen($db)) {
209 require_once './libraries/bookmark.lib.php';
210 $book_sql_query = PMA_Bookmark_get($db, '\'' . PMA_sqlAddSlashes($table) . '\'',
211 'label', false, 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('/DROP[[:space:]]+(DATABASE|SCHEMA)[[:space:]]+/i',
232 $sql_query);
235 * Check rights in case of DROP DATABASE
237 * This test may be bypassed if $is_js_confirmed = 1 (already checked with js)
238 * but since a malicious user may pass this variable by url/form, we don't take
239 * into account this case.
241 if (!defined('PMA_CHK_DROP')
242 && !$cfg['AllowUserDropDatabase']
243 && $is_drop_database
244 && !$is_superuser) {
245 require_once './libraries/header.inc.php';
246 PMA_mysqlDie(__('"DROP DATABASE" statements are disabled.'), '', '', $err_url);
247 } // end if
249 require_once './libraries/display_tbl.lib.php';
250 PMA_displayTable_checkConfigParams();
253 * Need to find the real end of rows?
255 if (isset($find_real_end) && $find_real_end) {
256 $unlim_num_rows = PMA_Table::countRecords($db, $table, $force_exact = true);
257 $_SESSION['tmp_user_values']['pos'] = @((ceil($unlim_num_rows / $_SESSION['tmp_user_values']['max_rows']) - 1) * $_SESSION['tmp_user_values']['max_rows']);
262 * Bookmark add
264 if (isset($store_bkm)) {
265 PMA_Bookmark_save($fields, (isset($bkm_all_users) && $bkm_all_users == 'true' ? true : false));
266 // go back to sql.php to redisplay query; do not use &amp; in this case:
267 PMA_sendHeaderLocation($cfg['PmaAbsoluteUri'] . $goto . '&label=' . $fields['label']);
268 } // end if
271 * Parse and analyze the query
273 require_once './libraries/parse_analyze.lib.php';
276 * Sets or modifies the $goto variable if required
278 if ($goto == 'sql.php') {
279 $is_gotofile = false;
280 $goto = 'sql.php?'
281 . PMA_generate_common_url($db, $table)
282 . '&amp;sql_query=' . urlencode($sql_query);
283 } // end if
287 * Go back to further page if table should not be dropped
289 if (isset($btnDrop) && $btnDrop == __('No')) {
290 if (!empty($back)) {
291 $goto = $back;
293 if ($is_gotofile) {
294 if (strpos($goto, 'db_') === 0 && strlen($table)) {
295 $table = '';
297 $active_page = $goto;
298 require './' . PMA_securePath($goto);
299 } else {
300 PMA_sendHeaderLocation($cfg['PmaAbsoluteUri'] . str_replace('&amp;', '&', $goto));
302 exit();
303 } // end if
307 * Displays the confirm page if required
309 * This part of the script is bypassed if $is_js_confirmed = 1 (already checked
310 * with js) because possible security issue is not so important here: at most,
311 * the confirm message isn't displayed.
313 * Also bypassed if only showing php code.or validating a SQL query
315 if (! $cfg['Confirm'] || isset($_REQUEST['is_js_confirmed']) || isset($btnDrop)
316 // if we are coming from a "Create PHP code" or a "Without PHP Code"
317 // dialog, we won't execute the query anyway, so don't confirm
318 || isset($GLOBALS['show_as_php'])
319 || !empty($GLOBALS['validatequery'])) {
320 $do_confirm = false;
321 } else {
322 $do_confirm = isset($analyzed_sql[0]['queryflags']['need_confirm']);
325 if ($do_confirm) {
326 $stripped_sql_query = $sql_query;
327 require_once './libraries/header.inc.php';
328 if ($is_drop_database) {
329 echo '<h1 class="error">' . __('You are about to DESTROY a complete database!') . '</h1>';
331 echo '<form action="sql.php" method="post">' . "\n"
332 .PMA_generate_common_hidden_inputs($db, $table);
334 <input type="hidden" name="sql_query" value="<?php echo htmlspecialchars($sql_query); ?>" />
335 <input type="hidden" name="message_to_show" value="<?php echo isset($message_to_show) ? PMA_sanitize($message_to_show, true) : ''; ?>" />
336 <input type="hidden" name="goto" value="<?php echo $goto; ?>" />
337 <input type="hidden" name="back" value="<?php echo isset($back) ? PMA_sanitize($back, true) : ''; ?>" />
338 <input type="hidden" name="reload" value="<?php echo isset($reload) ? PMA_sanitize($reload, true) : 0; ?>" />
339 <input type="hidden" name="purge" value="<?php echo isset($purge) ? PMA_sanitize($purge, true) : ''; ?>" />
340 <input type="hidden" name="dropped_column" value="<?php echo isset($dropped_column) ? PMA_sanitize($dropped_column, true) : ''; ?>" />
341 <input type="hidden" name="show_query" value="<?php echo isset($show_query) ? PMA_sanitize($show_query, true) : ''; ?>" />
342 <?php
343 echo '<fieldset class="confirmation">' . "\n"
344 .' <legend>' . __('Do you really want to ') . '</legend>'
345 .' <tt>' . htmlspecialchars($stripped_sql_query) . '</tt>' . "\n"
346 .'</fieldset>' . "\n"
347 .'<fieldset class="tblFooters">' . "\n";
349 <input type="submit" name="btnDrop" value="<?php echo __('Yes'); ?>" id="buttonYes" />
350 <input type="submit" name="btnDrop" value="<?php echo __('No'); ?>" id="buttonNo" />
351 <?php
352 echo '</fieldset>' . "\n"
353 . '</form>' . "\n";
356 * Displays the footer and exit
358 require './libraries/footer.inc.php';
359 } // end if $do_confirm
362 // Defines some variables
363 // A table has to be created, renamed, dropped -> navi frame should be reloaded
365 * @todo use the parser/analyzer
368 if (empty($reload)
369 && preg_match('/^(CREATE|ALTER|DROP)\s+(VIEW|TABLE|DATABASE|SCHEMA)\s+/i', $sql_query)) {
370 $reload = 1;
373 // SK -- Patch: $is_group added for use in calculation of total number of
374 // rows.
375 // $is_count is changed for more correct "LIMIT" clause
376 // appending in queries like
377 // "SELECT COUNT(...) FROM ... GROUP BY ..."
380 * @todo detect all this with the parser, to avoid problems finding
381 * those strings in comments or backquoted identifiers
384 $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;
385 if ($is_select) { // see line 141
386 $is_group = preg_match('@(GROUP[[:space:]]+BY|HAVING|SELECT[[:space:]]+DISTINCT)[[:space:]]+@i', $sql_query);
387 $is_func = !$is_group && (preg_match('@[[:space:]]+(SUM|AVG|STD|STDDEV|MIN|MAX|BIT_OR|BIT_AND)\s*\(@i', $sql_query));
388 $is_count = !$is_group && (preg_match('@^SELECT[[:space:]]+COUNT\((.*\.+)?.*\)@i', $sql_query));
389 $is_export = (preg_match('@[[:space:]]+INTO[[:space:]]+OUTFILE[[:space:]]+@i', $sql_query));
390 $is_analyse = (preg_match('@[[:space:]]+PROCEDURE[[:space:]]+ANALYSE@i', $sql_query));
391 } elseif (preg_match('@^EXPLAIN[[:space:]]+@i', $sql_query)) {
392 $is_explain = true;
393 } elseif (preg_match('@^DELETE[[:space:]]+@i', $sql_query)) {
394 $is_delete = true;
395 $is_affected = true;
396 } elseif (preg_match('@^(INSERT|LOAD[[:space:]]+DATA|REPLACE)[[:space:]]+@i', $sql_query)) {
397 $is_insert = true;
398 $is_affected = true;
399 if (preg_match('@^(REPLACE)[[:space:]]+@i', $sql_query)) {
400 $is_replace = true;
402 } elseif (preg_match('@^UPDATE[[:space:]]+@i', $sql_query)) {
403 $is_affected = true;
404 } elseif (preg_match('@^[[:space:]]*SHOW[[:space:]]+@i', $sql_query)) {
405 $is_show = true;
406 } elseif (preg_match('@^(CHECK|ANALYZE|REPAIR|OPTIMIZE)[[:space:]]+TABLE[[:space:]]+@i', $sql_query)) {
407 $is_maint = true;
410 // assign default full_sql_query
411 $full_sql_query = $sql_query;
413 // Handle remembered sorting order, only for single table query
414 if ($GLOBALS['cfg']['RememberSorting']
415 && ! ($is_count || $is_export || $is_func || $is_analyse)
416 && count($analyzed_sql[0]['select_expr']) == 0
417 && isset($analyzed_sql[0]['queryflags']['select_from'])
418 && count($analyzed_sql[0]['table_ref']) == 1
420 $pmatable = new PMA_Table($table, $db);
421 if (empty($analyzed_sql[0]['order_by_clause'])) {
422 $sorted_col = $pmatable->getUiProp(PMA_Table::PROP_SORTED_COLUMN);
423 if ($sorted_col) {
424 // retrieve the remembered sorting order for current table
425 $sql_order_to_append = ' ORDER BY ' . $sorted_col . ' ';
426 $full_sql_query = $analyzed_sql[0]['section_before_limit'] . $sql_order_to_append . $analyzed_sql[0]['section_after_limit'];
428 // update the $analyzed_sql
429 $analyzed_sql[0]['section_before_limit'] .= $sql_order_to_append;
430 $analyzed_sql[0]['order_by_clause'] = $sorted_col;
432 } else {
433 // store the remembered table into session
434 $pmatable->setUiProp(PMA_Table::PROP_SORTED_COLUMN, $analyzed_sql[0]['order_by_clause']);
438 // Do append a "LIMIT" clause?
439 if ((! $cfg['ShowAll'] || $_SESSION['tmp_user_values']['max_rows'] != 'all')
440 && ! ($is_count || $is_export || $is_func || $is_analyse)
441 && isset($analyzed_sql[0]['queryflags']['select_from'])
442 && ! isset($analyzed_sql[0]['queryflags']['offset'])
443 && empty($analyzed_sql[0]['limit_clause'])
445 $sql_limit_to_append = ' LIMIT ' . $_SESSION['tmp_user_values']['pos'] . ', ' . $_SESSION['tmp_user_values']['max_rows'] . " ";
447 $full_sql_query = $analyzed_sql[0]['section_before_limit'] . "\n" . $sql_limit_to_append . $analyzed_sql[0]['section_after_limit'];
449 * @todo pretty printing of this modified query
451 if (isset($display_query)) {
452 // if the analysis of the original query revealed that we found
453 // a section_after_limit, we now have to analyze $display_query
454 // to display it correctly
456 if (!empty($analyzed_sql[0]['section_after_limit']) && trim($analyzed_sql[0]['section_after_limit']) != ';') {
457 $analyzed_display_query = PMA_SQP_analyze(PMA_SQP_parse($display_query));
458 $display_query = $analyzed_display_query[0]['section_before_limit'] . "\n" . $sql_limit_to_append . $analyzed_display_query[0]['section_after_limit'];
464 if (strlen($db)) {
465 PMA_DBI_select_db($db);
468 // E x e c u t e t h e q u e r y
470 // Only if we didn't ask to see the php code (mikebeck)
471 if (isset($GLOBALS['show_as_php']) || !empty($GLOBALS['validatequery'])) {
472 unset($result);
473 $num_rows = 0;
474 } else {
475 if (isset($_SESSION['profiling']) && PMA_profilingSupported()) {
476 PMA_DBI_query('SET PROFILING=1;');
479 // Measure query time.
480 $querytime_before = array_sum(explode(' ', microtime()));
482 $result = @PMA_DBI_try_query($full_sql_query, null, PMA_DBI_QUERY_STORE);
484 // If a stored procedure was called, there may be more results that are
485 // queued up and waiting to be flushed from the buffer. So let's do that.
486 while (true) {
487 if (! PMA_DBI_more_results()) {
488 break;
490 PMA_DBI_next_result();
493 $querytime_after = array_sum(explode(' ', microtime()));
495 $GLOBALS['querytime'] = $querytime_after - $querytime_before;
497 // Displays an error message if required and stop parsing the script
498 if ($error = PMA_DBI_getError()) {
499 if ($is_gotofile) {
500 if (strpos($goto, 'db_') === 0 && strlen($table)) {
501 $table = '';
503 $active_page = $goto;
504 $message = PMA_Message::rawError($error);
506 if ($GLOBALS['is_ajax_request'] == true) {
507 PMA_ajaxResponse($message, false);
511 * Go to target path.
513 require './' . PMA_securePath($goto);
514 } else {
515 $full_err_url = (preg_match('@^(db|tbl)_@', $err_url))
516 ? $err_url . '&amp;show_query=1&amp;sql_query=' . urlencode($sql_query)
517 : $err_url;
518 PMA_mysqlDie($error, $full_sql_query, '', $full_err_url);
520 exit;
522 unset($error);
524 // Gets the number of rows affected/returned
525 // (This must be done immediately after the query because
526 // mysql_affected_rows() reports about the last query done)
528 if (!$is_affected) {
529 $num_rows = ($result) ? @PMA_DBI_num_rows($result) : 0;
530 } elseif (! isset($num_rows)) {
531 $num_rows = @PMA_DBI_affected_rows();
534 // Grabs the profiling results
535 if (isset($_SESSION['profiling']) && PMA_profilingSupported()) {
536 $profiling_results = PMA_DBI_fetch_result('SHOW PROFILE;');
539 // Checks if the current database has changed
540 // This could happen if the user sends a query like "USE `database`;"
542 * commented out auto-switching to active database - really required?
543 * bug #1814718 win: table list disappears (mixed case db names)
544 * https://sourceforge.net/support/tracker.php?aid=1814718
545 * @todo RELEASE test and comit or rollback before release
546 $current_db = PMA_DBI_fetch_value('SELECT DATABASE()');
547 if ($db !== $current_db) {
548 $db = $current_db;
549 $reload = 1;
551 unset($current_db);
554 // tmpfile remove after convert encoding appended by Y.Kawada
555 if (function_exists('PMA_kanji_file_conv')
556 && (isset($textfile) && file_exists($textfile))) {
557 unlink($textfile);
560 // Counts the total number of rows for the same 'SELECT' query without the
561 // 'LIMIT' clause that may have been programatically added
563 if (empty($sql_limit_to_append)) {
564 $unlim_num_rows = $num_rows;
565 // if we did not append a limit, set this to get a correct
566 // "Showing rows..." message
567 //$_SESSION['tmp_user_values']['max_rows'] = 'all';
568 } elseif ($is_select) {
570 // c o u n t q u e r y
572 // If we are "just browsing", there is only one table,
573 // and no WHERE clause (or just 'WHERE 1 '),
574 // we do a quick count (which uses MaxExactCount) because
575 // SQL_CALC_FOUND_ROWS is not quick on large InnoDB tables
577 // However, do not count again if we did it previously
578 // due to $find_real_end == true
580 if (!$is_group
581 && ! isset($analyzed_sql[0]['queryflags']['union'])
582 && ! isset($analyzed_sql[0]['table_ref'][1]['table_name'])
583 && (empty($analyzed_sql[0]['where_clause'])
584 || $analyzed_sql[0]['where_clause'] == '1 ')
585 && ! isset($find_real_end)
588 // "j u s t b r o w s i n g"
589 $unlim_num_rows = PMA_Table::countRecords($db, $table);
591 } else { // n o t " j u s t b r o w s i n g "
593 // add select expression after the SQL_CALC_FOUND_ROWS
595 // for UNION, just adding SQL_CALC_FOUND_ROWS
596 // after the first SELECT works.
598 // take the left part, could be:
599 // SELECT
600 // (SELECT
601 $count_query = PMA_SQP_formatHtml($parsed_sql, 'query_only', 0, $analyzed_sql[0]['position_of_first_select'] + 1);
602 $count_query .= ' SQL_CALC_FOUND_ROWS ';
603 // add everything that was after the first SELECT
604 $count_query .= PMA_SQP_formatHtml($parsed_sql, 'query_only', $analyzed_sql[0]['position_of_first_select']+1);
605 // ensure there is no semicolon at the end of the
606 // count query because we'll probably add
607 // a LIMIT 1 clause after it
608 $count_query = rtrim($count_query);
609 $count_query = rtrim($count_query, ';');
611 // if using SQL_CALC_FOUND_ROWS, add a LIMIT to avoid
612 // long delays. Returned count will be complete anyway.
613 // (but a LIMIT would disrupt results in an UNION)
615 if (! isset($analyzed_sql[0]['queryflags']['union'])) {
616 $count_query .= ' LIMIT 1';
619 // run the count query
621 PMA_DBI_try_query($count_query);
622 // if (mysql_error()) {
623 // void.
624 // I tried the case
625 // (SELECT `User`, `Host`, `Db`, `Select_priv` FROM `db`)
626 // UNION (SELECT `User`, `Host`, "%" AS "Db",
627 // `Select_priv`
628 // FROM `user`) ORDER BY `User`, `Host`, `Db`;
629 // and although the generated count_query is wrong
630 // the SELECT FOUND_ROWS() work! (maybe it gets the
631 // count from the latest query that worked)
633 // another case where the count_query is wrong:
634 // SELECT COUNT(*), f1 from t1 group by f1
635 // and you click to sort on count(*)
636 // }
637 $unlim_num_rows = PMA_DBI_fetch_value('SELECT FOUND_ROWS()');
638 } // end else "just browsing"
640 } else { // not $is_select
641 $unlim_num_rows = 0;
642 } // end rows total count
644 // if a table or database gets dropped, check column comments.
645 if (isset($purge) && $purge == '1') {
647 * Cleanup relations.
649 require_once './libraries/relation_cleanup.lib.php';
651 if (strlen($table) && strlen($db)) {
652 PMA_relationsCleanupTable($db, $table);
653 } elseif (strlen($db)) {
654 PMA_relationsCleanupDatabase($db);
655 } else {
656 // VOID. No DB/Table gets deleted.
657 } // end if relation-stuff
658 } // end if ($purge)
660 // If a column gets dropped, do relation magic.
661 if (isset($dropped_column) && strlen($db) && strlen($table) && !empty($dropped_column)) {
662 require_once './libraries/relation_cleanup.lib.php';
663 PMA_relationsCleanupColumn($db, $table, $dropped_column);
665 } // end if column was dropped
666 } // end else "didn't ask to see php code"
668 // No rows returned -> move back to the calling page
669 if (0 == $num_rows || $is_affected) {
670 if ($is_delete) {
671 $message = PMA_Message::deleted_rows($num_rows);
672 } elseif ($is_insert) {
673 if ($is_replace) {
674 /* For replace we get DELETED + INSERTED row count, so we have to call it affected */
675 $message = PMA_Message::affected_rows($num_rows);
676 } else {
677 $message = PMA_Message::inserted_rows($num_rows);
679 $insert_id = PMA_DBI_insert_id();
680 if ($insert_id != 0) {
681 // insert_id is id of FIRST record inserted in one insert, so if we inserted multiple rows, we had to increment this
682 $message->addMessage('[br]');
683 // need to use a temporary because the Message class
684 // currently supports adding parameters only to the first
685 // message
686 $_inserted = PMA_Message::notice(__('Inserted row id: %1$d'));
687 $_inserted->addParam($insert_id + $num_rows - 1);
688 $message->addMessage($_inserted);
690 } elseif ($is_affected) {
691 $message = PMA_Message::affected_rows($num_rows);
693 // Ok, here is an explanation for the !$is_select.
694 // The form generated by sql_query_form.lib.php
695 // and db_sql.php has many submit buttons
696 // on the same form, and some confusion arises from the
697 // fact that $message_to_show is sent for every case.
698 // The $message_to_show containing a success message and sent with
699 // the form should not have priority over errors
700 } elseif (!empty($message_to_show) && !$is_select) {
701 $message = PMA_Message::rawSuccess(htmlspecialchars($message_to_show));
702 } elseif (!empty($GLOBALS['show_as_php'])) {
703 $message = PMA_Message::success(__('Showing as PHP code'));
704 } elseif (isset($GLOBALS['show_as_php'])) {
705 /* User disable showing as PHP, query is only displayed */
706 $message = PMA_Message::notice(__('Showing SQL query'));
707 } elseif (!empty($GLOBALS['validatequery'])) {
708 $message = PMA_Message::notice(__('Validated SQL'));
709 } else {
710 $message = PMA_Message::success(__('MySQL returned an empty result set (i.e. zero rows).'));
713 if (isset($GLOBALS['querytime'])) {
714 $_querytime = PMA_Message::notice(__('Query took %01.4f sec'));
715 $_querytime->addParam($GLOBALS['querytime']);
716 $message->addMessage('(');
717 $message->addMessage($_querytime);
718 $message->addMessage(')');
721 if ($GLOBALS['is_ajax_request'] == true) {
722 if ($cfg['ShowSQL']) {
723 $extra_data['sql_query'] = PMA_showMessage($message, $GLOBALS['sql_query'], 'success');
725 if (isset($GLOBALS['reload']) && $GLOBALS['reload'] == 1) {
726 $extra_data['reload'] = 1;
727 $extra_data['db'] = $GLOBALS['db'];
729 PMA_ajaxResponse($message, $message->isSuccess(), (isset($extra_data) ? $extra_data : ''));
732 if ($is_gotofile) {
733 $goto = PMA_securePath($goto);
734 // Checks for a valid target script
735 $is_db = $is_table = false;
736 if (isset($_REQUEST['purge']) && $_REQUEST['purge'] == '1') {
737 $table = '';
738 unset($url_params['table']);
740 include 'libraries/db_table_exists.lib.php';
742 if (strpos($goto, 'tbl_') === 0 && ! $is_table) {
743 if (strlen($table)) {
744 $table = '';
746 $goto = 'db_sql.php';
748 if (strpos($goto, 'db_') === 0 && ! $is_db) {
749 if (strlen($db)) {
750 $db = '';
752 $goto = 'main.php';
754 // Loads to target script
755 if ($goto != 'main.php') {
756 require_once './libraries/header.inc.php';
758 $active_page = $goto;
759 require './' . $goto;
760 } else {
761 // avoid a redirect loop when last record was deleted
762 if (0 == $num_rows && 'sql.php' == $cfg['DefaultTabTable']) {
763 $goto = str_replace('sql.php','tbl_structure.php',$goto);
765 PMA_sendHeaderLocation($cfg['PmaAbsoluteUri'] . str_replace('&amp;', '&', $goto) . '&message=' . urlencode($message));
766 } // end else
767 exit();
768 } // end no rows returned
770 // At least one row is returned -> displays a table with results
771 else {
772 //If we are retrieving the full value of a truncated field or the original
773 // value of a transformed field, show it here and exit
774 if ($GLOBALS['grid_edit'] == true && $GLOBALS['cfg']['AjaxEnable']) {
775 $row = PMA_DBI_fetch_row($result);
776 $extra_data = array();
777 $extra_data['value'] = $row[0];
778 PMA_ajaxResponse(NULL, true, $extra_data);
781 if (isset($_REQUEST['ajax_request']) && isset($_REQUEST['table_maintenance'])) {
782 $GLOBALS['js_include'][] = 'functions.js';
783 $GLOBALS['js_include'][] = 'makegrid.js';
784 $GLOBALS['js_include'][] = 'sql.js';
786 // Gets the list of fields properties
787 if (isset($result) && $result) {
788 $fields_meta = PMA_DBI_get_fields_meta($result);
789 $fields_cnt = count($fields_meta);
792 if (empty($disp_mode)) {
793 // see the "PMA_setDisplayMode()" function in
794 // libraries/display_tbl.lib.php
795 $disp_mode = 'urdr111101';
798 // hide edit and delete links for information_schema
799 if (PMA_is_system_schema($db)) {
800 $disp_mode = 'nnnn110111';
803 $message = PMA_Message::success($message);
804 echo PMA_showMessage($message, $GLOBALS['sql_query'], 'success');
805 PMA_displayTable($result, $disp_mode, $analyzed_sql);
806 exit();
809 // Displays the headers
810 if (isset($show_query)) {
811 unset($show_query);
813 if (isset($printview) && $printview == '1') {
814 require_once './libraries/header_printview.inc.php';
815 } else {
817 $GLOBALS['js_include'][] = 'functions.js';
818 $GLOBALS['js_include'][] = 'makegrid.js';
819 $GLOBALS['js_include'][] = 'sql.js';
821 unset($message);
823 if (! $GLOBALS['is_ajax_request'] || ! $GLOBALS['cfg']['AjaxEnable']) {
824 if (strlen($table)) {
825 require './libraries/tbl_common.php';
826 $url_query .= '&amp;goto=tbl_sql.php&amp;back=tbl_sql.php';
827 require './libraries/tbl_info.inc.php';
828 require './libraries/tbl_links.inc.php';
829 } elseif (strlen($db)) {
830 require './libraries/db_common.inc.php';
831 require './libraries/db_info.inc.php';
832 } else {
833 require './libraries/server_common.inc.php';
834 require './libraries/server_links.inc.php';
836 } else {
837 require_once './libraries/header.inc.php';
838 //we don't need to buffer the output in PMA_showMessage here.
839 //set a global variable and check against it in the function
840 $GLOBALS['buffer_message'] = false;
844 if (strlen($db)) {
845 $cfgRelation = PMA_getRelationsParam();
848 // Gets the list of fields properties
849 if (isset($result) && $result) {
850 $fields_meta = PMA_DBI_get_fields_meta($result);
851 $fields_cnt = count($fields_meta);
854 if (! $GLOBALS['is_ajax_request']) {
855 //begin the sqlqueryresults div here. container div
856 echo '<div id="sqlqueryresults"';
857 if ($GLOBALS['cfg']['AjaxEnable']) {
858 echo ' class="ajax"';
860 echo '>';
863 // Display previous update query (from tbl_replace)
864 if (isset($disp_query) && $cfg['ShowSQL'] == true) {
865 PMA_showMessage($disp_message, $disp_query, 'success');
868 if (isset($profiling_results)) {
869 // pma_token/url_query needed for chart export
871 <script type="text/javascript">
872 pma_token = '<?php echo $_SESSION[' PMA_token ']; ?>';
873 url_query = '<?php echo isset($url_query)?$url_query:PMA_generate_common_url($db);?>';
874 $(document).ready(makeProfilingChart);
875 </script>
876 <?php
877 echo '<fieldset><legend>' . __('Profiling') . '</legend>' . "\n";
878 echo '<div style="float: left;">';
879 echo '<table>' . "\n";
880 echo ' <tr>' . "\n";
881 echo ' <th>' . __('Status') . PMA_showMySQLDocu('general-thread-states','general-thread-states') . '</th>' . "\n";
882 echo ' <th>' . __('Time') . '</th>' . "\n";
883 echo ' </tr>' . "\n";
885 $chart_json = Array();
886 foreach ($profiling_results as $one_result) {
887 echo ' <tr>' . "\n";
888 echo '<td>' . ucwords($one_result['Status']) . '</td>' . "\n";
889 echo '<td align="right">' . (PMA_formatNumber($one_result['Duration'],3,1)) . 's</td>' . "\n";
890 $chart_json[ucwords($one_result['Status'])] = $one_result['Duration'];
893 echo '</table>' . "\n";
894 echo '</div>';
895 //require_once './libraries/chart.lib.php';
896 echo '<div id="profilingchart" style="display:none;">';
897 //PMA_chart_profiling($profiling_results);
898 echo json_encode($chart_json);
899 echo '</div>';
900 echo '</fieldset>' . "\n";
903 // Displays the results in a table
904 if (empty($disp_mode)) {
905 // see the "PMA_setDisplayMode()" function in
906 // libraries/display_tbl.lib.php
907 $disp_mode = 'urdr111101';
910 // hide edit and delete links for information_schema
911 if (PMA_is_system_schema($db)) {
912 $disp_mode = 'nnnn110111';
915 if (isset($label)) {
916 $message = PMA_message::success(__('Bookmark %s created'));
917 $message->addParam($label);
918 $message->display();
921 PMA_displayTable($result, $disp_mode, $analyzed_sql);
922 PMA_DBI_free_result($result);
924 // BEGIN INDEX CHECK See if indexes should be checked.
925 if (isset($query_type) && $query_type == 'check_tbl' && isset($selected) && is_array($selected)) {
926 foreach ($selected as $idx => $tbl_name) {
927 $check = PMA_Index::findDuplicates($tbl_name, $db);
928 if (! empty($check)) {
929 printf(__('Problems with indexes of table `%s`'), $tbl_name);
930 echo $check;
933 } // End INDEX CHECK
935 // Bookmark support if required
936 if ($disp_mode[7] == '1'
937 && (! empty($cfg['Bookmark']) && empty($id_bookmark))
938 && !empty($sql_query)) {
939 echo "\n";
941 $goto = 'sql.php?'
942 . PMA_generate_common_url($db, $table)
943 . '&amp;sql_query=' . urlencode($sql_query)
944 . '&amp;id_bookmark=1';
947 <form action="sql.php" method="post" onsubmit="return emptyFormElements(this, 'fields[label]');">
948 <?php echo PMA_generate_common_hidden_inputs(); ?>
949 <input type="hidden" name="goto" value="<?php echo $goto; ?>" />
950 <input type="hidden" name="fields[dbase]" value="<?php echo htmlspecialchars($db); ?>" />
951 <input type="hidden" name="fields[user]" value="<?php echo $cfg['Bookmark']['user']; ?>" />
952 <input type="hidden" name="fields[query]" value="<?php echo urlencode(isset($complete_query) ? $complete_query : $sql_query); ?>" />
953 <fieldset>
954 <legend><?php
955 echo PMA_getIcon('b_bookmark.png', __('Bookmark this SQL query'));
957 </legend>
959 <div class="formelement">
960 <label for="fields_label_"><?php echo __('Label'); ?>:</label>
961 <input type="text" id="fields_label_" name="fields[label]" value="" />
962 </div>
964 <div class="formelement">
965 <input type="checkbox" name="bkm_all_users" id="bkm_all_users" value="true" />
966 <label for="bkm_all_users"><?php echo __('Let every user access this bookmark'); ?></label>
967 </div>
969 <div class="clearfloat"></div>
970 </fieldset>
971 <fieldset class="tblFooters">
972 <input type="submit" name="store_bkm" value="<?php echo __('Bookmark this SQL query'); ?>" />
973 </fieldset>
974 </form>
975 <?php
976 } // end bookmark support
978 // Do print the page if required
979 if (isset($printview) && $printview == '1') {
981 <script type="text/javascript">
982 //<![CDATA[
983 // Do print the page
984 window.onload = function()
986 if (typeof(window.print) != 'undefined') {
987 window.print();
990 //]]>
991 </script>
992 <?php
993 } // end print case
995 if ($GLOBALS['is_ajax_request'] != true) {
996 echo '</div>'; // end sqlqueryresults div
998 } // end rows returned
1001 * Displays the footer
1003 if (! isset($_REQUEST['table_maintenance'])) {
1004 require './libraries/footer.inc.php';