More typos
[phpmyadmin/ammaryasirr.git] / sql.php
blobfef6eb1f65814459a843f593a57a919712052297
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>';
100 else {
101 $dropdown = PMA_foreignDropdown($foreignData['disp_row'], $foreignData['foreign_field'], $foreignData['foreign_display'], $curr_value, $cfg['ForeignKeyMaxLimit']);
102 $dropdown = '<select>' . $dropdown . '</select>';
105 $extra_data['dropdown'] = $dropdown;
106 PMA_ajaxResponse(NULL, true, $extra_data);
110 * Just like above, find possible values for enum fields during grid edit.
112 * Logic taken from libraries/display_tbl_lib.php
114 if (isset($_REQUEST['get_enum_values']) && $_REQUEST['get_enum_values'] == true) {
115 $field_info_query = 'SHOW FIELDS FROM `' . $db . '`.`' . $table . '` LIKE \'' . $_REQUEST['column'] . '\' ;';
117 $field_info_result = PMA_DBI_fetch_result($field_info_query, null, null, null, PMA_DBI_QUERY_STORE);
119 $search = array('enum', '(', ')', "'");
121 $values = explode(',', str_replace($search, '', $field_info_result[0]['Type']));
123 $dropdown = '<option value="">&nbsp;</option>';
124 foreach ($values as $value) {
125 $dropdown .= '<option value="' . htmlspecialchars($value) . '"';
126 if ($value == $_REQUEST['curr_value']) {
127 $dropdown .= ' selected="selected"';
129 $dropdown .= '>' . $value . '</option>';
132 $dropdown = '<select>' . $dropdown . '</select>';
134 $extra_data['dropdown'] = $dropdown;
135 PMA_ajaxResponse(NULL, true, $extra_data);
139 * Find possible values for set fields during grid edit.
141 if (isset($_REQUEST['get_set_values']) && $_REQUEST['get_set_values'] == true) {
142 $field_info_query = 'SHOW FIELDS FROM `' . $db . '`.`' . $table . '` LIKE \'' . $_REQUEST['column'] . '\' ;';
144 $field_info_result = PMA_DBI_fetch_result($field_info_query, null, null, null, PMA_DBI_QUERY_STORE);
146 $selected_values = explode(',', $_REQUEST['curr_value']);
148 $search = array('set', '(', ')', "'");
149 $values = explode(',', str_replace($search, '', $field_info_result[0]['Type']));
151 $select = '';
152 foreach ($values as $value) {
153 $select .= '<option value="' . htmlspecialchars($value) . '"';
154 if (in_array($value, $selected_values, true)) {
155 $select .= ' selected="selected"';
157 $select .= '>' . $value . '</option>';
160 $select_size = (sizeof($values) > 10) ? 10 : sizeof($values);
161 $select = '<select multiple="multiple" size="' . $select_size . '">' . $select . '</select>';
163 $extra_data['select'] = $select;
164 PMA_ajaxResponse(NULL, true, $extra_data);
168 * Check ajax request to set the column order
170 if (isset($_REQUEST['set_col_prefs']) && $_REQUEST['set_col_prefs'] == true) {
171 $pmatable = new PMA_Table($table, $db);
172 $retval = false;
174 // set column order
175 if (isset($_REQUEST['col_order'])) {
176 $col_order = explode(',', $_REQUEST['col_order']);
177 $retval = $pmatable->setUiProp(PMA_Table::PROP_COLUMN_ORDER, $col_order, $_REQUEST['table_create_time']);
180 // set column visibility
181 if (isset($_REQUEST['col_visib'])) {
182 $col_visib = explode(',', $_REQUEST['col_visib']);
183 $retval &= $pmatable->setUiProp(PMA_Table::PROP_COLUMN_VISIB, $col_visib, $_REQUEST['table_create_time']);
186 PMA_ajaxResponse(NULL, ($retval == true));
189 // Default to browse if no query set and we have table
190 // (needed for browsing from DefaultTabTable)
191 if (empty($sql_query) && strlen($table) && strlen($db)) {
192 require_once './libraries/bookmark.lib.php';
193 $book_sql_query = PMA_Bookmark_get($db, '\'' . PMA_sqlAddSlashes($table) . '\'',
194 'label', false, true);
196 if (! empty($book_sql_query)) {
197 $GLOBALS['using_bookmark_message'] = PMA_message::notice(__('Using bookmark "%s" as default browse query.'));
198 $GLOBALS['using_bookmark_message']->addParam($table);
199 $GLOBALS['using_bookmark_message']->addMessage(PMA_showDocu('faq6_22'));
200 $sql_query = $book_sql_query;
201 } else {
202 $sql_query = 'SELECT * FROM ' . PMA_backquote($table);
204 unset($book_sql_query);
206 // set $goto to what will be displayed if query returns 0 rows
207 $goto = 'tbl_structure.php';
208 } else {
209 // Now we can check the parameters
210 PMA_checkParameters(array('sql_query'));
213 // instead of doing the test twice
214 $is_drop_database = preg_match('/DROP[[:space:]]+(DATABASE|SCHEMA)[[:space:]]+/i',
215 $sql_query);
218 * Check rights in case of DROP DATABASE
220 * This test may be bypassed if $is_js_confirmed = 1 (already checked with js)
221 * but since a malicious user may pass this variable by url/form, we don't take
222 * into account this case.
224 if (!defined('PMA_CHK_DROP')
225 && !$cfg['AllowUserDropDatabase']
226 && $is_drop_database
227 && !$is_superuser) {
228 require_once './libraries/header.inc.php';
229 PMA_mysqlDie(__('"DROP DATABASE" statements are disabled.'), '', '', $err_url);
230 } // end if
232 require_once './libraries/display_tbl.lib.php';
233 PMA_displayTable_checkConfigParams();
236 * Need to find the real end of rows?
238 if (isset($find_real_end) && $find_real_end) {
239 $unlim_num_rows = PMA_Table::countRecords($db, $table, $force_exact = true);
240 $_SESSION['tmp_user_values']['pos'] = @((ceil($unlim_num_rows / $_SESSION['tmp_user_values']['max_rows']) - 1) * $_SESSION['tmp_user_values']['max_rows']);
245 * Bookmark add
247 if (isset($store_bkm)) {
248 PMA_Bookmark_save($fields, (isset($bkm_all_users) && $bkm_all_users == 'true' ? true : false));
249 // go back to sql.php to redisplay query; do not use &amp; in this case:
250 PMA_sendHeaderLocation($cfg['PmaAbsoluteUri'] . $goto . '&label=' . $fields['label']);
251 } // end if
254 * Parse and analyze the query
256 require_once './libraries/parse_analyze.lib.php';
259 * Sets or modifies the $goto variable if required
261 if ($goto == 'sql.php') {
262 $is_gotofile = false;
263 $goto = 'sql.php?'
264 . PMA_generate_common_url($db, $table)
265 . '&amp;sql_query=' . urlencode($sql_query);
266 } // end if
270 * Go back to further page if table should not be dropped
272 if (isset($btnDrop) && $btnDrop == __('No')) {
273 if (!empty($back)) {
274 $goto = $back;
276 if ($is_gotofile) {
277 if (strpos($goto, 'db_') === 0 && strlen($table)) {
278 $table = '';
280 $active_page = $goto;
281 require './' . PMA_securePath($goto);
282 } else {
283 PMA_sendHeaderLocation($cfg['PmaAbsoluteUri'] . str_replace('&amp;', '&', $goto));
285 exit();
286 } // end if
290 * Displays the confirm page if required
292 * This part of the script is bypassed if $is_js_confirmed = 1 (already checked
293 * with js) because possible security issue is not so important here: at most,
294 * the confirm message isn't displayed.
296 * Also bypassed if only showing php code.or validating a SQL query
298 if (! $cfg['Confirm'] || isset($_REQUEST['is_js_confirmed']) || isset($btnDrop)
299 // if we are coming from a "Create PHP code" or a "Without PHP Code"
300 // dialog, we won't execute the query anyway, so don't confirm
301 || isset($GLOBALS['show_as_php'])
302 || !empty($GLOBALS['validatequery'])) {
303 $do_confirm = false;
304 } else {
305 $do_confirm = isset($analyzed_sql[0]['queryflags']['need_confirm']);
308 if ($do_confirm) {
309 $stripped_sql_query = $sql_query;
310 require_once './libraries/header.inc.php';
311 if ($is_drop_database) {
312 echo '<h1 class="error">' . __('You are about to DESTROY a complete database!') . '</h1>';
314 echo '<form action="sql.php" method="post">' . "\n"
315 .PMA_generate_common_hidden_inputs($db, $table);
317 <input type="hidden" name="sql_query" value="<?php echo htmlspecialchars($sql_query); ?>" />
318 <input type="hidden" name="message_to_show" value="<?php echo isset($message_to_show) ? PMA_sanitize($message_to_show, true) : ''; ?>" />
319 <input type="hidden" name="goto" value="<?php echo $goto; ?>" />
320 <input type="hidden" name="back" value="<?php echo isset($back) ? PMA_sanitize($back, true) : ''; ?>" />
321 <input type="hidden" name="reload" value="<?php echo isset($reload) ? PMA_sanitize($reload, true) : 0; ?>" />
322 <input type="hidden" name="purge" value="<?php echo isset($purge) ? PMA_sanitize($purge, true) : ''; ?>" />
323 <input type="hidden" name="dropped_column" value="<?php echo isset($dropped_column) ? PMA_sanitize($dropped_column, true) : ''; ?>" />
324 <input type="hidden" name="show_query" value="<?php echo isset($show_query) ? PMA_sanitize($show_query, true) : ''; ?>" />
325 <?php
326 echo '<fieldset class="confirmation">' . "\n"
327 .' <legend>' . __('Do you really want to ') . '</legend>'
328 .' <tt>' . htmlspecialchars($stripped_sql_query) . '</tt>' . "\n"
329 .'</fieldset>' . "\n"
330 .'<fieldset class="tblFooters">' . "\n";
332 <input type="submit" name="btnDrop" value="<?php echo __('Yes'); ?>" id="buttonYes" />
333 <input type="submit" name="btnDrop" value="<?php echo __('No'); ?>" id="buttonNo" />
334 <?php
335 echo '</fieldset>' . "\n"
336 . '</form>' . "\n";
339 * Displays the footer and exit
341 require './libraries/footer.inc.php';
342 } // end if $do_confirm
345 // Defines some variables
346 // A table has to be created, renamed, dropped -> navi frame should be reloaded
348 * @todo use the parser/analyzer
351 if (empty($reload)
352 && preg_match('/^(CREATE|ALTER|DROP)\s+(VIEW|TABLE|DATABASE|SCHEMA)\s+/i', $sql_query)) {
353 $reload = 1;
356 // SK -- Patch: $is_group added for use in calculation of total number of
357 // rows.
358 // $is_count is changed for more correct "LIMIT" clause
359 // appending in queries like
360 // "SELECT COUNT(...) FROM ... GROUP BY ..."
363 * @todo detect all this with the parser, to avoid problems finding
364 * those strings in comments or backquoted identifiers
367 $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;
368 if ($is_select) { // see line 141
369 $is_group = preg_match('@(GROUP[[:space:]]+BY|HAVING|SELECT[[:space:]]+DISTINCT)[[:space:]]+@i', $sql_query);
370 $is_func = !$is_group && (preg_match('@[[:space:]]+(SUM|AVG|STD|STDDEV|MIN|MAX|BIT_OR|BIT_AND)\s*\(@i', $sql_query));
371 $is_count = !$is_group && (preg_match('@^SELECT[[:space:]]+COUNT\((.*\.+)?.*\)@i', $sql_query));
372 $is_export = (preg_match('@[[:space:]]+INTO[[:space:]]+OUTFILE[[:space:]]+@i', $sql_query));
373 $is_analyse = (preg_match('@[[:space:]]+PROCEDURE[[:space:]]+ANALYSE@i', $sql_query));
374 } elseif (preg_match('@^EXPLAIN[[:space:]]+@i', $sql_query)) {
375 $is_explain = true;
376 } elseif (preg_match('@^DELETE[[:space:]]+@i', $sql_query)) {
377 $is_delete = true;
378 $is_affected = true;
379 } elseif (preg_match('@^(INSERT|LOAD[[:space:]]+DATA|REPLACE)[[:space:]]+@i', $sql_query)) {
380 $is_insert = true;
381 $is_affected = true;
382 if (preg_match('@^(REPLACE)[[:space:]]+@i', $sql_query)) {
383 $is_replace = true;
385 } elseif (preg_match('@^UPDATE[[:space:]]+@i', $sql_query)) {
386 $is_affected = true;
387 } elseif (preg_match('@^[[:space:]]*SHOW[[:space:]]+@i', $sql_query)) {
388 $is_show = true;
389 } elseif (preg_match('@^(CHECK|ANALYZE|REPAIR|OPTIMIZE)[[:space:]]+TABLE[[:space:]]+@i', $sql_query)) {
390 $is_maint = true;
393 // assign default full_sql_query
394 $full_sql_query = $sql_query;
396 // Handle remembered sorting order, only for single table query
397 if ($GLOBALS['cfg']['RememberSorting']
398 && ! ($is_count || $is_export || $is_func || $is_analyse)
399 && count($analyzed_sql[0]['select_expr']) == 0
400 && isset($analyzed_sql[0]['queryflags']['select_from'])
401 && count($analyzed_sql[0]['table_ref']) == 1
403 $pmatable = new PMA_Table($table, $db);
404 if (empty($analyzed_sql[0]['order_by_clause'])) {
405 $sorted_col = $pmatable->getUiProp(PMA_Table::PROP_SORTED_COLUMN);
406 if ($sorted_col) {
407 // retrieve the remembered sorting order for current table
408 $sql_order_to_append = ' ORDER BY ' . $sorted_col . ' ';
409 $full_sql_query = $analyzed_sql[0]['section_before_limit'] . $sql_order_to_append . $analyzed_sql[0]['section_after_limit'];
411 // update the $analyzed_sql
412 $analyzed_sql[0]['section_before_limit'] .= $sql_order_to_append;
413 $analyzed_sql[0]['order_by_clause'] = $sorted_col;
415 } else {
416 // store the remembered table into session
417 $pmatable->setUiProp(PMA_Table::PROP_SORTED_COLUMN, $analyzed_sql[0]['order_by_clause']);
421 // Do append a "LIMIT" clause?
422 if ((! $cfg['ShowAll'] || $_SESSION['tmp_user_values']['max_rows'] != 'all')
423 && ! ($is_count || $is_export || $is_func || $is_analyse)
424 && isset($analyzed_sql[0]['queryflags']['select_from'])
425 && ! isset($analyzed_sql[0]['queryflags']['offset'])
426 && empty($analyzed_sql[0]['limit_clause'])
428 $sql_limit_to_append = ' LIMIT ' . $_SESSION['tmp_user_values']['pos'] . ', ' . $_SESSION['tmp_user_values']['max_rows'] . " ";
430 $full_sql_query = $analyzed_sql[0]['section_before_limit'] . "\n" . $sql_limit_to_append . $analyzed_sql[0]['section_after_limit'];
432 * @todo pretty printing of this modified query
434 if (isset($display_query)) {
435 // if the analysis of the original query revealed that we found
436 // a section_after_limit, we now have to analyze $display_query
437 // to display it correctly
439 if (!empty($analyzed_sql[0]['section_after_limit']) && trim($analyzed_sql[0]['section_after_limit']) != ';') {
440 $analyzed_display_query = PMA_SQP_analyze(PMA_SQP_parse($display_query));
441 $display_query = $analyzed_display_query[0]['section_before_limit'] . "\n" . $sql_limit_to_append . $analyzed_display_query[0]['section_after_limit'];
447 if (strlen($db)) {
448 PMA_DBI_select_db($db);
451 // E x e c u t e t h e q u e r y
453 // Only if we didn't ask to see the php code (mikebeck)
454 if (isset($GLOBALS['show_as_php']) || !empty($GLOBALS['validatequery'])) {
455 unset($result);
456 $num_rows = 0;
457 } else {
458 if (isset($_SESSION['profiling']) && PMA_profilingSupported()) {
459 PMA_DBI_query('SET PROFILING=1;');
462 // Measure query time.
463 $querytime_before = array_sum(explode(' ', microtime()));
465 $result = @PMA_DBI_try_query($full_sql_query, null, PMA_DBI_QUERY_STORE);
467 // If a stored procedure was called, there may be more results that are
468 // queued up and waiting to be flushed from the buffer. So let's do that.
469 while (true) {
470 if (! PMA_DBI_more_results()) {
471 break;
473 PMA_DBI_next_result();
476 $querytime_after = array_sum(explode(' ', microtime()));
478 $GLOBALS['querytime'] = $querytime_after - $querytime_before;
480 // Displays an error message if required and stop parsing the script
481 if ($error = PMA_DBI_getError()) {
482 if ($is_gotofile) {
483 if (strpos($goto, 'db_') === 0 && strlen($table)) {
484 $table = '';
486 $active_page = $goto;
487 $message = PMA_Message::rawError($error);
489 if ($GLOBALS['is_ajax_request'] == true) {
490 PMA_ajaxResponse($message, false);
494 * Go to target path.
496 require './' . PMA_securePath($goto);
497 } else {
498 $full_err_url = (preg_match('@^(db|tbl)_@', $err_url))
499 ? $err_url . '&amp;show_query=1&amp;sql_query=' . urlencode($sql_query)
500 : $err_url;
501 PMA_mysqlDie($error, $full_sql_query, '', $full_err_url);
503 exit;
505 unset($error);
507 // Gets the number of rows affected/returned
508 // (This must be done immediately after the query because
509 // mysql_affected_rows() reports about the last query done)
511 if (!$is_affected) {
512 $num_rows = ($result) ? @PMA_DBI_num_rows($result) : 0;
513 } elseif (! isset($num_rows)) {
514 $num_rows = @PMA_DBI_affected_rows();
517 // Grabs the profiling results
518 if (isset($_SESSION['profiling']) && PMA_profilingSupported()) {
519 $profiling_results = PMA_DBI_fetch_result('SHOW PROFILE;');
522 // Checks if the current database has changed
523 // This could happen if the user sends a query like "USE `database`;"
525 * commented out auto-switching to active database - really required?
526 * bug #1814718 win: table list disappears (mixed case db names)
527 * https://sourceforge.net/support/tracker.php?aid=1814718
528 * @todo RELEASE test and comit or rollback before release
529 $current_db = PMA_DBI_fetch_value('SELECT DATABASE()');
530 if ($db !== $current_db) {
531 $db = $current_db;
532 $reload = 1;
534 unset($current_db);
537 // tmpfile remove after convert encoding appended by Y.Kawada
538 if (function_exists('PMA_kanji_file_conv')
539 && (isset($textfile) && file_exists($textfile))) {
540 unlink($textfile);
543 // Counts the total number of rows for the same 'SELECT' query without the
544 // 'LIMIT' clause that may have been programatically added
546 if (empty($sql_limit_to_append)) {
547 $unlim_num_rows = $num_rows;
548 // if we did not append a limit, set this to get a correct
549 // "Showing rows..." message
550 //$_SESSION['tmp_user_values']['max_rows'] = 'all';
551 } elseif ($is_select) {
553 // c o u n t q u e r y
555 // If we are "just browsing", there is only one table,
556 // and no WHERE clause (or just 'WHERE 1 '),
557 // we do a quick count (which uses MaxExactCount) because
558 // SQL_CALC_FOUND_ROWS is not quick on large InnoDB tables
560 // However, do not count again if we did it previously
561 // due to $find_real_end == true
563 if (!$is_group
564 && ! isset($analyzed_sql[0]['queryflags']['union'])
565 && ! isset($analyzed_sql[0]['table_ref'][1]['table_name'])
566 && (empty($analyzed_sql[0]['where_clause'])
567 || $analyzed_sql[0]['where_clause'] == '1 ')
568 && ! isset($find_real_end)
571 // "j u s t b r o w s i n g"
572 $unlim_num_rows = PMA_Table::countRecords($db, $table);
574 } else { // n o t " j u s t b r o w s i n g "
576 // add select expression after the SQL_CALC_FOUND_ROWS
578 // for UNION, just adding SQL_CALC_FOUND_ROWS
579 // after the first SELECT works.
581 // take the left part, could be:
582 // SELECT
583 // (SELECT
584 $count_query = PMA_SQP_formatHtml($parsed_sql, 'query_only', 0, $analyzed_sql[0]['position_of_first_select'] + 1);
585 $count_query .= ' SQL_CALC_FOUND_ROWS ';
586 // add everything that was after the first SELECT
587 $count_query .= PMA_SQP_formatHtml($parsed_sql, 'query_only', $analyzed_sql[0]['position_of_first_select']+1);
588 // ensure there is no semicolon at the end of the
589 // count query because we'll probably add
590 // a LIMIT 1 clause after it
591 $count_query = rtrim($count_query);
592 $count_query = rtrim($count_query, ';');
594 // if using SQL_CALC_FOUND_ROWS, add a LIMIT to avoid
595 // long delays. Returned count will be complete anyway.
596 // (but a LIMIT would disrupt results in an UNION)
598 if (! isset($analyzed_sql[0]['queryflags']['union'])) {
599 $count_query .= ' LIMIT 1';
602 // run the count query
604 PMA_DBI_try_query($count_query);
605 // if (mysql_error()) {
606 // void.
607 // I tried the case
608 // (SELECT `User`, `Host`, `Db`, `Select_priv` FROM `db`)
609 // UNION (SELECT `User`, `Host`, "%" AS "Db",
610 // `Select_priv`
611 // FROM `user`) ORDER BY `User`, `Host`, `Db`;
612 // and although the generated count_query is wrong
613 // the SELECT FOUND_ROWS() work! (maybe it gets the
614 // count from the latest query that worked)
616 // another case where the count_query is wrong:
617 // SELECT COUNT(*), f1 from t1 group by f1
618 // and you click to sort on count(*)
619 // }
620 $unlim_num_rows = PMA_DBI_fetch_value('SELECT FOUND_ROWS()');
621 } // end else "just browsing"
623 } else { // not $is_select
624 $unlim_num_rows = 0;
625 } // end rows total count
627 // if a table or database gets dropped, check column comments.
628 if (isset($purge) && $purge == '1') {
630 * Cleanup relations.
632 require_once './libraries/relation_cleanup.lib.php';
634 if (strlen($table) && strlen($db)) {
635 PMA_relationsCleanupTable($db, $table);
636 } elseif (strlen($db)) {
637 PMA_relationsCleanupDatabase($db);
638 } else {
639 // VOID. No DB/Table gets deleted.
640 } // end if relation-stuff
641 } // end if ($purge)
643 // If a column gets dropped, do relation magic.
644 if (isset($dropped_column) && strlen($db) && strlen($table) && !empty($dropped_column)) {
645 require_once './libraries/relation_cleanup.lib.php';
646 PMA_relationsCleanupColumn($db, $table, $dropped_column);
648 } // end if column was dropped
649 } // end else "didn't ask to see php code"
651 // No rows returned -> move back to the calling page
652 if (0 == $num_rows || $is_affected) {
653 if ($is_delete) {
654 $message = PMA_Message::deleted_rows($num_rows);
655 } elseif ($is_insert) {
656 if ($is_replace) {
657 /* For replace we get DELETED + INSERTED row count, so we have to call it affected */
658 $message = PMA_Message::affected_rows($num_rows);
659 } else {
660 $message = PMA_Message::inserted_rows($num_rows);
662 $insert_id = PMA_DBI_insert_id();
663 if ($insert_id != 0) {
664 // insert_id is id of FIRST record inserted in one insert, so if we inserted multiple rows, we had to increment this
665 $message->addMessage('[br]');
666 // need to use a temporary because the Message class
667 // currently supports adding parameters only to the first
668 // message
669 $_inserted = PMA_Message::notice(__('Inserted row id: %1$d'));
670 $_inserted->addParam($insert_id + $num_rows - 1);
671 $message->addMessage($_inserted);
673 } elseif ($is_affected) {
674 $message = PMA_Message::affected_rows($num_rows);
676 // Ok, here is an explanation for the !$is_select.
677 // The form generated by sql_query_form.lib.php
678 // and db_sql.php has many submit buttons
679 // on the same form, and some confusion arises from the
680 // fact that $message_to_show is sent for every case.
681 // The $message_to_show containing a success message and sent with
682 // the form should not have priority over errors
683 } elseif (!empty($message_to_show) && !$is_select) {
684 $message = PMA_Message::rawSuccess(htmlspecialchars($message_to_show));
685 } elseif (!empty($GLOBALS['show_as_php'])) {
686 $message = PMA_Message::success(__('Showing as PHP code'));
687 } elseif (isset($GLOBALS['show_as_php'])) {
688 /* User disable showing as PHP, query is only displayed */
689 $message = PMA_Message::notice(__('Showing SQL query'));
690 } elseif (!empty($GLOBALS['validatequery'])) {
691 $message = PMA_Message::notice(__('Validated SQL'));
692 } else {
693 $message = PMA_Message::success(__('MySQL returned an empty result set (i.e. zero rows).'));
696 if (isset($GLOBALS['querytime'])) {
697 $_querytime = PMA_Message::notice(__('Query took %01.4f sec'));
698 $_querytime->addParam($GLOBALS['querytime']);
699 $message->addMessage('(');
700 $message->addMessage($_querytime);
701 $message->addMessage(')');
704 if ($GLOBALS['is_ajax_request'] == true) {
705 if ($cfg['ShowSQL']) {
706 $extra_data['sql_query'] = PMA_showMessage($message, $GLOBALS['sql_query'], 'success');
708 if (isset($GLOBALS['reload']) && $GLOBALS['reload'] == 1) {
709 $extra_data['reload'] = 1;
710 $extra_data['db'] = $GLOBALS['db'];
712 PMA_ajaxResponse($message, $message->isSuccess(), (isset($extra_data) ? $extra_data : ''));
715 if ($is_gotofile) {
716 $goto = PMA_securePath($goto);
717 // Checks for a valid target script
718 $is_db = $is_table = false;
719 if (isset($_REQUEST['purge']) && $_REQUEST['purge'] == '1') {
720 $table = '';
721 unset($url_params['table']);
723 include 'libraries/db_table_exists.lib.php';
725 if (strpos($goto, 'tbl_') === 0 && ! $is_table) {
726 if (strlen($table)) {
727 $table = '';
729 $goto = 'db_sql.php';
731 if (strpos($goto, 'db_') === 0 && ! $is_db) {
732 if (strlen($db)) {
733 $db = '';
735 $goto = 'main.php';
737 // Loads to target script
738 if ($goto != 'main.php') {
739 require_once './libraries/header.inc.php';
741 $active_page = $goto;
742 require './' . $goto;
743 } else {
744 // avoid a redirect loop when last record was deleted
745 if (0 == $num_rows && 'sql.php' == $cfg['DefaultTabTable']) {
746 $goto = str_replace('sql.php','tbl_structure.php',$goto);
748 PMA_sendHeaderLocation($cfg['PmaAbsoluteUri'] . str_replace('&amp;', '&', $goto) . '&message=' . urlencode($message));
749 } // end else
750 exit();
751 } // end no rows returned
753 // At least one row is returned -> displays a table with results
754 else {
755 //If we are retrieving the full value of a truncated field or the original
756 // value of a transformed field, show it here and exit
757 if ($GLOBALS['grid_edit'] == true && $GLOBALS['cfg']['AjaxEnable']) {
758 $row = PMA_DBI_fetch_row($result);
759 $extra_data = array();
760 $extra_data['value'] = $row[0];
761 PMA_ajaxResponse(NULL, true, $extra_data);
764 // Displays the headers
765 if (isset($show_query)) {
766 unset($show_query);
768 if (isset($printview) && $printview == '1') {
769 require_once './libraries/header_printview.inc.php';
770 } else {
772 $GLOBALS['js_include'][] = 'functions.js';
773 $GLOBALS['js_include'][] = 'makegrid.js';
774 $GLOBALS['js_include'][] = 'sql.js';
776 unset($message);
778 if (! $GLOBALS['is_ajax_request'] || ! $GLOBALS['cfg']['AjaxEnable']) {
779 if (strlen($table)) {
780 require './libraries/tbl_common.php';
781 $url_query .= '&amp;goto=tbl_sql.php&amp;back=tbl_sql.php';
782 require './libraries/tbl_info.inc.php';
783 require './libraries/tbl_links.inc.php';
784 } elseif (strlen($db)) {
785 require './libraries/db_common.inc.php';
786 require './libraries/db_info.inc.php';
787 } else {
788 require './libraries/server_common.inc.php';
789 require './libraries/server_links.inc.php';
792 else {
793 require_once './libraries/header.inc.php';
794 //we don't need to buffer the output in PMA_showMessage here.
795 //set a global variable and check against it in the function
796 $GLOBALS['buffer_message'] = false;
800 if (strlen($db)) {
801 $cfgRelation = PMA_getRelationsParam();
804 // Gets the list of fields properties
805 if (isset($result) && $result) {
806 $fields_meta = PMA_DBI_get_fields_meta($result);
807 $fields_cnt = count($fields_meta);
810 if (! $GLOBALS['is_ajax_request']) {
811 //begin the sqlqueryresults div here. container div
812 echo '<div id="sqlqueryresults"';
813 if ($GLOBALS['cfg']['AjaxEnable']) {
814 echo ' class="ajax"';
816 echo '>';
819 // Display previous update query (from tbl_replace)
820 if (isset($disp_query) && $cfg['ShowSQL'] == true) {
821 PMA_showMessage($disp_message, $disp_query, 'success');
824 if (isset($profiling_results)) {
825 // pma_token/url_query needed for chart export
827 <script type="text/javascript">
828 pma_token = '<?php echo $_SESSION[' PMA_token ']; ?>';
829 url_query = '<?php echo isset($url_query)?$url_query:PMA_generate_common_url($db);?>';
830 $(document).ready(makeProfilingChart);
831 </script>
832 <?php
833 echo '<fieldset><legend>' . __('Profiling') . '</legend>' . "\n";
834 echo '<div style="float: left;">';
835 echo '<table>' . "\n";
836 echo ' <tr>' . "\n";
837 echo ' <th>' . __('Status') . PMA_showMySQLDocu('general-thread-states','general-thread-states') . '</th>' . "\n";
838 echo ' <th>' . __('Time') . '</th>' . "\n";
839 echo ' </tr>' . "\n";
841 $chart_json = Array();
842 foreach ($profiling_results as $one_result) {
843 echo ' <tr>' . "\n";
844 echo '<td>' . ucwords($one_result['Status']) . '</td>' . "\n";
845 echo '<td align="right">' . (PMA_formatNumber($one_result['Duration'],3,1)) . 's</td>' . "\n";
846 $chart_json[ucwords($one_result['Status'])] = $one_result['Duration'];
849 echo '</table>' . "\n";
850 echo '</div>';
851 //require_once './libraries/chart.lib.php';
852 echo '<div id="profilingchart" style="display:none;">';
853 //PMA_chart_profiling($profiling_results);
854 echo json_encode($chart_json);
855 echo '</div>';
856 echo '</fieldset>' . "\n";
859 // Displays the results in a table
860 if (empty($disp_mode)) {
861 // see the "PMA_setDisplayMode()" function in
862 // libraries/display_tbl.lib.php
863 $disp_mode = 'urdr111101';
866 // hide edit and delete links for information_schema
867 if ($db == 'information_schema') {
868 $disp_mode = 'nnnn110111';
871 if (isset($label)) {
872 $message = PMA_message::success(__('Bookmark %s created'));
873 $message->addParam($label);
874 $message->display();
877 PMA_displayTable($result, $disp_mode, $analyzed_sql);
878 PMA_DBI_free_result($result);
880 // BEGIN INDEX CHECK See if indexes should be checked.
881 if (isset($query_type) && $query_type == 'check_tbl' && isset($selected) && is_array($selected)) {
882 foreach ($selected as $idx => $tbl_name) {
883 $check = PMA_Index::findDuplicates($tbl_name, $db);
884 if (! empty($check)) {
885 printf(__('Problems with indexes of table `%s`'), $tbl_name);
886 echo $check;
889 } // End INDEX CHECK
891 // Bookmark support if required
892 if ($disp_mode[7] == '1'
893 && (! empty($cfg['Bookmark']) && empty($id_bookmark))
894 && !empty($sql_query)) {
895 echo "\n";
897 $goto = 'sql.php?'
898 . PMA_generate_common_url($db, $table)
899 . '&amp;sql_query=' . urlencode($sql_query)
900 . '&amp;id_bookmark=1';
903 <form action="sql.php" method="post" onsubmit="return emptyFormElements(this, 'fields[label]');">
904 <?php echo PMA_generate_common_hidden_inputs(); ?>
905 <input type="hidden" name="goto" value="<?php echo $goto; ?>" />
906 <input type="hidden" name="fields[dbase]" value="<?php echo htmlspecialchars($db); ?>" />
907 <input type="hidden" name="fields[user]" value="<?php echo $cfg['Bookmark']['user']; ?>" />
908 <input type="hidden" name="fields[query]" value="<?php echo urlencode(isset($complete_query) ? $complete_query : $sql_query); ?>" />
909 <fieldset>
910 <legend><?php
911 echo PMA_getIcon('b_bookmark.png', __('Bookmark this SQL query'));
913 </legend>
915 <div class="formelement">
916 <label for="fields_label_"><?php echo __('Label'); ?>:</label>
917 <input type="text" id="fields_label_" name="fields[label]" value="" />
918 </div>
920 <div class="formelement">
921 <input type="checkbox" name="bkm_all_users" id="bkm_all_users" value="true" />
922 <label for="bkm_all_users"><?php echo __('Let every user access this bookmark'); ?></label>
923 </div>
925 <div class="clearfloat"></div>
926 </fieldset>
927 <fieldset class="tblFooters">
928 <input type="submit" name="store_bkm" value="<?php echo __('Bookmark this SQL query'); ?>" />
929 </fieldset>
930 </form>
931 <?php
932 } // end bookmark support
934 // Do print the page if required
935 if (isset($printview) && $printview == '1') {
937 <script type="text/javascript">
938 //<![CDATA[
939 // Do print the page
940 window.onload = function()
942 if (typeof(window.print) != 'undefined') {
943 window.print();
946 //]]>
947 </script>
948 <?php
949 } // end print case
951 if ($GLOBALS['is_ajax_request'] != true) {
952 echo '</div>'; // end sqlqueryresults div
954 } // end rows returned
957 * Displays the footer
959 if (! isset($_REQUEST['table_maintenance'])) {
960 require './libraries/footer.inc.php';