Make this usage of $sql_backquotes less cryptic
[phpmyadmin.git] / sql.php
blob60740f64480e53ca0aaebd35ac7a316ca7846382
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'][] = 'tbl_change.js';
20 if (isset($_SESSION['profiling'])) {
21 $GLOBALS['js_include'][] = 'highcharts/highcharts.js';
22 /* Files required for chart exporting */
23 $GLOBALS['js_include'][] = 'highcharts/exporting.js';
24 /* < IE 9 doesn't support canvas natively */
25 if (PMA_USR_BROWSER_AGENT == 'IE' && PMA_USR_BROWSER_VER < 9) {
26 $GLOBALS['js_include'][] = 'canvg/flashcanvas.js';
28 $GLOBALS['js_include'][] = 'canvg/canvg.js';
31 /**
32 * Defines the url to return to in case of error in a sql statement
34 // Security checkings
35 if (! empty($goto)) {
36 $is_gotofile = preg_replace('@^([^?]+).*$@s', '\\1', $goto);
37 if (! @file_exists('./' . $is_gotofile)) {
38 unset($goto);
39 } else {
40 $is_gotofile = ($is_gotofile == $goto);
42 } else {
43 $goto = (! strlen($table)) ? $cfg['DefaultTabDatabase'] : $cfg['DefaultTabTable'];
44 $is_gotofile = true;
45 } // end if
47 if (! isset($err_url)) {
48 $err_url = (!empty($back) ? $back : $goto)
49 . '?' . PMA_generate_common_url($db)
50 . ((strpos(' ' . $goto, 'db_') != 1 && strlen($table)) ? '&amp;table=' . urlencode($table) : '');
51 } // end if
53 // Coming from a bookmark dialog
54 if (isset($fields['query'])) {
55 $sql_query = $fields['query'];
58 // This one is just to fill $db
59 if (isset($fields['dbase'])) {
60 $db = $fields['dbase'];
63 /**
64 * During grid edit, if we have a relational field, show the dropdown for it
66 * Logic taken from libraries/display_tbl_lib.php
68 * This doesn't seem to be the right place to do this, but I can't think of any
69 * better place either.
71 if (isset($_REQUEST['get_relational_values']) && $_REQUEST['get_relational_values'] == true) {
72 require_once 'libraries/relation.lib.php';
74 $column = $_REQUEST['column'];
75 $foreigners = PMA_getForeigners($db, $table, $column);
77 $display_field = PMA_getDisplayField($foreigners[$column]['foreign_db'], $foreigners[$column]['foreign_table']);
79 $foreignData = PMA_getForeignData($foreigners, $column, false, '', '');
81 if ($_SESSION['tmp_user_values']['relational_display'] == 'D'
82 && (isset($display_field) && strlen($display_field)
83 && (isset($_REQUEST['relation_key_or_display_column']) && $_REQUEST['relation_key_or_display_column']))) {
84 $curr_value = $_REQUEST['relation_key_or_display_column'];
85 } else {
86 $curr_value = $_REQUEST['curr_value'];
88 if ($foreignData['disp_row'] == null) {
89 //Handle the case when number of values is more than $cfg['ForeignKeyMaxLimit']
90 $_url_params = array(
91 'db' => $db,
92 'table' => $table,
93 'field' => $column
96 $dropdown = '<span class="curr_value">' . htmlspecialchars($_REQUEST['curr_value']) . '</span> <a href="browse_foreigners.php' . PMA_generate_common_url($_url_params) . '"'
97 . ' target="_blank" class="browse_foreign" '
98 .'>' . __('Browse foreign values') . '</a>';
99 } else {
100 $dropdown = PMA_foreignDropdown($foreignData['disp_row'], $foreignData['foreign_field'], $foreignData['foreign_display'], $curr_value, $cfg['ForeignKeyMaxLimit']);
101 $dropdown = '<select>' . $dropdown . '</select>';
104 $extra_data['dropdown'] = $dropdown;
105 PMA_ajaxResponse(NULL, true, $extra_data);
109 * Just like above, find possible values for enum fields during grid edit.
111 * Logic taken from libraries/display_tbl_lib.php
113 if (isset($_REQUEST['get_enum_values']) && $_REQUEST['get_enum_values'] == true) {
114 $field_info_query = 'SHOW FIELDS FROM `' . $db . '`.`' . $table . '` LIKE \'' . $_REQUEST['column'] . '\' ;';
116 $field_info_result = PMA_DBI_fetch_result($field_info_query, null, null, null, PMA_DBI_QUERY_STORE);
118 $search = array('enum', '(', ')', "'");
120 $values = explode(',', str_replace($search, '', $field_info_result[0]['Type']));
122 $dropdown = '<option value="">&nbsp;</option>';
123 foreach ($values as $value) {
124 $dropdown .= '<option value="' . htmlspecialchars($value) . '"';
125 if ($value == $_REQUEST['curr_value']) {
126 $dropdown .= ' selected="selected"';
128 $dropdown .= '>' . $value . '</option>';
131 $dropdown = '<select>' . $dropdown . '</select>';
133 $extra_data['dropdown'] = $dropdown;
134 PMA_ajaxResponse(NULL, true, $extra_data);
138 * Find possible values for set fields during grid edit.
140 if (isset($_REQUEST['get_set_values']) && $_REQUEST['get_set_values'] == true) {
141 $field_info_query = 'SHOW FIELDS FROM `' . $db . '`.`' . $table . '` LIKE \'' . $_REQUEST['column'] . '\' ;';
143 $field_info_result = PMA_DBI_fetch_result($field_info_query, null, null, null, PMA_DBI_QUERY_STORE);
145 $selected_values = explode(',', $_REQUEST['curr_value']);
147 $search = array('set', '(', ')', "'");
148 $values = explode(',', str_replace($search, '', $field_info_result[0]['Type']));
150 $select = '';
151 foreach ($values as $value) {
152 $select .= '<option value="' . htmlspecialchars($value) . '"';
153 if (in_array($value, $selected_values, true)) {
154 $select .= ' selected="selected"';
156 $select .= '>' . $value . '</option>';
159 $select_size = (sizeof($values) > 10) ? 10 : sizeof($values);
160 $select = '<select multiple="multiple" size="' . $select_size . '">' . $select . '</select>';
162 $extra_data['select'] = $select;
163 PMA_ajaxResponse(NULL, true, $extra_data);
167 * Check ajax request to set the column order
169 if (isset($_REQUEST['set_col_prefs']) && $_REQUEST['set_col_prefs'] == true) {
170 $pmatable = new PMA_Table($table, $db);
171 $retval = false;
173 // set column order
174 if (isset($_REQUEST['col_order'])) {
175 $col_order = explode(',', $_REQUEST['col_order']);
176 $retval = $pmatable->setUiProp(PMA_Table::PROP_COLUMN_ORDER, $col_order, $_REQUEST['table_create_time']);
177 if ($retval !== true) {
178 PMA_ajaxResponse($retval->getString(), false);
183 // set column visibility
184 if (isset($_REQUEST['col_visib'])) {
185 $col_visib = explode(',', $_REQUEST['col_visib']);
186 $retval = $pmatable->setUiProp(PMA_Table::PROP_COLUMN_VISIB, $col_visib, $_REQUEST['table_create_time']);
187 if ($retval !== true) {
188 PMA_ajaxResponse($retval->getString(), false);
192 PMA_ajaxResponse(NULL, ($retval == true));
195 // Default to browse if no query set and we have table
196 // (needed for browsing from DefaultTabTable)
197 if (empty($sql_query) && strlen($table) && strlen($db)) {
198 require_once './libraries/bookmark.lib.php';
199 $book_sql_query = PMA_Bookmark_get($db, '\'' . PMA_sqlAddSlashes($table) . '\'',
200 'label', false, true);
202 if (! empty($book_sql_query)) {
203 $GLOBALS['using_bookmark_message'] = PMA_message::notice(__('Using bookmark "%s" as default browse query.'));
204 $GLOBALS['using_bookmark_message']->addParam($table);
205 $GLOBALS['using_bookmark_message']->addMessage(PMA_showDocu('faq6_22'));
206 $sql_query = $book_sql_query;
207 } else {
208 $sql_query = 'SELECT * FROM ' . PMA_backquote($table);
210 unset($book_sql_query);
212 // set $goto to what will be displayed if query returns 0 rows
213 $goto = 'tbl_structure.php';
214 } else {
215 // Now we can check the parameters
216 PMA_checkParameters(array('sql_query'));
219 // instead of doing the test twice
220 $is_drop_database = preg_match('/DROP[[:space:]]+(DATABASE|SCHEMA)[[:space:]]+/i',
221 $sql_query);
224 * Check rights in case of DROP DATABASE
226 * This test may be bypassed if $is_js_confirmed = 1 (already checked with js)
227 * but since a malicious user may pass this variable by url/form, we don't take
228 * into account this case.
230 if (!defined('PMA_CHK_DROP')
231 && !$cfg['AllowUserDropDatabase']
232 && $is_drop_database
233 && !$is_superuser) {
234 require_once './libraries/header.inc.php';
235 PMA_mysqlDie(__('"DROP DATABASE" statements are disabled.'), '', '', $err_url);
236 } // end if
238 require_once './libraries/display_tbl.lib.php';
239 PMA_displayTable_checkConfigParams();
242 * Need to find the real end of rows?
244 if (isset($find_real_end) && $find_real_end) {
245 $unlim_num_rows = PMA_Table::countRecords($db, $table, $force_exact = true);
246 $_SESSION['tmp_user_values']['pos'] = @((ceil($unlim_num_rows / $_SESSION['tmp_user_values']['max_rows']) - 1) * $_SESSION['tmp_user_values']['max_rows']);
251 * Bookmark add
253 if (isset($store_bkm)) {
254 PMA_Bookmark_save($fields, (isset($bkm_all_users) && $bkm_all_users == 'true' ? true : false));
255 // go back to sql.php to redisplay query; do not use &amp; in this case:
256 PMA_sendHeaderLocation($cfg['PmaAbsoluteUri'] . $goto . '&label=' . $fields['label']);
257 } // end if
260 * Parse and analyze the query
262 require_once './libraries/parse_analyze.lib.php';
265 * Sets or modifies the $goto variable if required
267 if ($goto == 'sql.php') {
268 $is_gotofile = false;
269 $goto = 'sql.php?'
270 . PMA_generate_common_url($db, $table)
271 . '&amp;sql_query=' . urlencode($sql_query);
272 } // end if
276 * Go back to further page if table should not be dropped
278 if (isset($btnDrop) && $btnDrop == __('No')) {
279 if (!empty($back)) {
280 $goto = $back;
282 if ($is_gotofile) {
283 if (strpos($goto, 'db_') === 0 && strlen($table)) {
284 $table = '';
286 $active_page = $goto;
287 require './' . PMA_securePath($goto);
288 } else {
289 PMA_sendHeaderLocation($cfg['PmaAbsoluteUri'] . str_replace('&amp;', '&', $goto));
291 exit();
292 } // end if
296 * Displays the confirm page if required
298 * This part of the script is bypassed if $is_js_confirmed = 1 (already checked
299 * with js) because possible security issue is not so important here: at most,
300 * the confirm message isn't displayed.
302 * Also bypassed if only showing php code.or validating a SQL query
304 if (! $cfg['Confirm'] || isset($_REQUEST['is_js_confirmed']) || isset($btnDrop)
305 // if we are coming from a "Create PHP code" or a "Without PHP Code"
306 // dialog, we won't execute the query anyway, so don't confirm
307 || isset($GLOBALS['show_as_php'])
308 || !empty($GLOBALS['validatequery'])) {
309 $do_confirm = false;
310 } else {
311 $do_confirm = isset($analyzed_sql[0]['queryflags']['need_confirm']);
314 if ($do_confirm) {
315 $stripped_sql_query = $sql_query;
316 require_once './libraries/header.inc.php';
317 if ($is_drop_database) {
318 echo '<h1 class="error">' . __('You are about to DESTROY a complete database!') . '</h1>';
320 echo '<form action="sql.php" method="post">' . "\n"
321 .PMA_generate_common_hidden_inputs($db, $table);
323 <input type="hidden" name="sql_query" value="<?php echo htmlspecialchars($sql_query); ?>" />
324 <input type="hidden" name="message_to_show" value="<?php echo isset($message_to_show) ? PMA_sanitize($message_to_show, true) : ''; ?>" />
325 <input type="hidden" name="goto" value="<?php echo $goto; ?>" />
326 <input type="hidden" name="back" value="<?php echo isset($back) ? PMA_sanitize($back, true) : ''; ?>" />
327 <input type="hidden" name="reload" value="<?php echo isset($reload) ? PMA_sanitize($reload, true) : 0; ?>" />
328 <input type="hidden" name="purge" value="<?php echo isset($purge) ? PMA_sanitize($purge, true) : ''; ?>" />
329 <input type="hidden" name="dropped_column" value="<?php echo isset($dropped_column) ? PMA_sanitize($dropped_column, true) : ''; ?>" />
330 <input type="hidden" name="show_query" value="<?php echo isset($show_query) ? PMA_sanitize($show_query, true) : ''; ?>" />
331 <?php
332 echo '<fieldset class="confirmation">' . "\n"
333 .' <legend>' . __('Do you really want to ') . '</legend>'
334 .' <tt>' . htmlspecialchars($stripped_sql_query) . '</tt>' . "\n"
335 .'</fieldset>' . "\n"
336 .'<fieldset class="tblFooters">' . "\n";
338 <input type="submit" name="btnDrop" value="<?php echo __('Yes'); ?>" id="buttonYes" />
339 <input type="submit" name="btnDrop" value="<?php echo __('No'); ?>" id="buttonNo" />
340 <?php
341 echo '</fieldset>' . "\n"
342 . '</form>' . "\n";
345 * Displays the footer and exit
347 require './libraries/footer.inc.php';
348 } // end if $do_confirm
351 // Defines some variables
352 // A table has to be created, renamed, dropped -> navi frame should be reloaded
354 * @todo use the parser/analyzer
357 if (empty($reload)
358 && preg_match('/^(CREATE|ALTER|DROP)\s+(VIEW|TABLE|DATABASE|SCHEMA)\s+/i', $sql_query)) {
359 $reload = 1;
362 // SK -- Patch: $is_group added for use in calculation of total number of
363 // rows.
364 // $is_count is changed for more correct "LIMIT" clause
365 // appending in queries like
366 // "SELECT COUNT(...) FROM ... GROUP BY ..."
369 * @todo detect all this with the parser, to avoid problems finding
370 * those strings in comments or backquoted identifiers
373 $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;
374 if ($is_select) { // see line 141
375 $is_group = preg_match('@(GROUP[[:space:]]+BY|HAVING|SELECT[[:space:]]+DISTINCT)[[:space:]]+@i', $sql_query);
376 $is_func = !$is_group && (preg_match('@[[:space:]]+(SUM|AVG|STD|STDDEV|MIN|MAX|BIT_OR|BIT_AND)\s*\(@i', $sql_query));
377 $is_count = !$is_group && (preg_match('@^SELECT[[:space:]]+COUNT\((.*\.+)?.*\)@i', $sql_query));
378 $is_export = (preg_match('@[[:space:]]+INTO[[:space:]]+OUTFILE[[:space:]]+@i', $sql_query));
379 $is_analyse = (preg_match('@[[:space:]]+PROCEDURE[[:space:]]+ANALYSE@i', $sql_query));
380 } elseif (preg_match('@^EXPLAIN[[:space:]]+@i', $sql_query)) {
381 $is_explain = true;
382 } elseif (preg_match('@^DELETE[[:space:]]+@i', $sql_query)) {
383 $is_delete = true;
384 $is_affected = true;
385 } elseif (preg_match('@^(INSERT|LOAD[[:space:]]+DATA|REPLACE)[[:space:]]+@i', $sql_query)) {
386 $is_insert = true;
387 $is_affected = true;
388 if (preg_match('@^(REPLACE)[[:space:]]+@i', $sql_query)) {
389 $is_replace = true;
391 } elseif (preg_match('@^UPDATE[[:space:]]+@i', $sql_query)) {
392 $is_affected = true;
393 } elseif (preg_match('@^[[:space:]]*SHOW[[:space:]]+@i', $sql_query)) {
394 $is_show = true;
395 } elseif (preg_match('@^(CHECK|ANALYZE|REPAIR|OPTIMIZE)[[:space:]]+TABLE[[:space:]]+@i', $sql_query)) {
396 $is_maint = true;
399 // assign default full_sql_query
400 $full_sql_query = $sql_query;
402 // Handle remembered sorting order, only for single table query
403 if ($GLOBALS['cfg']['RememberSorting']
404 && ! ($is_count || $is_export || $is_func || $is_analyse)
405 && count($analyzed_sql[0]['select_expr']) == 0
406 && isset($analyzed_sql[0]['queryflags']['select_from'])
407 && count($analyzed_sql[0]['table_ref']) == 1
409 $pmatable = new PMA_Table($table, $db);
410 if (empty($analyzed_sql[0]['order_by_clause'])) {
411 $sorted_col = $pmatable->getUiProp(PMA_Table::PROP_SORTED_COLUMN);
412 if ($sorted_col) {
413 // retrieve the remembered sorting order for current table
414 $sql_order_to_append = ' ORDER BY ' . $sorted_col . ' ';
415 $full_sql_query = $analyzed_sql[0]['section_before_limit'] . $sql_order_to_append . $analyzed_sql[0]['section_after_limit'];
417 // update the $analyzed_sql
418 $analyzed_sql[0]['section_before_limit'] .= $sql_order_to_append;
419 $analyzed_sql[0]['order_by_clause'] = $sorted_col;
421 } else {
422 // store the remembered table into session
423 $pmatable->setUiProp(PMA_Table::PROP_SORTED_COLUMN, $analyzed_sql[0]['order_by_clause']);
427 // Do append a "LIMIT" clause?
428 if ((! $cfg['ShowAll'] || $_SESSION['tmp_user_values']['max_rows'] != 'all')
429 && ! ($is_count || $is_export || $is_func || $is_analyse)
430 && isset($analyzed_sql[0]['queryflags']['select_from'])
431 && ! isset($analyzed_sql[0]['queryflags']['offset'])
432 && empty($analyzed_sql[0]['limit_clause'])
434 $sql_limit_to_append = ' LIMIT ' . $_SESSION['tmp_user_values']['pos'] . ', ' . $_SESSION['tmp_user_values']['max_rows'] . " ";
436 $full_sql_query = $analyzed_sql[0]['section_before_limit'] . "\n" . $sql_limit_to_append . $analyzed_sql[0]['section_after_limit'];
438 * @todo pretty printing of this modified query
440 if (isset($display_query)) {
441 // if the analysis of the original query revealed that we found
442 // a section_after_limit, we now have to analyze $display_query
443 // to display it correctly
445 if (!empty($analyzed_sql[0]['section_after_limit']) && trim($analyzed_sql[0]['section_after_limit']) != ';') {
446 $analyzed_display_query = PMA_SQP_analyze(PMA_SQP_parse($display_query));
447 $display_query = $analyzed_display_query[0]['section_before_limit'] . "\n" . $sql_limit_to_append . $analyzed_display_query[0]['section_after_limit'];
453 if (strlen($db)) {
454 PMA_DBI_select_db($db);
457 // E x e c u t e t h e q u e r y
459 // Only if we didn't ask to see the php code (mikebeck)
460 if (isset($GLOBALS['show_as_php']) || !empty($GLOBALS['validatequery'])) {
461 unset($result);
462 $num_rows = 0;
463 } else {
464 if (isset($_SESSION['profiling']) && PMA_profilingSupported()) {
465 PMA_DBI_query('SET PROFILING=1;');
468 // Measure query time.
469 $querytime_before = array_sum(explode(' ', microtime()));
471 $result = @PMA_DBI_try_query($full_sql_query, null, PMA_DBI_QUERY_STORE);
473 // If a stored procedure was called, there may be more results that are
474 // queued up and waiting to be flushed from the buffer. So let's do that.
475 while (true) {
476 if (! PMA_DBI_more_results()) {
477 break;
479 PMA_DBI_next_result();
482 $querytime_after = array_sum(explode(' ', microtime()));
484 $GLOBALS['querytime'] = $querytime_after - $querytime_before;
486 // Displays an error message if required and stop parsing the script
487 if ($error = PMA_DBI_getError()) {
488 if ($is_gotofile) {
489 if (strpos($goto, 'db_') === 0 && strlen($table)) {
490 $table = '';
492 $active_page = $goto;
493 $message = PMA_Message::rawError($error);
495 if ($GLOBALS['is_ajax_request'] == true) {
496 PMA_ajaxResponse($message, false);
500 * Go to target path.
502 require './' . PMA_securePath($goto);
503 } else {
504 $full_err_url = (preg_match('@^(db|tbl)_@', $err_url))
505 ? $err_url . '&amp;show_query=1&amp;sql_query=' . urlencode($sql_query)
506 : $err_url;
507 PMA_mysqlDie($error, $full_sql_query, '', $full_err_url);
509 exit;
511 unset($error);
513 // Gets the number of rows affected/returned
514 // (This must be done immediately after the query because
515 // mysql_affected_rows() reports about the last query done)
517 if (!$is_affected) {
518 $num_rows = ($result) ? @PMA_DBI_num_rows($result) : 0;
519 } elseif (! isset($num_rows)) {
520 $num_rows = @PMA_DBI_affected_rows();
523 // Grabs the profiling results
524 if (isset($_SESSION['profiling']) && PMA_profilingSupported()) {
525 $profiling_results = PMA_DBI_fetch_result('SHOW PROFILE;');
528 // Checks if the current database has changed
529 // This could happen if the user sends a query like "USE `database`;"
531 * commented out auto-switching to active database - really required?
532 * bug #1814718 win: table list disappears (mixed case db names)
533 * https://sourceforge.net/support/tracker.php?aid=1814718
534 * @todo RELEASE test and comit or rollback before release
535 $current_db = PMA_DBI_fetch_value('SELECT DATABASE()');
536 if ($db !== $current_db) {
537 $db = $current_db;
538 $reload = 1;
540 unset($current_db);
543 // tmpfile remove after convert encoding appended by Y.Kawada
544 if (function_exists('PMA_kanji_file_conv')
545 && (isset($textfile) && file_exists($textfile))) {
546 unlink($textfile);
549 // Counts the total number of rows for the same 'SELECT' query without the
550 // 'LIMIT' clause that may have been programatically added
552 if (empty($sql_limit_to_append)) {
553 $unlim_num_rows = $num_rows;
554 // if we did not append a limit, set this to get a correct
555 // "Showing rows..." message
556 //$_SESSION['tmp_user_values']['max_rows'] = 'all';
557 } elseif ($is_select) {
559 // c o u n t q u e r y
561 // If we are "just browsing", there is only one table,
562 // and no WHERE clause (or just 'WHERE 1 '),
563 // we do a quick count (which uses MaxExactCount) because
564 // SQL_CALC_FOUND_ROWS is not quick on large InnoDB tables
566 // However, do not count again if we did it previously
567 // due to $find_real_end == true
569 if (!$is_group
570 && ! isset($analyzed_sql[0]['queryflags']['union'])
571 && ! isset($analyzed_sql[0]['table_ref'][1]['table_name'])
572 && (empty($analyzed_sql[0]['where_clause'])
573 || $analyzed_sql[0]['where_clause'] == '1 ')
574 && ! isset($find_real_end)
577 // "j u s t b r o w s i n g"
578 $unlim_num_rows = PMA_Table::countRecords($db, $table);
580 } else { // n o t " j u s t b r o w s i n g "
582 // add select expression after the SQL_CALC_FOUND_ROWS
584 // for UNION, just adding SQL_CALC_FOUND_ROWS
585 // after the first SELECT works.
587 // take the left part, could be:
588 // SELECT
589 // (SELECT
590 $count_query = PMA_SQP_formatHtml($parsed_sql, 'query_only', 0, $analyzed_sql[0]['position_of_first_select'] + 1);
591 $count_query .= ' SQL_CALC_FOUND_ROWS ';
592 // add everything that was after the first SELECT
593 $count_query .= PMA_SQP_formatHtml($parsed_sql, 'query_only', $analyzed_sql[0]['position_of_first_select']+1);
594 // ensure there is no semicolon at the end of the
595 // count query because we'll probably add
596 // a LIMIT 1 clause after it
597 $count_query = rtrim($count_query);
598 $count_query = rtrim($count_query, ';');
600 // if using SQL_CALC_FOUND_ROWS, add a LIMIT to avoid
601 // long delays. Returned count will be complete anyway.
602 // (but a LIMIT would disrupt results in an UNION)
604 if (! isset($analyzed_sql[0]['queryflags']['union'])) {
605 $count_query .= ' LIMIT 1';
608 // run the count query
610 PMA_DBI_try_query($count_query);
611 // if (mysql_error()) {
612 // void.
613 // I tried the case
614 // (SELECT `User`, `Host`, `Db`, `Select_priv` FROM `db`)
615 // UNION (SELECT `User`, `Host`, "%" AS "Db",
616 // `Select_priv`
617 // FROM `user`) ORDER BY `User`, `Host`, `Db`;
618 // and although the generated count_query is wrong
619 // the SELECT FOUND_ROWS() work! (maybe it gets the
620 // count from the latest query that worked)
622 // another case where the count_query is wrong:
623 // SELECT COUNT(*), f1 from t1 group by f1
624 // and you click to sort on count(*)
625 // }
626 $unlim_num_rows = PMA_DBI_fetch_value('SELECT FOUND_ROWS()');
627 } // end else "just browsing"
629 } else { // not $is_select
630 $unlim_num_rows = 0;
631 } // end rows total count
633 // if a table or database gets dropped, check column comments.
634 if (isset($purge) && $purge == '1') {
636 * Cleanup relations.
638 require_once './libraries/relation_cleanup.lib.php';
640 if (strlen($table) && strlen($db)) {
641 PMA_relationsCleanupTable($db, $table);
642 } elseif (strlen($db)) {
643 PMA_relationsCleanupDatabase($db);
644 } else {
645 // VOID. No DB/Table gets deleted.
646 } // end if relation-stuff
647 } // end if ($purge)
649 // If a column gets dropped, do relation magic.
650 if (isset($dropped_column) && strlen($db) && strlen($table) && !empty($dropped_column)) {
651 require_once './libraries/relation_cleanup.lib.php';
652 PMA_relationsCleanupColumn($db, $table, $dropped_column);
654 } // end if column was dropped
655 } // end else "didn't ask to see php code"
657 // No rows returned -> move back to the calling page
658 if (0 == $num_rows || $is_affected) {
659 if ($is_delete) {
660 $message = PMA_Message::deleted_rows($num_rows);
661 } elseif ($is_insert) {
662 if ($is_replace) {
663 /* For replace we get DELETED + INSERTED row count, so we have to call it affected */
664 $message = PMA_Message::affected_rows($num_rows);
665 } else {
666 $message = PMA_Message::inserted_rows($num_rows);
668 $insert_id = PMA_DBI_insert_id();
669 if ($insert_id != 0) {
670 // insert_id is id of FIRST record inserted in one insert, so if we inserted multiple rows, we had to increment this
671 $message->addMessage('[br]');
672 // need to use a temporary because the Message class
673 // currently supports adding parameters only to the first
674 // message
675 $_inserted = PMA_Message::notice(__('Inserted row id: %1$d'));
676 $_inserted->addParam($insert_id + $num_rows - 1);
677 $message->addMessage($_inserted);
679 } elseif ($is_affected) {
680 $message = PMA_Message::affected_rows($num_rows);
682 // Ok, here is an explanation for the !$is_select.
683 // The form generated by sql_query_form.lib.php
684 // and db_sql.php has many submit buttons
685 // on the same form, and some confusion arises from the
686 // fact that $message_to_show is sent for every case.
687 // The $message_to_show containing a success message and sent with
688 // the form should not have priority over errors
689 } elseif (!empty($message_to_show) && !$is_select) {
690 $message = PMA_Message::rawSuccess(htmlspecialchars($message_to_show));
691 } elseif (!empty($GLOBALS['show_as_php'])) {
692 $message = PMA_Message::success(__('Showing as PHP code'));
693 } elseif (isset($GLOBALS['show_as_php'])) {
694 /* User disable showing as PHP, query is only displayed */
695 $message = PMA_Message::notice(__('Showing SQL query'));
696 } elseif (!empty($GLOBALS['validatequery'])) {
697 $message = PMA_Message::notice(__('Validated SQL'));
698 } else {
699 $message = PMA_Message::success(__('MySQL returned an empty result set (i.e. zero rows).'));
702 if (isset($GLOBALS['querytime'])) {
703 $_querytime = PMA_Message::notice(__('Query took %01.4f sec'));
704 $_querytime->addParam($GLOBALS['querytime']);
705 $message->addMessage('(');
706 $message->addMessage($_querytime);
707 $message->addMessage(')');
710 if ($GLOBALS['is_ajax_request'] == true) {
711 if ($cfg['ShowSQL']) {
712 $extra_data['sql_query'] = PMA_showMessage($message, $GLOBALS['sql_query'], 'success');
714 if (isset($GLOBALS['reload']) && $GLOBALS['reload'] == 1) {
715 $extra_data['reload'] = 1;
716 $extra_data['db'] = $GLOBALS['db'];
718 PMA_ajaxResponse($message, $message->isSuccess(), (isset($extra_data) ? $extra_data : ''));
721 if ($is_gotofile) {
722 $goto = PMA_securePath($goto);
723 // Checks for a valid target script
724 $is_db = $is_table = false;
725 if (isset($_REQUEST['purge']) && $_REQUEST['purge'] == '1') {
726 $table = '';
727 unset($url_params['table']);
729 include 'libraries/db_table_exists.lib.php';
731 if (strpos($goto, 'tbl_') === 0 && ! $is_table) {
732 if (strlen($table)) {
733 $table = '';
735 $goto = 'db_sql.php';
737 if (strpos($goto, 'db_') === 0 && ! $is_db) {
738 if (strlen($db)) {
739 $db = '';
741 $goto = 'main.php';
743 // Loads to target script
744 if ($goto != 'main.php') {
745 require_once './libraries/header.inc.php';
747 $active_page = $goto;
748 require './' . $goto;
749 } else {
750 // avoid a redirect loop when last record was deleted
751 if (0 == $num_rows && 'sql.php' == $cfg['DefaultTabTable']) {
752 $goto = str_replace('sql.php','tbl_structure.php',$goto);
754 PMA_sendHeaderLocation($cfg['PmaAbsoluteUri'] . str_replace('&amp;', '&', $goto) . '&message=' . urlencode($message));
755 } // end else
756 exit();
757 } // end no rows returned
759 // At least one row is returned -> displays a table with results
760 else {
761 //If we are retrieving the full value of a truncated field or the original
762 // value of a transformed field, show it here and exit
763 if ($GLOBALS['grid_edit'] == true && $GLOBALS['cfg']['AjaxEnable']) {
764 $row = PMA_DBI_fetch_row($result);
765 $extra_data = array();
766 $extra_data['value'] = $row[0];
767 PMA_ajaxResponse(NULL, true, $extra_data);
770 if (isset($_REQUEST['ajax_request']) && isset($_REQUEST['table_maintenance'])) {
771 $GLOBALS['js_include'][] = 'functions.js';
772 $GLOBALS['js_include'][] = 'makegrid.js';
773 $GLOBALS['js_include'][] = 'sql.js';
775 // Gets the list of fields properties
776 if (isset($result) && $result) {
777 $fields_meta = PMA_DBI_get_fields_meta($result);
778 $fields_cnt = count($fields_meta);
781 if (empty($disp_mode)) {
782 // see the "PMA_setDisplayMode()" function in
783 // libraries/display_tbl.lib.php
784 $disp_mode = 'urdr111101';
787 // hide edit and delete links for information_schema
788 if ($db == 'information_schema') {
789 $disp_mode = 'nnnn110111';
792 $message = PMA_Message::success($message);
793 echo PMA_showMessage($message, $GLOBALS['sql_query'], 'success');
794 PMA_displayTable($result, $disp_mode, $analyzed_sql);
795 exit();
798 // Displays the headers
799 if (isset($show_query)) {
800 unset($show_query);
802 if (isset($printview) && $printview == '1') {
803 require_once './libraries/header_printview.inc.php';
804 } else {
806 $GLOBALS['js_include'][] = 'functions.js';
807 $GLOBALS['js_include'][] = 'makegrid.js';
808 $GLOBALS['js_include'][] = 'sql.js';
810 unset($message);
812 if (! $GLOBALS['is_ajax_request'] || ! $GLOBALS['cfg']['AjaxEnable']) {
813 if (strlen($table)) {
814 require './libraries/tbl_common.php';
815 $url_query .= '&amp;goto=tbl_sql.php&amp;back=tbl_sql.php';
816 require './libraries/tbl_info.inc.php';
817 require './libraries/tbl_links.inc.php';
818 } elseif (strlen($db)) {
819 require './libraries/db_common.inc.php';
820 require './libraries/db_info.inc.php';
821 } else {
822 require './libraries/server_common.inc.php';
823 require './libraries/server_links.inc.php';
825 } else {
826 require_once './libraries/header.inc.php';
827 //we don't need to buffer the output in PMA_showMessage here.
828 //set a global variable and check against it in the function
829 $GLOBALS['buffer_message'] = false;
833 if (strlen($db)) {
834 $cfgRelation = PMA_getRelationsParam();
837 // Gets the list of fields properties
838 if (isset($result) && $result) {
839 $fields_meta = PMA_DBI_get_fields_meta($result);
840 $fields_cnt = count($fields_meta);
843 if (! $GLOBALS['is_ajax_request']) {
844 //begin the sqlqueryresults div here. container div
845 echo '<div id="sqlqueryresults"';
846 if ($GLOBALS['cfg']['AjaxEnable']) {
847 echo ' class="ajax"';
849 echo '>';
852 // Display previous update query (from tbl_replace)
853 if (isset($disp_query) && $cfg['ShowSQL'] == true) {
854 PMA_showMessage($disp_message, $disp_query, 'success');
857 if (isset($profiling_results)) {
858 // pma_token/url_query needed for chart export
860 <script type="text/javascript">
861 pma_token = '<?php echo $_SESSION[' PMA_token ']; ?>';
862 url_query = '<?php echo isset($url_query)?$url_query:PMA_generate_common_url($db);?>';
863 $(document).ready(makeProfilingChart);
864 </script>
865 <?php
866 echo '<fieldset><legend>' . __('Profiling') . '</legend>' . "\n";
867 echo '<div style="float: left;">';
868 echo '<table>' . "\n";
869 echo ' <tr>' . "\n";
870 echo ' <th>' . __('Status') . PMA_showMySQLDocu('general-thread-states','general-thread-states') . '</th>' . "\n";
871 echo ' <th>' . __('Time') . '</th>' . "\n";
872 echo ' </tr>' . "\n";
874 $chart_json = Array();
875 foreach ($profiling_results as $one_result) {
876 echo ' <tr>' . "\n";
877 echo '<td>' . ucwords($one_result['Status']) . '</td>' . "\n";
878 echo '<td align="right">' . (PMA_formatNumber($one_result['Duration'],3,1)) . 's</td>' . "\n";
879 $chart_json[ucwords($one_result['Status'])] = $one_result['Duration'];
882 echo '</table>' . "\n";
883 echo '</div>';
884 //require_once './libraries/chart.lib.php';
885 echo '<div id="profilingchart" style="display:none;">';
886 //PMA_chart_profiling($profiling_results);
887 echo json_encode($chart_json);
888 echo '</div>';
889 echo '</fieldset>' . "\n";
892 // Displays the results in a table
893 if (empty($disp_mode)) {
894 // see the "PMA_setDisplayMode()" function in
895 // libraries/display_tbl.lib.php
896 $disp_mode = 'urdr111101';
899 // hide edit and delete links for information_schema
900 if ($db == 'information_schema') {
901 $disp_mode = 'nnnn110111';
904 if (isset($label)) {
905 $message = PMA_message::success(__('Bookmark %s created'));
906 $message->addParam($label);
907 $message->display();
910 PMA_displayTable($result, $disp_mode, $analyzed_sql);
911 PMA_DBI_free_result($result);
913 // BEGIN INDEX CHECK See if indexes should be checked.
914 if (isset($query_type) && $query_type == 'check_tbl' && isset($selected) && is_array($selected)) {
915 foreach ($selected as $idx => $tbl_name) {
916 $check = PMA_Index::findDuplicates($tbl_name, $db);
917 if (! empty($check)) {
918 printf(__('Problems with indexes of table `%s`'), $tbl_name);
919 echo $check;
922 } // End INDEX CHECK
924 // Bookmark support if required
925 if ($disp_mode[7] == '1'
926 && (! empty($cfg['Bookmark']) && empty($id_bookmark))
927 && !empty($sql_query)) {
928 echo "\n";
930 $goto = 'sql.php?'
931 . PMA_generate_common_url($db, $table)
932 . '&amp;sql_query=' . urlencode($sql_query)
933 . '&amp;id_bookmark=1';
936 <form action="sql.php" method="post" onsubmit="return emptyFormElements(this, 'fields[label]');">
937 <?php echo PMA_generate_common_hidden_inputs(); ?>
938 <input type="hidden" name="goto" value="<?php echo $goto; ?>" />
939 <input type="hidden" name="fields[dbase]" value="<?php echo htmlspecialchars($db); ?>" />
940 <input type="hidden" name="fields[user]" value="<?php echo $cfg['Bookmark']['user']; ?>" />
941 <input type="hidden" name="fields[query]" value="<?php echo urlencode(isset($complete_query) ? $complete_query : $sql_query); ?>" />
942 <fieldset>
943 <legend><?php
944 echo PMA_getIcon('b_bookmark.png', __('Bookmark this SQL query'));
946 </legend>
948 <div class="formelement">
949 <label for="fields_label_"><?php echo __('Label'); ?>:</label>
950 <input type="text" id="fields_label_" name="fields[label]" value="" />
951 </div>
953 <div class="formelement">
954 <input type="checkbox" name="bkm_all_users" id="bkm_all_users" value="true" />
955 <label for="bkm_all_users"><?php echo __('Let every user access this bookmark'); ?></label>
956 </div>
958 <div class="clearfloat"></div>
959 </fieldset>
960 <fieldset class="tblFooters">
961 <input type="submit" name="store_bkm" value="<?php echo __('Bookmark this SQL query'); ?>" />
962 </fieldset>
963 </form>
964 <?php
965 } // end bookmark support
967 // Do print the page if required
968 if (isset($printview) && $printview == '1') {
970 <script type="text/javascript">
971 //<![CDATA[
972 // Do print the page
973 window.onload = function()
975 if (typeof(window.print) != 'undefined') {
976 window.print();
979 //]]>
980 </script>
981 <?php
982 } // end print case
984 if ($GLOBALS['is_ajax_request'] != true) {
985 echo '</div>'; // end sqlqueryresults div
987 } // end rows returned
990 * Displays the footer
992 if (! isset($_REQUEST['table_maintenance'])) {
993 require './libraries/footer.inc.php';