Fix format string
[phpmyadmin/madhuracj.git] / sql.php
blobe41b60267625a64f90c3cb903cc8936605586537
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);
173 // set column order
174 $col_order = explode(',', $_REQUEST['col_order']);
175 $retval = $pmatable->setUiProp(PMA_Table::PROP_COLUMN_ORDER, $col_order, $_REQUEST['table_create_time']);
177 // set column visibility
178 $col_visib = explode(',', $_REQUEST['col_visib']);
179 $retval &= $pmatable->setUiProp(PMA_Table::PROP_COLUMN_VISIB, $col_visib, $_REQUEST['table_create_time']);
181 PMA_ajaxResponse(NULL, ($retval == true));
184 // Default to browse if no query set and we have table
185 // (needed for browsing from DefaultTabTable)
186 if (empty($sql_query) && strlen($table) && strlen($db)) {
187 require_once './libraries/bookmark.lib.php';
188 $book_sql_query = PMA_Bookmark_get($db, '\'' . PMA_sqlAddSlashes($table) . '\'',
189 'label', false, true);
191 if (! empty($book_sql_query)) {
192 $GLOBALS['using_bookmark_message'] = PMA_message::notice(__('Using bookmark "%s" as default browse query.'));
193 $GLOBALS['using_bookmark_message']->addParam($table);
194 $GLOBALS['using_bookmark_message']->addMessage(PMA_showDocu('faq6_22'));
195 $sql_query = $book_sql_query;
196 } else {
197 $sql_query = 'SELECT * FROM ' . PMA_backquote($table);
199 unset($book_sql_query);
201 // set $goto to what will be displayed if query returns 0 rows
202 $goto = 'tbl_structure.php';
203 } else {
204 // Now we can check the parameters
205 PMA_checkParameters(array('sql_query'));
208 // instead of doing the test twice
209 $is_drop_database = preg_match('/DROP[[:space:]]+(DATABASE|SCHEMA)[[:space:]]+/i',
210 $sql_query);
213 * Check rights in case of DROP DATABASE
215 * This test may be bypassed if $is_js_confirmed = 1 (already checked with js)
216 * but since a malicious user may pass this variable by url/form, we don't take
217 * into account this case.
219 if (!defined('PMA_CHK_DROP')
220 && !$cfg['AllowUserDropDatabase']
221 && $is_drop_database
222 && !$is_superuser) {
223 require_once './libraries/header.inc.php';
224 PMA_mysqlDie(__('"DROP DATABASE" statements are disabled.'), '', '', $err_url);
225 } // end if
227 require_once './libraries/display_tbl.lib.php';
228 PMA_displayTable_checkConfigParams();
231 * Need to find the real end of rows?
233 if (isset($find_real_end) && $find_real_end) {
234 $unlim_num_rows = PMA_Table::countRecords($db, $table, $force_exact = true);
235 $_SESSION['tmp_user_values']['pos'] = @((ceil($unlim_num_rows / $_SESSION['tmp_user_values']['max_rows']) - 1) * $_SESSION['tmp_user_values']['max_rows']);
240 * Bookmark add
242 if (isset($store_bkm)) {
243 PMA_Bookmark_save($fields, (isset($bkm_all_users) && $bkm_all_users == 'true' ? true : false));
244 // go back to sql.php to redisplay query; do not use &amp; in this case:
245 PMA_sendHeaderLocation($cfg['PmaAbsoluteUri'] . $goto . '&label=' . $fields['label']);
246 } // end if
249 * Parse and analyze the query
251 require_once './libraries/parse_analyze.lib.php';
254 * Sets or modifies the $goto variable if required
256 if ($goto == 'sql.php') {
257 $is_gotofile = false;
258 $goto = 'sql.php?'
259 . PMA_generate_common_url($db, $table)
260 . '&amp;sql_query=' . urlencode($sql_query);
261 } // end if
265 * Go back to further page if table should not be dropped
267 if (isset($btnDrop) && $btnDrop == __('No')) {
268 if (!empty($back)) {
269 $goto = $back;
271 if ($is_gotofile) {
272 if (strpos($goto, 'db_') === 0 && strlen($table)) {
273 $table = '';
275 $active_page = $goto;
276 require './' . PMA_securePath($goto);
277 } else {
278 PMA_sendHeaderLocation($cfg['PmaAbsoluteUri'] . str_replace('&amp;', '&', $goto));
280 exit();
281 } // end if
285 * Displays the confirm page if required
287 * This part of the script is bypassed if $is_js_confirmed = 1 (already checked
288 * with js) because possible security issue is not so important here: at most,
289 * the confirm message isn't displayed.
291 * Also bypassed if only showing php code.or validating a SQL query
293 if (! $cfg['Confirm'] || isset($_REQUEST['is_js_confirmed']) || isset($btnDrop)
294 // if we are coming from a "Create PHP code" or a "Without PHP Code"
295 // dialog, we won't execute the query anyway, so don't confirm
296 || isset($GLOBALS['show_as_php'])
297 || !empty($GLOBALS['validatequery'])) {
298 $do_confirm = false;
299 } else {
300 $do_confirm = isset($analyzed_sql[0]['queryflags']['need_confirm']);
303 if ($do_confirm) {
304 $stripped_sql_query = $sql_query;
305 require_once './libraries/header.inc.php';
306 if ($is_drop_database) {
307 echo '<h1 class="error">' . __('You are about to DESTROY a complete database!') . '</h1>';
309 echo '<form action="sql.php" method="post">' . "\n"
310 .PMA_generate_common_hidden_inputs($db, $table);
312 <input type="hidden" name="sql_query" value="<?php echo htmlspecialchars($sql_query); ?>" />
313 <input type="hidden" name="message_to_show" value="<?php echo isset($message_to_show) ? PMA_sanitize($message_to_show, true) : ''; ?>" />
314 <input type="hidden" name="goto" value="<?php echo $goto; ?>" />
315 <input type="hidden" name="back" value="<?php echo isset($back) ? PMA_sanitize($back, true) : ''; ?>" />
316 <input type="hidden" name="reload" value="<?php echo isset($reload) ? PMA_sanitize($reload, true) : 0; ?>" />
317 <input type="hidden" name="purge" value="<?php echo isset($purge) ? PMA_sanitize($purge, true) : ''; ?>" />
318 <input type="hidden" name="dropped_column" value="<?php echo isset($dropped_column) ? PMA_sanitize($dropped_column, true) : ''; ?>" />
319 <input type="hidden" name="show_query" value="<?php echo isset($show_query) ? PMA_sanitize($show_query, true) : ''; ?>" />
320 <?php
321 echo '<fieldset class="confirmation">' . "\n"
322 .' <legend>' . __('Do you really want to ') . '</legend>'
323 .' <tt>' . htmlspecialchars($stripped_sql_query) . '</tt>' . "\n"
324 .'</fieldset>' . "\n"
325 .'<fieldset class="tblFooters">' . "\n";
327 <input type="submit" name="btnDrop" value="<?php echo __('Yes'); ?>" id="buttonYes" />
328 <input type="submit" name="btnDrop" value="<?php echo __('No'); ?>" id="buttonNo" />
329 <?php
330 echo '</fieldset>' . "\n"
331 . '</form>' . "\n";
334 * Displays the footer and exit
336 require './libraries/footer.inc.php';
337 } // end if $do_confirm
340 // Defines some variables
341 // A table has to be created, renamed, dropped -> navi frame should be reloaded
343 * @todo use the parser/analyzer
346 if (empty($reload)
347 && preg_match('/^(CREATE|ALTER|DROP)\s+(VIEW|TABLE|DATABASE|SCHEMA)\s+/i', $sql_query)) {
348 $reload = 1;
351 // SK -- Patch: $is_group added for use in calculation of total number of
352 // rows.
353 // $is_count is changed for more correct "LIMIT" clause
354 // appending in queries like
355 // "SELECT COUNT(...) FROM ... GROUP BY ..."
358 * @todo detect all this with the parser, to avoid problems finding
359 * those strings in comments or backquoted identifiers
362 $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;
363 if ($is_select) { // see line 141
364 $is_group = preg_match('@(GROUP[[:space:]]+BY|HAVING|SELECT[[:space:]]+DISTINCT)[[:space:]]+@i', $sql_query);
365 $is_func = !$is_group && (preg_match('@[[:space:]]+(SUM|AVG|STD|STDDEV|MIN|MAX|BIT_OR|BIT_AND)\s*\(@i', $sql_query));
366 $is_count = !$is_group && (preg_match('@^SELECT[[:space:]]+COUNT\((.*\.+)?.*\)@i', $sql_query));
367 $is_export = (preg_match('@[[:space:]]+INTO[[:space:]]+OUTFILE[[:space:]]+@i', $sql_query));
368 $is_analyse = (preg_match('@[[:space:]]+PROCEDURE[[:space:]]+ANALYSE@i', $sql_query));
369 } elseif (preg_match('@^EXPLAIN[[:space:]]+@i', $sql_query)) {
370 $is_explain = true;
371 } elseif (preg_match('@^DELETE[[:space:]]+@i', $sql_query)) {
372 $is_delete = true;
373 $is_affected = true;
374 } elseif (preg_match('@^(INSERT|LOAD[[:space:]]+DATA|REPLACE)[[:space:]]+@i', $sql_query)) {
375 $is_insert = true;
376 $is_affected = true;
377 if (preg_match('@^(REPLACE)[[:space:]]+@i', $sql_query)) {
378 $is_replace = true;
380 } elseif (preg_match('@^UPDATE[[:space:]]+@i', $sql_query)) {
381 $is_affected = true;
382 } elseif (preg_match('@^[[:space:]]*SHOW[[:space:]]+@i', $sql_query)) {
383 $is_show = true;
384 } elseif (preg_match('@^(CHECK|ANALYZE|REPAIR|OPTIMIZE)[[:space:]]+TABLE[[:space:]]+@i', $sql_query)) {
385 $is_maint = true;
388 // assign default full_sql_query
389 $full_sql_query = $sql_query;
391 // Handle remembered sorting order, only for single table query
392 if ($GLOBALS['cfg']['RememberSorting']
393 && ! ($is_count || $is_export || $is_func || $is_analyse)
394 && count($analyzed_sql[0]['select_expr']) == 0
395 && isset($analyzed_sql[0]['queryflags']['select_from'])
396 && count($analyzed_sql[0]['table_ref']) == 1
398 $pmatable = new PMA_Table($table, $db);
399 if (empty($analyzed_sql[0]['order_by_clause'])) {
400 $sorted_col = $pmatable->getUiProp(PMA_Table::PROP_SORTED_COLUMN);
401 if ($sorted_col) {
402 // retrieve the remembered sorting order for current table
403 $sql_order_to_append = ' ORDER BY ' . $sorted_col . ' ';
404 $full_sql_query = $analyzed_sql[0]['section_before_limit'] . $sql_order_to_append . $analyzed_sql[0]['section_after_limit'];
406 // update the $analyzed_sql
407 $analyzed_sql[0]['section_before_limit'] .= $sql_order_to_append;
408 $analyzed_sql[0]['order_by_clause'] = $sorted_col;
410 } else {
411 // store the remembered table into session
412 $pmatable->setUiProp(PMA_Table::PROP_SORTED_COLUMN, $analyzed_sql[0]['order_by_clause']);
416 // Do append a "LIMIT" clause?
417 if ((! $cfg['ShowAll'] || $_SESSION['tmp_user_values']['max_rows'] != 'all')
418 && ! ($is_count || $is_export || $is_func || $is_analyse)
419 && isset($analyzed_sql[0]['queryflags']['select_from'])
420 && ! isset($analyzed_sql[0]['queryflags']['offset'])
421 && empty($analyzed_sql[0]['limit_clause'])
423 $sql_limit_to_append = ' LIMIT ' . $_SESSION['tmp_user_values']['pos'] . ', ' . $_SESSION['tmp_user_values']['max_rows'] . " ";
425 $full_sql_query = $analyzed_sql[0]['section_before_limit'] . "\n" . $sql_limit_to_append . $analyzed_sql[0]['section_after_limit'];
427 * @todo pretty printing of this modified query
429 if (isset($display_query)) {
430 // if the analysis of the original query revealed that we found
431 // a section_after_limit, we now have to analyze $display_query
432 // to display it correctly
434 if (!empty($analyzed_sql[0]['section_after_limit']) && trim($analyzed_sql[0]['section_after_limit']) != ';') {
435 $analyzed_display_query = PMA_SQP_analyze(PMA_SQP_parse($display_query));
436 $display_query = $analyzed_display_query[0]['section_before_limit'] . "\n" . $sql_limit_to_append . $analyzed_display_query[0]['section_after_limit'];
442 if (strlen($db)) {
443 PMA_DBI_select_db($db);
446 // E x e c u t e t h e q u e r y
448 // Only if we didn't ask to see the php code (mikebeck)
449 if (isset($GLOBALS['show_as_php']) || !empty($GLOBALS['validatequery'])) {
450 unset($result);
451 $num_rows = 0;
452 } else {
453 if (isset($_SESSION['profiling']) && PMA_profilingSupported()) {
454 PMA_DBI_query('SET PROFILING=1;');
457 // Measure query time.
458 $querytime_before = array_sum(explode(' ', microtime()));
460 $result = @PMA_DBI_try_query($full_sql_query, null, PMA_DBI_QUERY_STORE);
462 // If a stored procedure was called, there may be more results that are
463 // queued up and waiting to be flushed from the buffer. So let's do that.
464 while (true) {
465 if (! PMA_DBI_more_results()) {
466 break;
468 PMA_DBI_next_result();
471 $querytime_after = array_sum(explode(' ', microtime()));
473 $GLOBALS['querytime'] = $querytime_after - $querytime_before;
475 // Displays an error message if required and stop parsing the script
476 if ($error = PMA_DBI_getError()) {
477 if ($is_gotofile) {
478 if (strpos($goto, 'db_') === 0 && strlen($table)) {
479 $table = '';
481 $active_page = $goto;
482 $message = PMA_Message::rawError($error);
484 if ($GLOBALS['is_ajax_request'] == true) {
485 PMA_ajaxResponse($message, false);
489 * Go to target path.
491 require './' . PMA_securePath($goto);
492 } else {
493 $full_err_url = (preg_match('@^(db|tbl)_@', $err_url))
494 ? $err_url . '&amp;show_query=1&amp;sql_query=' . urlencode($sql_query)
495 : $err_url;
496 PMA_mysqlDie($error, $full_sql_query, '', $full_err_url);
498 exit;
500 unset($error);
502 // Gets the number of rows affected/returned
503 // (This must be done immediately after the query because
504 // mysql_affected_rows() reports about the last query done)
506 if (!$is_affected) {
507 $num_rows = ($result) ? @PMA_DBI_num_rows($result) : 0;
508 } elseif (! isset($num_rows)) {
509 $num_rows = @PMA_DBI_affected_rows();
512 // Grabs the profiling results
513 if (isset($_SESSION['profiling']) && PMA_profilingSupported()) {
514 $profiling_results = PMA_DBI_fetch_result('SHOW PROFILE;');
517 // Checks if the current database has changed
518 // This could happen if the user sends a query like "USE `database`;"
520 * commented out auto-switching to active database - really required?
521 * bug #1814718 win: table list disappears (mixed case db names)
522 * https://sourceforge.net/support/tracker.php?aid=1814718
523 * @todo RELEASE test and comit or rollback before release
524 $current_db = PMA_DBI_fetch_value('SELECT DATABASE()');
525 if ($db !== $current_db) {
526 $db = $current_db;
527 $reload = 1;
529 unset($current_db);
532 // tmpfile remove after convert encoding appended by Y.Kawada
533 if (function_exists('PMA_kanji_file_conv')
534 && (isset($textfile) && file_exists($textfile))) {
535 unlink($textfile);
538 // Counts the total number of rows for the same 'SELECT' query without the
539 // 'LIMIT' clause that may have been programatically added
541 if (empty($sql_limit_to_append)) {
542 $unlim_num_rows = $num_rows;
543 // if we did not append a limit, set this to get a correct
544 // "Showing rows..." message
545 //$_SESSION['tmp_user_values']['max_rows'] = 'all';
546 } elseif ($is_select) {
548 // c o u n t q u e r y
550 // If we are "just browsing", there is only one table,
551 // and no WHERE clause (or just 'WHERE 1 '),
552 // we do a quick count (which uses MaxExactCount) because
553 // SQL_CALC_FOUND_ROWS is not quick on large InnoDB tables
555 // However, do not count again if we did it previously
556 // due to $find_real_end == true
558 if (!$is_group
559 && ! isset($analyzed_sql[0]['queryflags']['union'])
560 && ! isset($analyzed_sql[0]['table_ref'][1]['table_name'])
561 && (empty($analyzed_sql[0]['where_clause'])
562 || $analyzed_sql[0]['where_clause'] == '1 ')
563 && ! isset($find_real_end)
566 // "j u s t b r o w s i n g"
567 $unlim_num_rows = PMA_Table::countRecords($db, $table);
569 } else { // n o t " j u s t b r o w s i n g "
571 // add select expression after the SQL_CALC_FOUND_ROWS
573 // for UNION, just adding SQL_CALC_FOUND_ROWS
574 // after the first SELECT works.
576 // take the left part, could be:
577 // SELECT
578 // (SELECT
579 $count_query = PMA_SQP_formatHtml($parsed_sql, 'query_only', 0, $analyzed_sql[0]['position_of_first_select'] + 1);
580 $count_query .= ' SQL_CALC_FOUND_ROWS ';
581 // add everything that was after the first SELECT
582 $count_query .= PMA_SQP_formatHtml($parsed_sql, 'query_only', $analyzed_sql[0]['position_of_first_select']+1);
583 // ensure there is no semicolon at the end of the
584 // count query because we'll probably add
585 // a LIMIT 1 clause after it
586 $count_query = rtrim($count_query);
587 $count_query = rtrim($count_query, ';');
589 // if using SQL_CALC_FOUND_ROWS, add a LIMIT to avoid
590 // long delays. Returned count will be complete anyway.
591 // (but a LIMIT would disrupt results in an UNION)
593 if (! isset($analyzed_sql[0]['queryflags']['union'])) {
594 $count_query .= ' LIMIT 1';
597 // run the count query
599 PMA_DBI_try_query($count_query);
600 // if (mysql_error()) {
601 // void.
602 // I tried the case
603 // (SELECT `User`, `Host`, `Db`, `Select_priv` FROM `db`)
604 // UNION (SELECT `User`, `Host`, "%" AS "Db",
605 // `Select_priv`
606 // FROM `user`) ORDER BY `User`, `Host`, `Db`;
607 // and although the generated count_query is wrong
608 // the SELECT FOUND_ROWS() work! (maybe it gets the
609 // count from the latest query that worked)
611 // another case where the count_query is wrong:
612 // SELECT COUNT(*), f1 from t1 group by f1
613 // and you click to sort on count(*)
614 // }
615 $unlim_num_rows = PMA_DBI_fetch_value('SELECT FOUND_ROWS()');
616 } // end else "just browsing"
618 } else { // not $is_select
619 $unlim_num_rows = 0;
620 } // end rows total count
622 // if a table or database gets dropped, check column comments.
623 if (isset($purge) && $purge == '1') {
625 * Cleanup relations.
627 require_once './libraries/relation_cleanup.lib.php';
629 if (strlen($table) && strlen($db)) {
630 PMA_relationsCleanupTable($db, $table);
631 } elseif (strlen($db)) {
632 PMA_relationsCleanupDatabase($db);
633 } else {
634 // VOID. No DB/Table gets deleted.
635 } // end if relation-stuff
636 } // end if ($purge)
638 // If a column gets dropped, do relation magic.
639 if (isset($dropped_column) && strlen($db) && strlen($table) && !empty($dropped_column)) {
640 require_once './libraries/relation_cleanup.lib.php';
641 PMA_relationsCleanupColumn($db, $table, $dropped_column);
643 } // end if column was dropped
644 } // end else "didn't ask to see php code"
646 // No rows returned -> move back to the calling page
647 if (0 == $num_rows || $is_affected) {
648 if ($is_delete) {
649 $message = PMA_Message::deleted_rows($num_rows);
650 } elseif ($is_insert) {
651 if ($is_replace) {
652 /* For replace we get DELETED + INSERTED row count, so we have to call it affected */
653 $message = PMA_Message::affected_rows($num_rows);
654 } else {
655 $message = PMA_Message::inserted_rows($num_rows);
657 $insert_id = PMA_DBI_insert_id();
658 if ($insert_id != 0) {
659 // insert_id is id of FIRST record inserted in one insert, so if we inserted multiple rows, we had to increment this
660 $message->addMessage('[br]');
661 // need to use a temporary because the Message class
662 // currently supports adding parameters only to the first
663 // message
664 $_inserted = PMA_Message::notice(__('Inserted row id: %1$d'));
665 $_inserted->addParam($insert_id + $num_rows - 1);
666 $message->addMessage($_inserted);
668 } elseif ($is_affected) {
669 $message = PMA_Message::affected_rows($num_rows);
671 // Ok, here is an explanation for the !$is_select.
672 // The form generated by sql_query_form.lib.php
673 // and db_sql.php has many submit buttons
674 // on the same form, and some confusion arises from the
675 // fact that $message_to_show is sent for every case.
676 // The $message_to_show containing a success message and sent with
677 // the form should not have priority over errors
678 } elseif (!empty($message_to_show) && !$is_select) {
679 $message = PMA_Message::rawSuccess(htmlspecialchars($message_to_show));
680 } elseif (!empty($GLOBALS['show_as_php'])) {
681 $message = PMA_Message::success(__('Showing as PHP code'));
682 } elseif (isset($GLOBALS['show_as_php'])) {
683 /* User disable showing as PHP, query is only displayed */
684 $message = PMA_Message::notice(__('Showing SQL query'));
685 } elseif (!empty($GLOBALS['validatequery'])) {
686 $message = PMA_Message::notice(__('Validated SQL'));
687 } else {
688 $message = PMA_Message::success(__('MySQL returned an empty result set (i.e. zero rows).'));
691 if (isset($GLOBALS['querytime'])) {
692 $_querytime = PMA_Message::notice(__('Query took %01.4f sec'));
693 $_querytime->addParam($GLOBALS['querytime']);
694 $message->addMessage('(');
695 $message->addMessage($_querytime);
696 $message->addMessage(')');
699 if ($GLOBALS['is_ajax_request'] == true) {
702 * If we are in grid editing, we need to process the relational and
703 * transformed fields, if they were edited. After that, output the correct
704 * link/transformed value and exit
706 * Logic taken from libraries/display_tbl.lib.php
709 if (isset($_REQUEST['rel_fields_list']) && $_REQUEST['rel_fields_list'] != '') {
710 //handle relations work here for updated row.
711 require_once './libraries/relation.lib.php';
713 $map = PMA_getForeigners($db, $table, '', 'both');
715 $rel_fields = array();
716 parse_str($_REQUEST['rel_fields_list'], $rel_fields);
718 foreach ( $rel_fields as $rel_field => $rel_field_value) {
720 $where_comparison = "='" . $rel_field_value . "'";
721 $display_field = PMA_getDisplayField($map[$rel_field]['foreign_db'], $map[$rel_field]['foreign_table']);
723 // Field to display from the foreign table?
724 if (isset($display_field) && strlen($display_field)) {
725 $dispsql = 'SELECT ' . PMA_backquote($display_field)
726 . ' FROM ' . PMA_backquote($map[$rel_field]['foreign_db'])
727 . '.' . PMA_backquote($map[$rel_field]['foreign_table'])
728 . ' WHERE ' . PMA_backquote($map[$rel_field]['foreign_field'])
729 . $where_comparison;
730 $dispresult = PMA_DBI_try_query($dispsql, null, PMA_DBI_QUERY_STORE);
731 if ($dispresult && PMA_DBI_num_rows($dispresult) > 0) {
732 list($dispval) = PMA_DBI_fetch_row($dispresult, 0);
733 } else {
734 //$dispval = __('Link not found');
736 @PMA_DBI_free_result($dispresult);
737 } else {
738 $dispval = '';
739 } // end if... else...
741 if ('K' == $_SESSION['tmp_user_values']['relational_display']) {
742 // user chose "relational key" in the display options, so
743 // the title contains the display field
744 $title = (! empty($dispval))? ' title="' . htmlspecialchars($dispval) . '"' : '';
745 } else {
746 $title = ' title="' . htmlspecialchars($rel_field_value) . '"';
749 $_url_params = array(
750 'db' => $map[$rel_field]['foreign_db'],
751 'table' => $map[$rel_field]['foreign_table'],
752 'pos' => '0',
753 'sql_query' => 'SELECT * FROM '
754 . PMA_backquote($map[$rel_field]['foreign_db']) . '.' . PMA_backquote($map[$rel_field]['foreign_table'])
755 . ' WHERE ' . PMA_backquote($map[$rel_field]['foreign_field'])
756 . $where_comparison
758 $output = '<a href="sql.php' . PMA_generate_common_url($_url_params) . '"' . $title . '>';
760 if ('D' == $_SESSION['tmp_user_values']['relational_display']) {
761 // user chose "relational display field" in the
762 // display options, so show display field in the cell
763 $output .= (!empty($dispval)) ? htmlspecialchars($dispval) : '';
764 } else {
765 // otherwise display data in the cell
766 $output .= htmlspecialchars($rel_field_value);
768 $output .= '</a>';
769 $extra_data['relations'][$rel_field] = $output;
773 if (isset($_REQUEST['do_transformations']) && $_REQUEST['do_transformations'] == true ) {
774 require_once './libraries/transformations.lib.php';
775 //if some posted fields need to be transformed, generate them here.
776 $mime_map = PMA_getMIME($db, $table);
778 if ($mime_map === false) {
779 $mime_map = array();
782 $edited_values = array();
783 parse_str($_REQUEST['transform_fields_list'], $edited_values);
785 foreach($mime_map as $transformation) {
786 $include_file = PMA_securePath($transformation['transformation']);
787 $column_name = $transformation['column_name'];
788 $column_data = $edited_values[$column_name];
790 $_url_params = array(
791 'db' => $db,
792 'table' => $table,
793 'where_clause' => $_REQUEST['where_clause'],
794 'transform_key' => $column_name,
797 if (file_exists('./libraries/transformations/' . $include_file)) {
798 $transformfunction_name = str_replace('.inc.php', '', $transformation['transformation']);
800 require_once './libraries/transformations/' . $include_file;
802 if (function_exists('PMA_transformation_' . $transformfunction_name)) {
803 $transform_function = 'PMA_transformation_' . $transformfunction_name;
804 $transform_options = PMA_transformation_getOptions((isset($transformation['transformation_options']) ? $transformation['transformation_options'] : ''));
805 $transform_options['wrapper_link'] = PMA_generate_common_url($_url_params);
809 $extra_data['transformations'][$column_name] = $transform_function($column_data, $transform_options);
813 if ($cfg['ShowSQL']) {
814 $extra_data['sql_query'] = PMA_showMessage($message, $GLOBALS['sql_query'], 'success');
816 if (isset($GLOBALS['reload']) && $GLOBALS['reload'] == 1) {
817 $extra_data['reload'] = 1;
818 $extra_data['db'] = $GLOBALS['db'];
820 PMA_ajaxResponse($message, $message->isSuccess(), (isset($extra_data) ? $extra_data : ''));
823 if ($is_gotofile) {
824 $goto = PMA_securePath($goto);
825 // Checks for a valid target script
826 $is_db = $is_table = false;
827 if (isset($_REQUEST['purge']) && $_REQUEST['purge'] == '1') {
828 $table = '';
829 unset($url_params['table']);
831 include 'libraries/db_table_exists.lib.php';
833 if (strpos($goto, 'tbl_') === 0 && ! $is_table) {
834 if (strlen($table)) {
835 $table = '';
837 $goto = 'db_sql.php';
839 if (strpos($goto, 'db_') === 0 && ! $is_db) {
840 if (strlen($db)) {
841 $db = '';
843 $goto = 'main.php';
845 // Loads to target script
846 if ($goto != 'main.php') {
847 require_once './libraries/header.inc.php';
849 $active_page = $goto;
850 require './' . $goto;
851 } else {
852 // avoid a redirect loop when last record was deleted
853 if (0 == $num_rows && 'sql.php' == $cfg['DefaultTabTable']) {
854 $goto = str_replace('sql.php','tbl_structure.php',$goto);
856 PMA_sendHeaderLocation($cfg['PmaAbsoluteUri'] . str_replace('&amp;', '&', $goto) . '&message=' . urlencode($message));
857 } // end else
858 exit();
859 } // end no rows returned
861 // At least one row is returned -> displays a table with results
862 else {
863 //If we are retrieving the full value of a truncated field or the original
864 // value of a transformed field, show it here and exit
865 if ($GLOBALS['grid_edit'] == true && $GLOBALS['cfg']['AjaxEnable']) {
866 $row = PMA_DBI_fetch_row($result);
867 $extra_data = array();
868 $extra_data['value'] = $row[0];
869 PMA_ajaxResponse(NULL, true, $extra_data);
872 // Displays the headers
873 if (isset($show_query)) {
874 unset($show_query);
876 if (isset($printview) && $printview == '1') {
877 require_once './libraries/header_printview.inc.php';
878 } else {
880 $GLOBALS['js_include'][] = 'functions.js';
881 $GLOBALS['js_include'][] = 'makegrid.js';
882 $GLOBALS['js_include'][] = 'sql.js';
884 unset($message);
886 if (! $GLOBALS['is_ajax_request'] || ! $GLOBALS['cfg']['AjaxEnable']) {
887 if (strlen($table)) {
888 require './libraries/tbl_common.php';
889 $url_query .= '&amp;goto=tbl_sql.php&amp;back=tbl_sql.php';
890 require './libraries/tbl_info.inc.php';
891 require './libraries/tbl_links.inc.php';
892 } elseif (strlen($db)) {
893 require './libraries/db_common.inc.php';
894 require './libraries/db_info.inc.php';
895 } else {
896 require './libraries/server_common.inc.php';
897 require './libraries/server_links.inc.php';
900 else {
901 require_once './libraries/header.inc.php';
902 //we don't need to buffer the output in PMA_showMessage here.
903 //set a global variable and check against it in the function
904 $GLOBALS['buffer_message'] = false;
908 if (strlen($db)) {
909 $cfgRelation = PMA_getRelationsParam();
912 // Gets the list of fields properties
913 if (isset($result) && $result) {
914 $fields_meta = PMA_DBI_get_fields_meta($result);
915 $fields_cnt = count($fields_meta);
918 if (! $GLOBALS['is_ajax_request']) {
919 //begin the sqlqueryresults div here. container div
920 echo '<div id="sqlqueryresults"';
921 if ($GLOBALS['cfg']['AjaxEnable']) {
922 echo ' class="ajax"';
924 echo '>';
927 // Display previous update query (from tbl_replace)
928 if (isset($disp_query) && $cfg['ShowSQL'] == true) {
929 PMA_showMessage($disp_message, $disp_query, 'success');
932 if (isset($profiling_results)) {
933 // pma_token/url_query needed for chart export
935 <script type="text/javascript">
936 pma_token = '<?php echo $_SESSION[' PMA_token ']; ?>';
937 url_query = '<?php echo isset($url_query)?$url_query:PMA_generate_common_url($db);?>';
938 $(document).ready(makeProfilingChart);
939 </script>
940 <?php
941 echo '<fieldset><legend>' . __('Profiling') . '</legend>' . "\n";
942 echo '<div style="float: left;">';
943 echo '<table>' . "\n";
944 echo ' <tr>' . "\n";
945 echo ' <th>' . __('Status') . PMA_showMySQLDocu('general-thread-states','general-thread-states') . '</th>' . "\n";
946 echo ' <th>' . __('Time') . '</th>' . "\n";
947 echo ' </tr>' . "\n";
949 $chart_json = Array();
950 foreach ($profiling_results as $one_result) {
951 echo ' <tr>' . "\n";
952 echo '<td>' . ucwords($one_result['Status']) . '</td>' . "\n";
953 echo '<td align="right">' . (PMA_formatNumber($one_result['Duration'],3,1)) . 's</td>' . "\n";
954 $chart_json[ucwords($one_result['Status'])] = $one_result['Duration'];
957 echo '</table>' . "\n";
958 echo '</div>';
959 //require_once './libraries/chart.lib.php';
960 echo '<div id="profilingchart" style="display:none;">';
961 //PMA_chart_profiling($profiling_results);
962 echo json_encode($chart_json);
963 echo '</div>';
964 echo '</fieldset>' . "\n";
967 // Displays the results in a table
968 if (empty($disp_mode)) {
969 // see the "PMA_setDisplayMode()" function in
970 // libraries/display_tbl.lib.php
971 $disp_mode = 'urdr111101';
974 // hide edit and delete links for information_schema
975 if ($db == 'information_schema') {
976 $disp_mode = 'nnnn110111';
979 if (isset($label)) {
980 $message = PMA_message::success(__('Bookmark %s created'));
981 $message->addParam($label);
982 $message->display();
985 PMA_displayTable($result, $disp_mode, $analyzed_sql);
986 PMA_DBI_free_result($result);
988 // BEGIN INDEX CHECK See if indexes should be checked.
989 if (isset($query_type) && $query_type == 'check_tbl' && isset($selected) && is_array($selected)) {
990 foreach ($selected as $idx => $tbl_name) {
991 $check = PMA_Index::findDuplicates($tbl_name, $db);
992 if (! empty($check)) {
993 printf(__('Problems with indexes of table `%s`'), $tbl_name);
994 echo $check;
997 } // End INDEX CHECK
999 // Bookmark support if required
1000 if ($disp_mode[7] == '1'
1001 && (! empty($cfg['Bookmark']) && empty($id_bookmark))
1002 && !empty($sql_query)) {
1003 echo "\n";
1005 $goto = 'sql.php?'
1006 . PMA_generate_common_url($db, $table)
1007 . '&amp;sql_query=' . urlencode($sql_query)
1008 . '&amp;id_bookmark=1';
1011 <form action="sql.php" method="post" onsubmit="return emptyFormElements(this, 'fields[label]');">
1012 <?php echo PMA_generate_common_hidden_inputs(); ?>
1013 <input type="hidden" name="goto" value="<?php echo $goto; ?>" />
1014 <input type="hidden" name="fields[dbase]" value="<?php echo htmlspecialchars($db); ?>" />
1015 <input type="hidden" name="fields[user]" value="<?php echo $cfg['Bookmark']['user']; ?>" />
1016 <input type="hidden" name="fields[query]" value="<?php echo urlencode(isset($complete_query) ? $complete_query : $sql_query); ?>" />
1017 <fieldset>
1018 <legend><?php
1019 echo PMA_getIcon('b_bookmark.png', __('Bookmark this SQL query'));
1021 </legend>
1023 <div class="formelement">
1024 <label for="fields_label_"><?php echo __('Label'); ?>:</label>
1025 <input type="text" id="fields_label_" name="fields[label]" value="" />
1026 </div>
1028 <div class="formelement">
1029 <input type="checkbox" name="bkm_all_users" id="bkm_all_users" value="true" />
1030 <label for="bkm_all_users"><?php echo __('Let every user access this bookmark'); ?></label>
1031 </div>
1033 <div class="clearfloat"></div>
1034 </fieldset>
1035 <fieldset class="tblFooters">
1036 <input type="submit" name="store_bkm" value="<?php echo __('Bookmark this SQL query'); ?>" />
1037 </fieldset>
1038 </form>
1039 <?php
1040 } // end bookmark support
1042 // Do print the page if required
1043 if (isset($printview) && $printview == '1') {
1045 <script type="text/javascript">
1046 //<![CDATA[
1047 // Do print the page
1048 window.onload = function()
1050 if (typeof(window.print) != 'undefined') {
1051 window.print();
1054 //]]>
1055 </script>
1056 <?php
1057 } // end print case
1059 if ($GLOBALS['is_ajax_request'] != true) {
1060 echo '</div>'; // end sqlqueryresults div
1062 } // end rows returned
1065 * Displays the footer
1067 if (! isset($_REQUEST['table_maintenance'])) {
1068 require './libraries/footer.inc.php';