[Drizzle] Don't show "Create view" button for query results
[phpmyadmin.git] / sql.php
blob688b44aa435bb5aae68dc8085e5bd642ca1c2b07
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';
19 if(isset($_SESSION['profiling'])) {
20 $GLOBALS['js_include'][] = 'highcharts/highcharts.js';
21 /* Files required for chart exporting */
22 $GLOBALS['js_include'][] = 'highcharts/exporting.js';
23 $GLOBALS['js_include'][] = 'canvg/canvg.js';
24 $GLOBALS['js_include'][] = 'canvg/rgbcolor.js';
27 /**
28 * Defines the url to return to in case of error in a sql statement
30 // Security checkings
31 if (! empty($goto)) {
32 $is_gotofile = preg_replace('@^([^?]+).*$@s', '\\1', $goto);
33 if (! @file_exists('./' . $is_gotofile)) {
34 unset($goto);
35 } else {
36 $is_gotofile = ($is_gotofile == $goto);
38 } else {
39 $goto = (! strlen($table)) ? $cfg['DefaultTabDatabase'] : $cfg['DefaultTabTable'];
40 $is_gotofile = true;
41 } // end if
43 if (! isset($err_url)) {
44 $err_url = (!empty($back) ? $back : $goto)
45 . '?' . PMA_generate_common_url($db)
46 . ((strpos(' ' . $goto, 'db_') != 1 && strlen($table)) ? '&amp;table=' . urlencode($table) : '');
47 } // end if
49 // Coming from a bookmark dialog
50 if (isset($fields['query'])) {
51 $sql_query = $fields['query'];
54 // This one is just to fill $db
55 if (isset($fields['dbase'])) {
56 $db = $fields['dbase'];
59 /**
60 * During inline edit, if we have a relational field, show the dropdown for it
62 * Logic taken from libraries/display_tbl_lib.php
64 * This doesn't seem to be the right place to do this, but I can't think of any
65 * better place either.
67 if (isset($_REQUEST['get_relational_values']) && $_REQUEST['get_relational_values'] == true) {
68 require_once 'libraries/relation.lib.php';
70 $column = $_REQUEST['column'];
71 $foreigners = PMA_getForeigners($db, $table, $column);
73 $display_field = PMA_getDisplayField($foreigners[$column]['foreign_db'], $foreigners[$column]['foreign_table']);
75 $foreignData = PMA_getForeignData($foreigners, $column, false, '', '');
77 if ($_SESSION['tmp_user_values']['relational_display'] == 'D'
78 && (isset($display_field) && strlen($display_field)
79 && (isset($_REQUEST['relation_key_or_display_column']) && $_REQUEST['relation_key_or_display_column']))) {
80 $curr_value = $_REQUEST['relation_key_or_display_column'];
81 } else {
82 $curr_value = $_REQUEST['curr_value'];
84 if ($foreignData['disp_row'] == null) {
85 //Handle the case when number of values is more than $cfg['ForeignKeyMaxLimit']
86 $_url_params = array(
87 'db' => $db,
88 'table' => $table,
89 'field' => $column
92 $dropdown = '<span class="curr_value">' . htmlspecialchars($_REQUEST['curr_value']) . '</span> <a href="browse_foreigners.php' . PMA_generate_common_url($_url_params) . '"'
93 . ' target="_blank" class="browse_foreign" '
94 .'>' . __('Browse foreign values') . '</a>';
96 else {
97 $dropdown = PMA_foreignDropdown($foreignData['disp_row'], $foreignData['foreign_field'], $foreignData['foreign_display'], $curr_value, $cfg['ForeignKeyMaxLimit']);
98 $dropdown = '<select>' . $dropdown . '</select>';
101 $extra_data['dropdown'] = $dropdown;
102 PMA_ajaxResponse(NULL, true, $extra_data);
106 * Just like above, find possible values for enum fields during inline edit.
108 * Logic taken from libraries/display_tbl_lib.php
110 if(isset($_REQUEST['get_enum_values']) && $_REQUEST['get_enum_values'] == true) {
111 $field_info_query = PMA_DBI_get_columns_sql($db, $table, $_REQUEST['column']);
113 $field_info_result = PMA_DBI_fetch_result($field_info_query, null, null, null, PMA_DBI_QUERY_STORE);
115 $search = array('enum', '(', ')', "'");
117 $values = explode(',', str_replace($search, '', $field_info_result[0]['Type']));
119 $dropdown = '<option value="">&nbsp;</option>';
120 foreach($values as $value) {
121 $dropdown .= '<option value="' . htmlspecialchars($value) . '"';
122 if($value == $_REQUEST['curr_value']) {
123 $dropdown .= ' selected="selected"';
125 $dropdown .= '>' . $value . '</option>';
128 $dropdown = '<select>' . $dropdown . '</select>';
130 $extra_data['dropdown'] = $dropdown;
131 PMA_ajaxResponse(NULL, true, $extra_data);
135 * Find possible values for set fields during inline edit.
137 if(isset($_REQUEST['get_set_values']) && $_REQUEST['get_set_values'] == true) {
138 $field_info_query = PMA_DBI_get_columns_sql($db, $table, $_REQUEST['column']);
140 $field_info_result = PMA_DBI_fetch_result($field_info_query, null, null, null, PMA_DBI_QUERY_STORE);
142 $selected_values = explode(',', $_REQUEST['curr_value']);
144 $search = array('set', '(', ')', "'");
145 $values = explode(',', str_replace($search, '', $field_info_result[0]['Type']));
147 $select = '';
148 foreach($values as $value) {
149 $select .= '<option value="' . htmlspecialchars($value) . '"';
150 if(in_array($value, $selected_values, true)) {
151 $select .= ' selected="selected"';
153 $select .= '>' . $value . '</option>';
156 $select_size = (sizeof($values) > 10) ? 10 : sizeof($values);
157 $select = '<select multiple="multiple" size="' . $select_size . '">' . $select . '</select>';
159 $extra_data['select'] = $select;
160 PMA_ajaxResponse(NULL, true, $extra_data);
164 * Check ajax request to set the column order
166 if(isset($_REQUEST['set_col_order']) && $_REQUEST['set_col_order'] == true) {
167 $pmatable = new PMA_Table($table, $db);
168 $col_order = explode(',', $_REQUEST['col_order']);
169 $retval = $pmatable->setUiProp(PMA_Table::PROP_COLUMN_ORDER, $col_order, $_REQUEST['table_create_time']);
170 PMA_ajaxResponse(NULL, ($retval == true));
173 // Default to browse if no query set and we have table
174 // (needed for browsing from DefaultTabTable)
175 if (empty($sql_query) && strlen($table) && strlen($db)) {
176 require_once './libraries/bookmark.lib.php';
177 $book_sql_query = PMA_Bookmark_get($db, '\'' . PMA_sqlAddslashes($table) . '\'',
178 'label', false, true);
180 if (! empty($book_sql_query)) {
181 $GLOBALS['using_bookmark_message'] = PMA_message::notice(__('Using bookmark "%s" as default browse query.'));
182 $GLOBALS['using_bookmark_message']->addParam($table);
183 $GLOBALS['using_bookmark_message']->addMessage(PMA_showDocu('faq6_22'));
184 $sql_query = $book_sql_query;
185 } else {
186 $sql_query = 'SELECT * FROM ' . PMA_backquote($table);
188 unset($book_sql_query);
190 // set $goto to what will be displayed if query returns 0 rows
191 $goto = 'tbl_structure.php';
192 } else {
193 // Now we can check the parameters
194 PMA_checkParameters(array('sql_query'));
197 // instead of doing the test twice
198 $is_drop_database = preg_match('/DROP[[:space:]]+(DATABASE|SCHEMA)[[:space:]]+/i',
199 $sql_query);
202 * Check rights in case of DROP DATABASE
204 * This test may be bypassed if $is_js_confirmed = 1 (already checked with js)
205 * but since a malicious user may pass this variable by url/form, we don't take
206 * into account this case.
208 if (!defined('PMA_CHK_DROP')
209 && !$cfg['AllowUserDropDatabase']
210 && $is_drop_database
211 && !$is_superuser) {
212 require_once './libraries/header.inc.php';
213 PMA_mysqlDie(__('"DROP DATABASE" statements are disabled.'), '', '', $err_url);
214 } // end if
216 require_once './libraries/display_tbl.lib.php';
217 PMA_displayTable_checkConfigParams();
220 * Need to find the real end of rows?
222 if (isset($find_real_end) && $find_real_end) {
223 $unlim_num_rows = PMA_Table::countRecords($db, $table, $force_exact = true);
224 $_SESSION['tmp_user_values']['pos'] = @((ceil($unlim_num_rows / $_SESSION['tmp_user_values']['max_rows']) - 1) * $_SESSION['tmp_user_values']['max_rows']);
229 * Bookmark add
231 if (isset($store_bkm)) {
232 PMA_Bookmark_save($fields, (isset($bkm_all_users) && $bkm_all_users == 'true' ? true : false));
233 // go back to sql.php to redisplay query; do not use &amp; in this case:
234 PMA_sendHeaderLocation($cfg['PmaAbsoluteUri'] . $goto . '&label=' . $fields['label']);
235 } // end if
238 * Parse and analyze the query
240 require_once './libraries/parse_analyze.lib.php';
243 * Sets or modifies the $goto variable if required
245 if ($goto == 'sql.php') {
246 $is_gotofile = false;
247 $goto = 'sql.php?'
248 . PMA_generate_common_url($db, $table)
249 . '&amp;sql_query=' . urlencode($sql_query);
250 } // end if
254 * Go back to further page if table should not be dropped
256 if (isset($btnDrop) && $btnDrop == __('No')) {
257 if (!empty($back)) {
258 $goto = $back;
260 if ($is_gotofile) {
261 if (strpos($goto, 'db_') === 0 && strlen($table)) {
262 $table = '';
264 $active_page = $goto;
265 require './' . PMA_securePath($goto);
266 } else {
267 PMA_sendHeaderLocation($cfg['PmaAbsoluteUri'] . str_replace('&amp;', '&', $goto));
269 exit();
270 } // end if
274 * Displays the confirm page if required
276 * This part of the script is bypassed if $is_js_confirmed = 1 (already checked
277 * with js) because possible security issue is not so important here: at most,
278 * the confirm message isn't displayed.
280 * Also bypassed if only showing php code.or validating a SQL query
282 if (! $cfg['Confirm'] || isset($_REQUEST['is_js_confirmed']) || isset($btnDrop)
283 // if we are coming from a "Create PHP code" or a "Without PHP Code"
284 // dialog, we won't execute the query anyway, so don't confirm
285 || isset($GLOBALS['show_as_php'])
286 || !empty($GLOBALS['validatequery'])) {
287 $do_confirm = false;
288 } else {
289 $do_confirm = isset($analyzed_sql[0]['queryflags']['need_confirm']);
292 if ($do_confirm) {
293 $stripped_sql_query = $sql_query;
294 require_once './libraries/header.inc.php';
295 if ($is_drop_database) {
296 echo '<h1 class="error">' . __('You are about to DESTROY a complete database!') . '</h1>';
298 echo '<form action="sql.php" method="post">' . "\n"
299 .PMA_generate_common_hidden_inputs($db, $table);
301 <input type="hidden" name="sql_query" value="<?php echo htmlspecialchars($sql_query); ?>" />
302 <input type="hidden" name="message_to_show" value="<?php echo isset($message_to_show) ? PMA_sanitize($message_to_show, true) : ''; ?>" />
303 <input type="hidden" name="goto" value="<?php echo $goto; ?>" />
304 <input type="hidden" name="back" value="<?php echo isset($back) ? PMA_sanitize($back, true) : ''; ?>" />
305 <input type="hidden" name="reload" value="<?php echo isset($reload) ? PMA_sanitize($reload, true) : 0; ?>" />
306 <input type="hidden" name="purge" value="<?php echo isset($purge) ? PMA_sanitize($purge, true) : ''; ?>" />
307 <input type="hidden" name="dropped_column" value="<?php echo isset($dropped_column) ? PMA_sanitize($dropped_column, true) : ''; ?>" />
308 <input type="hidden" name="show_query" value="<?php echo isset($show_query) ? PMA_sanitize($show_query, true) : ''; ?>" />
309 <?php
310 echo '<fieldset class="confirmation">' . "\n"
311 .' <legend>' . __('Do you really want to ') . '</legend>'
312 .' <tt>' . htmlspecialchars($stripped_sql_query) . '</tt>' . "\n"
313 .'</fieldset>' . "\n"
314 .'<fieldset class="tblFooters">' . "\n";
316 <input type="submit" name="btnDrop" value="<?php echo __('Yes'); ?>" id="buttonYes" />
317 <input type="submit" name="btnDrop" value="<?php echo __('No'); ?>" id="buttonNo" />
318 <?php
319 echo '</fieldset>' . "\n"
320 . '</form>' . "\n";
323 * Displays the footer and exit
325 require './libraries/footer.inc.php';
326 } // end if $do_confirm
329 // Defines some variables
330 // A table has to be created, renamed, dropped -> navi frame should be reloaded
332 * @todo use the parser/analyzer
335 if (empty($reload)
336 && preg_match('/^(CREATE|ALTER|DROP)\s+(VIEW|TABLE|DATABASE|SCHEMA)\s+/i', $sql_query)) {
337 $reload = 1;
340 // SK -- Patch: $is_group added for use in calculation of total number of
341 // rows.
342 // $is_count is changed for more correct "LIMIT" clause
343 // appending in queries like
344 // "SELECT COUNT(...) FROM ... GROUP BY ..."
347 * @todo detect all this with the parser, to avoid problems finding
348 * those strings in comments or backquoted identifiers
351 $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;
352 if ($is_select) { // see line 141
353 $is_group = preg_match('@(GROUP[[:space:]]+BY|HAVING|SELECT[[:space:]]+DISTINCT)[[:space:]]+@i', $sql_query);
354 $is_func = !$is_group && (preg_match('@[[:space:]]+(SUM|AVG|STD|STDDEV|MIN|MAX|BIT_OR|BIT_AND)\s*\(@i', $sql_query));
355 $is_count = !$is_group && (preg_match('@^SELECT[[:space:]]+COUNT\((.*\.+)?.*\)@i', $sql_query));
356 $is_export = (preg_match('@[[:space:]]+INTO[[:space:]]+OUTFILE[[:space:]]+@i', $sql_query));
357 $is_analyse = (preg_match('@[[:space:]]+PROCEDURE[[:space:]]+ANALYSE@i', $sql_query));
358 } elseif (preg_match('@^EXPLAIN[[:space:]]+@i', $sql_query)) {
359 $is_explain = true;
360 } elseif (preg_match('@^DELETE[[:space:]]+@i', $sql_query)) {
361 $is_delete = true;
362 $is_affected = true;
363 } elseif (preg_match('@^(INSERT|LOAD[[:space:]]+DATA|REPLACE)[[:space:]]+@i', $sql_query)) {
364 $is_insert = true;
365 $is_affected = true;
366 if (preg_match('@^(REPLACE)[[:space:]]+@i', $sql_query)) {
367 $is_replace = true;
369 } elseif (preg_match('@^UPDATE[[:space:]]+@i', $sql_query)) {
370 $is_affected = true;
371 } elseif (preg_match('@^[[:space:]]*SHOW[[:space:]]+@i', $sql_query)) {
372 $is_show = true;
373 } elseif (preg_match('@^(CHECK|ANALYZE|REPAIR|OPTIMIZE)[[:space:]]+TABLE[[:space:]]+@i', $sql_query)) {
374 $is_maint = true;
377 // assign default full_sql_query
378 $full_sql_query = $sql_query;
380 // Handle remembered sorting order, only for single table query
381 if ($GLOBALS['cfg']['RememberSorting']
382 && ! ($is_count || $is_export || $is_func || $is_analyse)
383 && count($analyzed_sql[0]['select_expr']) == 0
384 && isset($analyzed_sql[0]['queryflags']['select_from'])
385 && count($analyzed_sql[0]['table_ref']) == 1
387 $pmatable = new PMA_Table($table, $db);
388 if (empty($analyzed_sql[0]['order_by_clause'])) {
389 $sorted_col = $pmatable->getUiProp(PMA_Table::PROP_SORTED_COLUMN);
390 if ($sorted_col) {
391 // retrieve the remembered sorting order for current table
392 $sql_order_to_append = ' ORDER BY ' . $sorted_col . ' ';
393 $full_sql_query = $analyzed_sql[0]['section_before_limit'] . $sql_order_to_append . $analyzed_sql[0]['section_after_limit'];
395 // update the $analyzed_sql
396 $analyzed_sql[0]['section_before_limit'] .= $sql_order_to_append;
397 $analyzed_sql[0]['order_by_clause'] = $sorted_col;
399 } else {
400 // store the remembered table into session
401 $pmatable->setUiProp(PMA_Table::PROP_SORTED_COLUMN, $analyzed_sql[0]['order_by_clause']);
405 // Do append a "LIMIT" clause?
406 if ((! $cfg['ShowAll'] || $_SESSION['tmp_user_values']['max_rows'] != 'all')
407 && ! ($is_count || $is_export || $is_func || $is_analyse)
408 && isset($analyzed_sql[0]['queryflags']['select_from'])
409 && ! isset($analyzed_sql[0]['queryflags']['offset'])
410 && empty($analyzed_sql[0]['limit_clause'])
412 $sql_limit_to_append = ' LIMIT ' . $_SESSION['tmp_user_values']['pos'] . ', ' . $_SESSION['tmp_user_values']['max_rows'] . " ";
414 $full_sql_query = $analyzed_sql[0]['section_before_limit'] . "\n" . $sql_limit_to_append . $analyzed_sql[0]['section_after_limit'];
416 * @todo pretty printing of this modified query
418 if (isset($display_query)) {
419 // if the analysis of the original query revealed that we found
420 // a section_after_limit, we now have to analyze $display_query
421 // to display it correctly
423 if (!empty($analyzed_sql[0]['section_after_limit']) && trim($analyzed_sql[0]['section_after_limit']) != ';') {
424 $analyzed_display_query = PMA_SQP_analyze(PMA_SQP_parse($display_query));
425 $display_query = $analyzed_display_query[0]['section_before_limit'] . "\n" . $sql_limit_to_append . $analyzed_display_query[0]['section_after_limit'];
431 if (strlen($db)) {
432 PMA_DBI_select_db($db);
435 // E x e c u t e t h e q u e r y
437 // Only if we didn't ask to see the php code (mikebeck)
438 if (isset($GLOBALS['show_as_php']) || !empty($GLOBALS['validatequery'])) {
439 unset($result);
440 $num_rows = 0;
441 } else {
442 if (isset($_SESSION['profiling']) && PMA_profilingSupported()) {
443 PMA_DBI_query('SET PROFILING=1;');
446 // Measure query time.
447 $querytime_before = array_sum(explode(' ', microtime()));
449 $result = @PMA_DBI_try_query($full_sql_query, null, PMA_DBI_QUERY_STORE);
451 $querytime_after = array_sum(explode(' ', microtime()));
453 $GLOBALS['querytime'] = $querytime_after - $querytime_before;
455 // Displays an error message if required and stop parsing the script
456 if ($error = PMA_DBI_getError()) {
457 if ($is_gotofile) {
458 if (strpos($goto, 'db_') === 0 && strlen($table)) {
459 $table = '';
461 $active_page = $goto;
462 $message = PMA_Message::rawError($error);
464 if( $GLOBALS['is_ajax_request'] == true) {
465 PMA_ajaxResponse($message, false);
469 * Go to target path.
471 require './' . PMA_securePath($goto);
472 } else {
473 $full_err_url = (preg_match('@^(db|tbl)_@', $err_url))
474 ? $err_url . '&amp;show_query=1&amp;sql_query=' . urlencode($sql_query)
475 : $err_url;
476 PMA_mysqlDie($error, $full_sql_query, '', $full_err_url);
478 exit;
480 unset($error);
482 // Gets the number of rows affected/returned
483 // (This must be done immediately after the query because
484 // mysql_affected_rows() reports about the last query done)
486 if (!$is_affected) {
487 $num_rows = ($result) ? @PMA_DBI_num_rows($result) : 0;
488 } elseif (! isset($num_rows)) {
489 $num_rows = @PMA_DBI_affected_rows();
492 // Grabs the profiling results
493 if (isset($_SESSION['profiling']) && PMA_profilingSupported()) {
494 $profiling_results = PMA_DBI_fetch_result('SHOW PROFILE;');
497 // Checks if the current database has changed
498 // This could happen if the user sends a query like "USE `database`;"
500 * commented out auto-switching to active database - really required?
501 * bug #1814718 win: table list disappears (mixed case db names)
502 * https://sourceforge.net/support/tracker.php?aid=1814718
503 * @todo RELEASE test and comit or rollback before release
504 $current_db = PMA_DBI_fetch_value('SELECT DATABASE()');
505 if ($db !== $current_db) {
506 $db = $current_db;
507 $reload = 1;
509 unset($current_db);
512 // tmpfile remove after convert encoding appended by Y.Kawada
513 if (function_exists('PMA_kanji_file_conv')
514 && (isset($textfile) && file_exists($textfile))) {
515 unlink($textfile);
518 // Counts the total number of rows for the same 'SELECT' query without the
519 // 'LIMIT' clause that may have been programatically added
521 if (empty($sql_limit_to_append)) {
522 $unlim_num_rows = $num_rows;
523 // if we did not append a limit, set this to get a correct
524 // "Showing rows..." message
525 //$_SESSION['tmp_user_values']['max_rows'] = 'all';
526 } elseif ($is_select) {
528 // c o u n t q u e r y
530 // If we are "just browsing", there is only one table,
531 // and no WHERE clause (or just 'WHERE 1 '),
532 // we do a quick count (which uses MaxExactCount) because
533 // SQL_CALC_FOUND_ROWS is not quick on large InnoDB tables
535 // However, do not count again if we did it previously
536 // due to $find_real_end == true
538 if (!$is_group
539 && ! isset($analyzed_sql[0]['queryflags']['union'])
540 && ! isset($analyzed_sql[0]['table_ref'][1]['table_name'])
541 && (empty($analyzed_sql[0]['where_clause'])
542 || $analyzed_sql[0]['where_clause'] == '1 ')
543 && ! isset($find_real_end)
546 // "j u s t b r o w s i n g"
547 $unlim_num_rows = PMA_Table::countRecords($db, $table);
549 } else { // n o t " j u s t b r o w s i n g "
551 // add select expression after the SQL_CALC_FOUND_ROWS
553 // for UNION, just adding SQL_CALC_FOUND_ROWS
554 // after the first SELECT works.
556 // take the left part, could be:
557 // SELECT
558 // (SELECT
559 $count_query = PMA_SQP_formatHtml($parsed_sql, 'query_only', 0, $analyzed_sql[0]['position_of_first_select'] + 1);
560 $count_query .= ' SQL_CALC_FOUND_ROWS ';
561 // add everything that was after the first SELECT
562 $count_query .= PMA_SQP_formatHtml($parsed_sql, 'query_only', $analyzed_sql[0]['position_of_first_select']+1);
563 // ensure there is no semicolon at the end of the
564 // count query because we'll probably add
565 // a LIMIT 1 clause after it
566 $count_query = rtrim($count_query);
567 $count_query = rtrim($count_query, ';');
569 // if using SQL_CALC_FOUND_ROWS, add a LIMIT to avoid
570 // long delays. Returned count will be complete anyway.
571 // (but a LIMIT would disrupt results in an UNION)
573 if (! isset($analyzed_sql[0]['queryflags']['union'])) {
574 $count_query .= ' LIMIT 1';
577 // run the count query
579 PMA_DBI_try_query($count_query);
580 // if (mysql_error()) {
581 // void.
582 // I tried the case
583 // (SELECT `User`, `Host`, `Db`, `Select_priv` FROM `db`)
584 // UNION (SELECT `User`, `Host`, "%" AS "Db",
585 // `Select_priv`
586 // FROM `user`) ORDER BY `User`, `Host`, `Db`;
587 // and although the generated count_query is wrong
588 // the SELECT FOUND_ROWS() work! (maybe it gets the
589 // count from the latest query that worked)
591 // another case where the count_query is wrong:
592 // SELECT COUNT(*), f1 from t1 group by f1
593 // and you click to sort on count(*)
594 // }
595 $unlim_num_rows = PMA_DBI_fetch_value('SELECT FOUND_ROWS()');
596 } // end else "just browsing"
598 } else { // not $is_select
599 $unlim_num_rows = 0;
600 } // end rows total count
602 // if a table or database gets dropped, check column comments.
603 if (isset($purge) && $purge == '1') {
605 * Cleanup relations.
607 require_once './libraries/relation_cleanup.lib.php';
609 if (strlen($table) && strlen($db)) {
610 PMA_relationsCleanupTable($db, $table);
611 } elseif (strlen($db)) {
612 PMA_relationsCleanupDatabase($db);
613 } else {
614 // VOID. No DB/Table gets deleted.
615 } // end if relation-stuff
616 } // end if ($purge)
618 // If a column gets dropped, do relation magic.
619 if (isset($dropped_column) && strlen($db) && strlen($table) && !empty($dropped_column)) {
620 require_once './libraries/relation_cleanup.lib.php';
621 PMA_relationsCleanupColumn($db, $table, $dropped_column);
623 } // end if column was dropped
624 } // end else "didn't ask to see php code"
626 // No rows returned -> move back to the calling page
627 if (0 == $num_rows || $is_affected) {
628 if ($is_delete) {
629 $message = PMA_Message::deleted_rows($num_rows);
630 } elseif ($is_insert) {
631 if ($is_replace) {
632 /* For replace we get DELETED + INSERTED row count, so we have to call it affected */
633 $message = PMA_Message::affected_rows($num_rows);
634 } else {
635 $message = PMA_Message::inserted_rows($num_rows);
637 $insert_id = PMA_DBI_insert_id();
638 if ($insert_id != 0) {
639 // insert_id is id of FIRST record inserted in one insert, so if we inserted multiple rows, we had to increment this
640 $message->addMessage('[br]');
641 // need to use a temporary because the Message class
642 // currently supports adding parameters only to the first
643 // message
644 $_inserted = PMA_Message::notice(__('Inserted row id: %1$d'));
645 $_inserted->addParam($insert_id + $num_rows - 1);
646 $message->addMessage($_inserted);
648 } elseif ($is_affected) {
649 $message = PMA_Message::affected_rows($num_rows);
651 // Ok, here is an explanation for the !$is_select.
652 // The form generated by sql_query_form.lib.php
653 // and db_sql.php has many submit buttons
654 // on the same form, and some confusion arises from the
655 // fact that $message_to_show is sent for every case.
656 // The $message_to_show containing a success message and sent with
657 // the form should not have priority over errors
658 } elseif (!empty($message_to_show) && !$is_select) {
659 $message = PMA_Message::rawSuccess(htmlspecialchars($message_to_show));
660 } elseif (!empty($GLOBALS['show_as_php'])) {
661 $message = PMA_Message::success(__('Showing as PHP code'));
662 } elseif (isset($GLOBALS['show_as_php'])) {
663 /* User disable showing as PHP, query is only displayed */
664 $message = PMA_Message::notice(__('Showing SQL query'));
665 } elseif (!empty($GLOBALS['validatequery'])) {
666 $message = PMA_Message::notice(__('Validated SQL'));
667 } else {
668 $message = PMA_Message::success(__('MySQL returned an empty result set (i.e. zero rows).'));
671 if (isset($GLOBALS['querytime'])) {
672 $_querytime = PMA_Message::notice(__('Query took %01.4f sec'));
673 $_querytime->addParam($GLOBALS['querytime']);
674 $message->addMessage('(');
675 $message->addMessage($_querytime);
676 $message->addMessage(')');
679 if( $GLOBALS['is_ajax_request'] == true) {
682 * If we are in inline editing, we need to process the relational and
683 * transformed fields, if they were edited. After that, output the correct
684 * link/transformed value and exit
686 * Logic taken from libraries/display_tbl.lib.php
689 if(isset($_REQUEST['rel_fields_list']) && $_REQUEST['rel_fields_list'] != '') {
690 //handle relations work here for updated row.
691 require_once './libraries/relation.lib.php';
693 $map = PMA_getForeigners($db, $table, '', 'both');
695 $rel_fields = array();
696 parse_str($_REQUEST['rel_fields_list'], $rel_fields);
698 foreach( $rel_fields as $rel_field => $rel_field_value) {
700 $where_comparison = "='" . $rel_field_value . "'";
701 $display_field = PMA_getDisplayField($map[$rel_field]['foreign_db'], $map[$rel_field]['foreign_table']);
703 // Field to display from the foreign table?
704 if (isset($display_field) && strlen($display_field)) {
705 $dispsql = 'SELECT ' . PMA_backquote($display_field)
706 . ' FROM ' . PMA_backquote($map[$rel_field]['foreign_db'])
707 . '.' . PMA_backquote($map[$rel_field]['foreign_table'])
708 . ' WHERE ' . PMA_backquote($map[$rel_field]['foreign_field'])
709 . $where_comparison;
710 $dispresult = PMA_DBI_try_query($dispsql, null, PMA_DBI_QUERY_STORE);
711 if ($dispresult && PMA_DBI_num_rows($dispresult) > 0) {
712 list($dispval) = PMA_DBI_fetch_row($dispresult, 0);
713 } else {
714 //$dispval = __('Link not found');
716 @PMA_DBI_free_result($dispresult);
717 } else {
718 $dispval = '';
719 } // end if... else...
721 if ('K' == $_SESSION['tmp_user_values']['relational_display']) {
722 // user chose "relational key" in the display options, so
723 // the title contains the display field
724 $title = (! empty($dispval))? ' title="' . htmlspecialchars($dispval) . '"' : '';
725 } else {
726 $title = ' title="' . htmlspecialchars($rel_field_value) . '"';
729 $_url_params = array(
730 'db' => $map[$rel_field]['foreign_db'],
731 'table' => $map[$rel_field]['foreign_table'],
732 'pos' => '0',
733 'sql_query' => 'SELECT * FROM '
734 . PMA_backquote($map[$rel_field]['foreign_db']) . '.' . PMA_backquote($map[$rel_field]['foreign_table'])
735 . ' WHERE ' . PMA_backquote($map[$rel_field]['foreign_field'])
736 . $where_comparison
738 $output = '<a href="sql.php' . PMA_generate_common_url($_url_params) . '"' . $title . '>';
740 if ('D' == $_SESSION['tmp_user_values']['relational_display']) {
741 // user chose "relational display field" in the
742 // display options, so show display field in the cell
743 $output .= (!empty($dispval)) ? htmlspecialchars($dispval) : '';
744 } else {
745 // otherwise display data in the cell
746 $output .= htmlspecialchars($rel_field_value);
748 $output .= '</a>';
749 $extra_data['relations'][$rel_field] = $output;
753 if(isset($_REQUEST['do_transformations']) && $_REQUEST['do_transformations'] == true ) {
754 require_once './libraries/transformations.lib.php';
755 //if some posted fields need to be transformed, generate them here.
756 $mime_map = PMA_getMIME($db, $table);
758 if ($mime_map === false) {
759 $mime_map = array();
762 $edited_values = array();
763 parse_str($_REQUEST['transform_fields_list'], $edited_values);
765 foreach($mime_map as $transformation) {
766 $include_file = $transformation['transformation'];
767 $column_name = $transformation['column_name'];
768 $column_data = $edited_values[$column_name];
770 $_url_params = array(
771 'db' => $db,
772 'table' => $table,
773 'where_clause' => $_REQUEST['where_clause'],
774 'transform_key' => $column_name,
777 if (file_exists('./libraries/transformations/' . $include_file)) {
778 $transformfunction_name = str_replace('.inc.php', '', $transformation['transformation']);
780 require_once './libraries/transformations/' . $include_file;
782 if (function_exists('PMA_transformation_' . $transformfunction_name)) {
783 $transform_function = 'PMA_transformation_' . $transformfunction_name;
784 $transform_options = PMA_transformation_getOptions((isset($transformation['transformation_options']) ? $transformation['transformation_options'] : ''));
785 $transform_options['wrapper_link'] = PMA_generate_common_url($_url_params);
789 $extra_data['transformations'][$column_name] = $transform_function($column_data, $transform_options);
793 if ($cfg['ShowSQL']) {
794 $extra_data['sql_query'] = PMA_showMessage($message, $GLOBALS['sql_query'], 'success');
796 if (isset($GLOBALS['reload']) && $GLOBALS['reload'] == 1) {
797 $extra_data['reload'] = 1;
798 $extra_data['db'] = $GLOBALS['db'];
800 PMA_ajaxResponse($message, $message->isSuccess(), (isset($extra_data) ? $extra_data : ''));
803 if ($is_gotofile) {
804 $goto = PMA_securePath($goto);
805 // Checks for a valid target script
806 $is_db = $is_table = false;
807 if (isset($_REQUEST['purge'])) {
808 $table = '';
809 unset($url_params['table']);
811 include 'libraries/db_table_exists.lib.php';
813 if (strpos($goto, 'tbl_') === 0 && ! $is_table) {
814 if (strlen($table)) {
815 $table = '';
817 $goto = 'db_sql.php';
819 if (strpos($goto, 'db_') === 0 && ! $is_db) {
820 if (strlen($db)) {
821 $db = '';
823 $goto = 'main.php';
825 // Loads to target script
826 if ($goto != 'main.php') {
827 require_once './libraries/header.inc.php';
829 $active_page = $goto;
830 require './' . $goto;
831 } else {
832 // avoid a redirect loop when last record was deleted
833 if (0 == $num_rows && 'sql.php' == $cfg['DefaultTabTable']) {
834 $goto = str_replace('sql.php','tbl_structure.php',$goto);
836 PMA_sendHeaderLocation($cfg['PmaAbsoluteUri'] . str_replace('&amp;', '&', $goto) . '&message=' . urlencode($message));
837 } // end else
838 exit();
839 } // end no rows returned
841 // At least one row is returned -> displays a table with results
842 else {
843 //If we are retrieving the full value of a truncated field or the original
844 // value of a transformed field, show it here and exit
845 if( $GLOBALS['inline_edit'] == true && $GLOBALS['cfg']['AjaxEnable']) {
846 $row = PMA_DBI_fetch_row($result);
847 $extra_data = array();
848 $extra_data['value'] = $row[0];
849 PMA_ajaxResponse(NULL, true, $extra_data);
852 // Displays the headers
853 if (isset($show_query)) {
854 unset($show_query);
856 if (isset($printview) && $printview == '1') {
857 require_once './libraries/header_printview.inc.php';
858 } else {
860 $GLOBALS['js_include'][] = 'functions.js';
861 $GLOBALS['js_include'][] = 'makegrid.js';
862 $GLOBALS['js_include'][] = 'sql.js';
864 unset($message);
866 if( ! $GLOBALS['is_ajax_request'] || ! $GLOBALS['cfg']['AjaxEnable']) {
867 if (strlen($table)) {
868 require './libraries/tbl_common.php';
869 $url_query .= '&amp;goto=tbl_sql.php&amp;back=tbl_sql.php';
870 require './libraries/tbl_info.inc.php';
871 require './libraries/tbl_links.inc.php';
872 } elseif (strlen($db)) {
873 require './libraries/db_common.inc.php';
874 require './libraries/db_info.inc.php';
875 } else {
876 require './libraries/server_common.inc.php';
877 require './libraries/server_links.inc.php';
880 else {
881 require_once './libraries/header.inc.php';
882 //we don't need to buffer the output in PMA_showMessage here.
883 //set a global variable and check against it in the function
884 $GLOBALS['buffer_message'] = false;
888 if (strlen($db)) {
889 $cfgRelation = PMA_getRelationsParam();
892 // Gets the list of fields properties
893 if (isset($result) && $result) {
894 $fields_meta = PMA_DBI_get_fields_meta($result);
895 $fields_cnt = count($fields_meta);
898 if( ! $GLOBALS['is_ajax_request']) {
899 //begin the sqlqueryresults div here. container div
900 echo '<div id="sqlqueryresults"';
901 if ($GLOBALS['cfg']['AjaxEnable']) {
902 echo ' class="ajax"';
904 echo '>';
907 // Display previous update query (from tbl_replace)
908 if (isset($disp_query) && $cfg['ShowSQL'] == true) {
909 PMA_showMessage($disp_message, $disp_query, 'success');
912 if (isset($profiling_results)) {
913 // pma_token/url_query needed for chart export
915 <script type="text/javascript">
916 pma_token = '<?php echo $_SESSION[' PMA_token ']; ?>';
917 url_query = '<?php echo isset($url_query)?$url_query:PMA_generate_common_url($db);?>';
918 $(document).ready(createProfilingChart);
919 </script>
920 <?php
921 echo '<fieldset><legend>' . __('Profiling') . '</legend>' . "\n";
922 echo '<div style="float: left;">';
923 echo '<table>' . "\n";
924 echo ' <tr>' . "\n";
925 echo ' <th>' . __('Status') . '</th>' . "\n";
926 echo ' <th>' . __('Time') . '</th>' . "\n";
927 echo ' </tr>' . "\n";
929 $chart_json = Array();
930 foreach($profiling_results as $one_result) {
931 echo ' <tr>' . "\n";
932 echo '<td>' . ucwords($one_result['Status']) . '</td>' . "\n";
933 echo '<td align="right">' . (PMA_formatNumber($one_result['Duration'],3,1)) . 's</td>' . "\n";
934 $chart_json[ucwords($one_result['Status'])] = $one_result['Duration'];
937 echo '</table>' . "\n";
938 echo '</div>';
939 //require_once './libraries/chart.lib.php';
940 echo '<div id="profilingchart" style="display:none;">';
941 //PMA_chart_profiling($profiling_results);
942 echo json_encode($chart_json);
943 echo '</div>';
944 echo '</fieldset>' . "\n";
947 // Displays the results in a table
948 if (empty($disp_mode)) {
949 // see the "PMA_setDisplayMode()" function in
950 // libraries/display_tbl.lib.php
951 $disp_mode = 'urdr111101';
954 // hide edit and delete links for information_schema
955 if (strtolower($db) == 'information_schema' || (PMA_DRIZZLE && strtolower($db) == 'data_dictionary')) {
956 $disp_mode = 'nnnn110111';
959 if (isset($label)) {
960 $message = PMA_message::success(__('Bookmark %s created'));
961 $message->addParam($label);
962 $message->display();
965 PMA_displayTable($result, $disp_mode, $analyzed_sql);
966 PMA_DBI_free_result($result);
968 // BEGIN INDEX CHECK See if indexes should be checked.
969 if (isset($query_type) && $query_type == 'check_tbl' && isset($selected) && is_array($selected)) {
970 foreach ($selected as $idx => $tbl_name) {
971 $check = PMA_Index::findDuplicates($tbl_name, $db);
972 if (! empty($check)) {
973 printf(__('Problems with indexes of table `%s`'), $tbl_name);
974 echo $check;
977 } // End INDEX CHECK
979 // Bookmark support if required
980 if ($disp_mode[7] == '1'
981 && (! empty($cfg['Bookmark']) && empty($id_bookmark))
982 && !empty($sql_query)) {
983 echo "\n";
985 $goto = 'sql.php?'
986 . PMA_generate_common_url($db, $table)
987 . '&amp;sql_query=' . urlencode($sql_query)
988 . '&amp;id_bookmark=1';
991 <form action="sql.php" method="post" onsubmit="return emptyFormElements(this, 'fields[label]');">
992 <?php echo PMA_generate_common_hidden_inputs(); ?>
993 <input type="hidden" name="goto" value="<?php echo $goto; ?>" />
994 <input type="hidden" name="fields[dbase]" value="<?php echo htmlspecialchars($db); ?>" />
995 <input type="hidden" name="fields[user]" value="<?php echo $cfg['Bookmark']['user']; ?>" />
996 <input type="hidden" name="fields[query]" value="<?php echo urlencode(isset($complete_query) ? $complete_query : $sql_query); ?>" />
997 <fieldset>
998 <legend><?php
999 echo ($cfg['PropertiesIconic'] ? '<img class="icon" src="' . $pmaThemeImage . 'b_bookmark.png" width="16" height="16" alt="' . __('Bookmark this SQL query') . '" />' : '')
1000 . __('Bookmark this SQL query');
1002 </legend>
1004 <div class="formelement">
1005 <label for="fields_label_"><?php echo __('Label'); ?>:</label>
1006 <input type="text" id="fields_label_" name="fields[label]" value="" />
1007 </div>
1009 <div class="formelement">
1010 <input type="checkbox" name="bkm_all_users" id="bkm_all_users" value="true" />
1011 <label for="bkm_all_users"><?php echo __('Let every user access this bookmark'); ?></label>
1012 </div>
1014 <div class="clearfloat"></div>
1015 </fieldset>
1016 <fieldset class="tblFooters">
1017 <input type="submit" name="store_bkm" value="<?php echo __('Bookmark this SQL query'); ?>" />
1018 </fieldset>
1019 </form>
1020 <?php
1021 } // end bookmark support
1023 // Do print the page if required
1024 if (isset($printview) && $printview == '1') {
1026 <script type="text/javascript">
1027 //<![CDATA[
1028 // Do print the page
1029 window.onload = function()
1031 if (typeof(window.print) != 'undefined') {
1032 window.print();
1035 //]]>
1036 </script>
1037 <?php
1038 } // end print case
1040 if( $GLOBALS['is_ajax_request'] != true) {
1041 echo '</div>'; // end sqlqueryresults div
1043 } // end rows returned
1046 * Displays the footer
1048 if(! isset($_REQUEST['table_maintenance'])) {
1049 require './libraries/footer.inc.php';