Merge remote-tracking branch 'origin/master' into drizzle
[phpmyadmin.git] / sql.php
blob25834bff5a0eb4228729de338e6a9a692f20dbb5
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 $GLOBALS['js_include'][] = 'canvg/canvg.js';
25 $GLOBALS['js_include'][] = 'canvg/rgbcolor.js';
28 /**
29 * Defines the url to return to in case of error in a sql statement
31 // Security checkings
32 if (! empty($goto)) {
33 $is_gotofile = preg_replace('@^([^?]+).*$@s', '\\1', $goto);
34 if (! @file_exists('./' . $is_gotofile)) {
35 unset($goto);
36 } else {
37 $is_gotofile = ($is_gotofile == $goto);
39 } else {
40 $goto = (! strlen($table)) ? $cfg['DefaultTabDatabase'] : $cfg['DefaultTabTable'];
41 $is_gotofile = true;
42 } // end if
44 if (! isset($err_url)) {
45 $err_url = (!empty($back) ? $back : $goto)
46 . '?' . PMA_generate_common_url($db)
47 . ((strpos(' ' . $goto, 'db_') != 1 && strlen($table)) ? '&amp;table=' . urlencode($table) : '');
48 } // end if
50 // Coming from a bookmark dialog
51 if (isset($fields['query'])) {
52 $sql_query = $fields['query'];
55 // This one is just to fill $db
56 if (isset($fields['dbase'])) {
57 $db = $fields['dbase'];
60 /**
61 * During inline edit, if we have a relational field, show the dropdown for it
63 * Logic taken from libraries/display_tbl_lib.php
65 * This doesn't seem to be the right place to do this, but I can't think of any
66 * better place either.
68 if (isset($_REQUEST['get_relational_values']) && $_REQUEST['get_relational_values'] == true) {
69 require_once 'libraries/relation.lib.php';
71 $column = $_REQUEST['column'];
72 $foreigners = PMA_getForeigners($db, $table, $column);
74 $display_field = PMA_getDisplayField($foreigners[$column]['foreign_db'], $foreigners[$column]['foreign_table']);
76 $foreignData = PMA_getForeignData($foreigners, $column, false, '', '');
78 if ($_SESSION['tmp_user_values']['relational_display'] == 'D'
79 && (isset($display_field) && strlen($display_field)
80 && (isset($_REQUEST['relation_key_or_display_column']) && $_REQUEST['relation_key_or_display_column']))) {
81 $curr_value = $_REQUEST['relation_key_or_display_column'];
82 } else {
83 $curr_value = $_REQUEST['curr_value'];
85 if ($foreignData['disp_row'] == null) {
86 //Handle the case when number of values is more than $cfg['ForeignKeyMaxLimit']
87 $_url_params = array(
88 'db' => $db,
89 'table' => $table,
90 'field' => $column
93 $dropdown = '<span class="curr_value">' . htmlspecialchars($_REQUEST['curr_value']) . '</span> <a href="browse_foreigners.php' . PMA_generate_common_url($_url_params) . '"'
94 . ' target="_blank" class="browse_foreign" '
95 .'>' . __('Browse foreign values') . '</a>';
97 else {
98 $dropdown = PMA_foreignDropdown($foreignData['disp_row'], $foreignData['foreign_field'], $foreignData['foreign_display'], $curr_value, $cfg['ForeignKeyMaxLimit']);
99 $dropdown = '<select>' . $dropdown . '</select>';
102 $extra_data['dropdown'] = $dropdown;
103 PMA_ajaxResponse(NULL, true, $extra_data);
107 * Just like above, find possible values for enum fields during inline edit.
109 * Logic taken from libraries/display_tbl_lib.php
111 if (isset($_REQUEST['get_enum_values']) && $_REQUEST['get_enum_values'] == true) {
112 $field_info_query = PMA_DBI_get_columns_sql($db, $table, $_REQUEST['column']);
114 $field_info_result = PMA_DBI_fetch_result($field_info_query, null, null, null, PMA_DBI_QUERY_STORE);
116 $search = array('enum', '(', ')', "'");
118 $values = explode(',', str_replace($search, '', $field_info_result[0]['Type']));
120 $dropdown = '<option value="">&nbsp;</option>';
121 foreach ($values as $value) {
122 $dropdown .= '<option value="' . htmlspecialchars($value) . '"';
123 if ($value == $_REQUEST['curr_value']) {
124 $dropdown .= ' selected="selected"';
126 $dropdown .= '>' . $value . '</option>';
129 $dropdown = '<select>' . $dropdown . '</select>';
131 $extra_data['dropdown'] = $dropdown;
132 PMA_ajaxResponse(NULL, true, $extra_data);
136 * Find possible values for set fields during inline edit.
138 if (isset($_REQUEST['get_set_values']) && $_REQUEST['get_set_values'] == true) {
139 $field_info_query = PMA_DBI_get_columns_sql($db, $table, $_REQUEST['column']);
141 $field_info_result = PMA_DBI_fetch_result($field_info_query, null, null, null, PMA_DBI_QUERY_STORE);
143 $selected_values = explode(',', $_REQUEST['curr_value']);
145 $search = array('set', '(', ')', "'");
146 $values = explode(',', str_replace($search, '', $field_info_result[0]['Type']));
148 $select = '';
149 foreach ($values as $value) {
150 $select .= '<option value="' . htmlspecialchars($value) . '"';
151 if (in_array($value, $selected_values, true)) {
152 $select .= ' selected="selected"';
154 $select .= '>' . $value . '</option>';
157 $select_size = (sizeof($values) > 10) ? 10 : sizeof($values);
158 $select = '<select multiple="multiple" size="' . $select_size . '">' . $select . '</select>';
160 $extra_data['select'] = $select;
161 PMA_ajaxResponse(NULL, true, $extra_data);
165 * Check ajax request to set the column order
167 if (isset($_REQUEST['set_col_prefs']) && $_REQUEST['set_col_prefs'] == true) {
168 $pmatable = new PMA_Table($table, $db);
170 // set column order
171 $col_order = explode(',', $_REQUEST['col_order']);
172 $retval = $pmatable->setUiProp(PMA_Table::PROP_COLUMN_ORDER, $col_order, $_REQUEST['table_create_time']);
174 // set column visibility
175 $col_visib = explode(',', $_REQUEST['col_visib']);
176 $retval &= $pmatable->setUiProp(PMA_Table::PROP_COLUMN_VISIB, $col_visib, $_REQUEST['table_create_time']);
178 PMA_ajaxResponse(NULL, ($retval == true));
181 // Default to browse if no query set and we have table
182 // (needed for browsing from DefaultTabTable)
183 if (empty($sql_query) && strlen($table) && strlen($db)) {
184 require_once './libraries/bookmark.lib.php';
185 $book_sql_query = PMA_Bookmark_get($db, '\'' . PMA_sqlAddSlashes($table) . '\'',
186 'label', false, true);
188 if (! empty($book_sql_query)) {
189 $GLOBALS['using_bookmark_message'] = PMA_message::notice(__('Using bookmark "%s" as default browse query.'));
190 $GLOBALS['using_bookmark_message']->addParam($table);
191 $GLOBALS['using_bookmark_message']->addMessage(PMA_showDocu('faq6_22'));
192 $sql_query = $book_sql_query;
193 } else {
194 $sql_query = 'SELECT * FROM ' . PMA_backquote($table);
196 unset($book_sql_query);
198 // set $goto to what will be displayed if query returns 0 rows
199 $goto = 'tbl_structure.php';
200 } else {
201 // Now we can check the parameters
202 PMA_checkParameters(array('sql_query'));
205 // instead of doing the test twice
206 $is_drop_database = preg_match('/DROP[[:space:]]+(DATABASE|SCHEMA)[[:space:]]+/i',
207 $sql_query);
210 * Check rights in case of DROP DATABASE
212 * This test may be bypassed if $is_js_confirmed = 1 (already checked with js)
213 * but since a malicious user may pass this variable by url/form, we don't take
214 * into account this case.
216 if (!defined('PMA_CHK_DROP')
217 && !$cfg['AllowUserDropDatabase']
218 && $is_drop_database
219 && !$is_superuser) {
220 require_once './libraries/header.inc.php';
221 PMA_mysqlDie(__('"DROP DATABASE" statements are disabled.'), '', '', $err_url);
222 } // end if
224 require_once './libraries/display_tbl.lib.php';
225 PMA_displayTable_checkConfigParams();
228 * Need to find the real end of rows?
230 if (isset($find_real_end) && $find_real_end) {
231 $unlim_num_rows = PMA_Table::countRecords($db, $table, $force_exact = true);
232 $_SESSION['tmp_user_values']['pos'] = @((ceil($unlim_num_rows / $_SESSION['tmp_user_values']['max_rows']) - 1) * $_SESSION['tmp_user_values']['max_rows']);
237 * Bookmark add
239 if (isset($store_bkm)) {
240 PMA_Bookmark_save($fields, (isset($bkm_all_users) && $bkm_all_users == 'true' ? true : false));
241 // go back to sql.php to redisplay query; do not use &amp; in this case:
242 PMA_sendHeaderLocation($cfg['PmaAbsoluteUri'] . $goto . '&label=' . $fields['label']);
243 } // end if
246 * Parse and analyze the query
248 require_once './libraries/parse_analyze.lib.php';
251 * Sets or modifies the $goto variable if required
253 if ($goto == 'sql.php') {
254 $is_gotofile = false;
255 $goto = 'sql.php?'
256 . PMA_generate_common_url($db, $table)
257 . '&amp;sql_query=' . urlencode($sql_query);
258 } // end if
262 * Go back to further page if table should not be dropped
264 if (isset($btnDrop) && $btnDrop == __('No')) {
265 if (!empty($back)) {
266 $goto = $back;
268 if ($is_gotofile) {
269 if (strpos($goto, 'db_') === 0 && strlen($table)) {
270 $table = '';
272 $active_page = $goto;
273 require './' . PMA_securePath($goto);
274 } else {
275 PMA_sendHeaderLocation($cfg['PmaAbsoluteUri'] . str_replace('&amp;', '&', $goto));
277 exit();
278 } // end if
282 * Displays the confirm page if required
284 * This part of the script is bypassed if $is_js_confirmed = 1 (already checked
285 * with js) because possible security issue is not so important here: at most,
286 * the confirm message isn't displayed.
288 * Also bypassed if only showing php code.or validating a SQL query
290 if (! $cfg['Confirm'] || isset($_REQUEST['is_js_confirmed']) || isset($btnDrop)
291 // if we are coming from a "Create PHP code" or a "Without PHP Code"
292 // dialog, we won't execute the query anyway, so don't confirm
293 || isset($GLOBALS['show_as_php'])
294 || !empty($GLOBALS['validatequery'])) {
295 $do_confirm = false;
296 } else {
297 $do_confirm = isset($analyzed_sql[0]['queryflags']['need_confirm']);
300 if ($do_confirm) {
301 $stripped_sql_query = $sql_query;
302 require_once './libraries/header.inc.php';
303 if ($is_drop_database) {
304 echo '<h1 class="error">' . __('You are about to DESTROY a complete database!') . '</h1>';
306 echo '<form action="sql.php" method="post">' . "\n"
307 .PMA_generate_common_hidden_inputs($db, $table);
309 <input type="hidden" name="sql_query" value="<?php echo htmlspecialchars($sql_query); ?>" />
310 <input type="hidden" name="message_to_show" value="<?php echo isset($message_to_show) ? PMA_sanitize($message_to_show, true) : ''; ?>" />
311 <input type="hidden" name="goto" value="<?php echo $goto; ?>" />
312 <input type="hidden" name="back" value="<?php echo isset($back) ? PMA_sanitize($back, true) : ''; ?>" />
313 <input type="hidden" name="reload" value="<?php echo isset($reload) ? PMA_sanitize($reload, true) : 0; ?>" />
314 <input type="hidden" name="purge" value="<?php echo isset($purge) ? PMA_sanitize($purge, true) : ''; ?>" />
315 <input type="hidden" name="dropped_column" value="<?php echo isset($dropped_column) ? PMA_sanitize($dropped_column, true) : ''; ?>" />
316 <input type="hidden" name="show_query" value="<?php echo isset($show_query) ? PMA_sanitize($show_query, true) : ''; ?>" />
317 <?php
318 echo '<fieldset class="confirmation">' . "\n"
319 .' <legend>' . __('Do you really want to ') . '</legend>'
320 .' <tt>' . htmlspecialchars($stripped_sql_query) . '</tt>' . "\n"
321 .'</fieldset>' . "\n"
322 .'<fieldset class="tblFooters">' . "\n";
324 <input type="submit" name="btnDrop" value="<?php echo __('Yes'); ?>" id="buttonYes" />
325 <input type="submit" name="btnDrop" value="<?php echo __('No'); ?>" id="buttonNo" />
326 <?php
327 echo '</fieldset>' . "\n"
328 . '</form>' . "\n";
331 * Displays the footer and exit
333 require './libraries/footer.inc.php';
334 } // end if $do_confirm
337 // Defines some variables
338 // A table has to be created, renamed, dropped -> navi frame should be reloaded
340 * @todo use the parser/analyzer
343 if (empty($reload)
344 && preg_match('/^(CREATE|ALTER|DROP)\s+(VIEW|TABLE|DATABASE|SCHEMA)\s+/i', $sql_query)) {
345 $reload = 1;
348 // SK -- Patch: $is_group added for use in calculation of total number of
349 // rows.
350 // $is_count is changed for more correct "LIMIT" clause
351 // appending in queries like
352 // "SELECT COUNT(...) FROM ... GROUP BY ..."
355 * @todo detect all this with the parser, to avoid problems finding
356 * those strings in comments or backquoted identifiers
359 $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;
360 if ($is_select) { // see line 141
361 $is_group = preg_match('@(GROUP[[:space:]]+BY|HAVING|SELECT[[:space:]]+DISTINCT)[[:space:]]+@i', $sql_query);
362 $is_func = !$is_group && (preg_match('@[[:space:]]+(SUM|AVG|STD|STDDEV|MIN|MAX|BIT_OR|BIT_AND)\s*\(@i', $sql_query));
363 $is_count = !$is_group && (preg_match('@^SELECT[[:space:]]+COUNT\((.*\.+)?.*\)@i', $sql_query));
364 $is_export = (preg_match('@[[:space:]]+INTO[[:space:]]+OUTFILE[[:space:]]+@i', $sql_query));
365 $is_analyse = (preg_match('@[[:space:]]+PROCEDURE[[:space:]]+ANALYSE@i', $sql_query));
366 } elseif (preg_match('@^EXPLAIN[[:space:]]+@i', $sql_query)) {
367 $is_explain = true;
368 } elseif (preg_match('@^DELETE[[:space:]]+@i', $sql_query)) {
369 $is_delete = true;
370 $is_affected = true;
371 } elseif (preg_match('@^(INSERT|LOAD[[:space:]]+DATA|REPLACE)[[:space:]]+@i', $sql_query)) {
372 $is_insert = true;
373 $is_affected = true;
374 if (preg_match('@^(REPLACE)[[:space:]]+@i', $sql_query)) {
375 $is_replace = true;
377 } elseif (preg_match('@^UPDATE[[:space:]]+@i', $sql_query)) {
378 $is_affected = true;
379 } elseif (preg_match('@^[[:space:]]*SHOW[[:space:]]+@i', $sql_query)) {
380 $is_show = true;
381 } elseif (preg_match('@^(CHECK|ANALYZE|REPAIR|OPTIMIZE)[[:space:]]+TABLE[[:space:]]+@i', $sql_query)) {
382 $is_maint = true;
385 // assign default full_sql_query
386 $full_sql_query = $sql_query;
388 // Handle remembered sorting order, only for single table query
389 if ($GLOBALS['cfg']['RememberSorting']
390 && ! ($is_count || $is_export || $is_func || $is_analyse)
391 && count($analyzed_sql[0]['select_expr']) == 0
392 && isset($analyzed_sql[0]['queryflags']['select_from'])
393 && count($analyzed_sql[0]['table_ref']) == 1
395 $pmatable = new PMA_Table($table, $db);
396 if (empty($analyzed_sql[0]['order_by_clause'])) {
397 $sorted_col = $pmatable->getUiProp(PMA_Table::PROP_SORTED_COLUMN);
398 if ($sorted_col) {
399 // retrieve the remembered sorting order for current table
400 $sql_order_to_append = ' ORDER BY ' . $sorted_col . ' ';
401 $full_sql_query = $analyzed_sql[0]['section_before_limit'] . $sql_order_to_append . $analyzed_sql[0]['section_after_limit'];
403 // update the $analyzed_sql
404 $analyzed_sql[0]['section_before_limit'] .= $sql_order_to_append;
405 $analyzed_sql[0]['order_by_clause'] = $sorted_col;
407 } else {
408 // store the remembered table into session
409 $pmatable->setUiProp(PMA_Table::PROP_SORTED_COLUMN, $analyzed_sql[0]['order_by_clause']);
413 // Do append a "LIMIT" clause?
414 if ((! $cfg['ShowAll'] || $_SESSION['tmp_user_values']['max_rows'] != 'all')
415 && ! ($is_count || $is_export || $is_func || $is_analyse)
416 && isset($analyzed_sql[0]['queryflags']['select_from'])
417 && ! isset($analyzed_sql[0]['queryflags']['offset'])
418 && empty($analyzed_sql[0]['limit_clause'])
420 $sql_limit_to_append = ' LIMIT ' . $_SESSION['tmp_user_values']['pos'] . ', ' . $_SESSION['tmp_user_values']['max_rows'] . " ";
422 $full_sql_query = $analyzed_sql[0]['section_before_limit'] . "\n" . $sql_limit_to_append . $analyzed_sql[0]['section_after_limit'];
424 * @todo pretty printing of this modified query
426 if (isset($display_query)) {
427 // if the analysis of the original query revealed that we found
428 // a section_after_limit, we now have to analyze $display_query
429 // to display it correctly
431 if (!empty($analyzed_sql[0]['section_after_limit']) && trim($analyzed_sql[0]['section_after_limit']) != ';') {
432 $analyzed_display_query = PMA_SQP_analyze(PMA_SQP_parse($display_query));
433 $display_query = $analyzed_display_query[0]['section_before_limit'] . "\n" . $sql_limit_to_append . $analyzed_display_query[0]['section_after_limit'];
439 if (strlen($db)) {
440 PMA_DBI_select_db($db);
443 // E x e c u t e t h e q u e r y
445 // Only if we didn't ask to see the php code (mikebeck)
446 if (isset($GLOBALS['show_as_php']) || !empty($GLOBALS['validatequery'])) {
447 unset($result);
448 $num_rows = 0;
449 } else {
450 if (isset($_SESSION['profiling']) && PMA_profilingSupported()) {
451 PMA_DBI_query('SET PROFILING=1;');
454 // Measure query time.
455 $querytime_before = array_sum(explode(' ', microtime()));
457 $result = @PMA_DBI_try_query($full_sql_query, null, PMA_DBI_QUERY_STORE);
459 // If a stored procedure was called, there may be more results that are
460 // queued up and waiting to be flushed from the buffer. So let's do that.
461 while (true) {
462 if (! PMA_DBI_more_results()) {
463 break;
465 PMA_DBI_next_result();
468 $querytime_after = array_sum(explode(' ', microtime()));
470 $GLOBALS['querytime'] = $querytime_after - $querytime_before;
472 // Displays an error message if required and stop parsing the script
473 if ($error = PMA_DBI_getError()) {
474 if ($is_gotofile) {
475 if (strpos($goto, 'db_') === 0 && strlen($table)) {
476 $table = '';
478 $active_page = $goto;
479 $message = PMA_Message::rawError($error);
481 if ($GLOBALS['is_ajax_request'] == true) {
482 PMA_ajaxResponse($message, false);
486 * Go to target path.
488 require './' . PMA_securePath($goto);
489 } else {
490 $full_err_url = (preg_match('@^(db|tbl)_@', $err_url))
491 ? $err_url . '&amp;show_query=1&amp;sql_query=' . urlencode($sql_query)
492 : $err_url;
493 PMA_mysqlDie($error, $full_sql_query, '', $full_err_url);
495 exit;
497 unset($error);
499 // Gets the number of rows affected/returned
500 // (This must be done immediately after the query because
501 // mysql_affected_rows() reports about the last query done)
503 if (!$is_affected) {
504 $num_rows = ($result) ? @PMA_DBI_num_rows($result) : 0;
505 } elseif (! isset($num_rows)) {
506 $num_rows = @PMA_DBI_affected_rows();
509 // Grabs the profiling results
510 if (isset($_SESSION['profiling']) && PMA_profilingSupported()) {
511 $profiling_results = PMA_DBI_fetch_result('SHOW PROFILE;');
514 // Checks if the current database has changed
515 // This could happen if the user sends a query like "USE `database`;"
517 * commented out auto-switching to active database - really required?
518 * bug #1814718 win: table list disappears (mixed case db names)
519 * https://sourceforge.net/support/tracker.php?aid=1814718
520 * @todo RELEASE test and comit or rollback before release
521 $current_db = PMA_DBI_fetch_value('SELECT DATABASE()');
522 if ($db !== $current_db) {
523 $db = $current_db;
524 $reload = 1;
526 unset($current_db);
529 // tmpfile remove after convert encoding appended by Y.Kawada
530 if (function_exists('PMA_kanji_file_conv')
531 && (isset($textfile) && file_exists($textfile))) {
532 unlink($textfile);
535 // Counts the total number of rows for the same 'SELECT' query without the
536 // 'LIMIT' clause that may have been programatically added
538 if (empty($sql_limit_to_append)) {
539 $unlim_num_rows = $num_rows;
540 // if we did not append a limit, set this to get a correct
541 // "Showing rows..." message
542 //$_SESSION['tmp_user_values']['max_rows'] = 'all';
543 } elseif ($is_select) {
545 // c o u n t q u e r y
547 // If we are "just browsing", there is only one table,
548 // and no WHERE clause (or just 'WHERE 1 '),
549 // we do a quick count (which uses MaxExactCount) because
550 // SQL_CALC_FOUND_ROWS is not quick on large InnoDB tables
552 // However, do not count again if we did it previously
553 // due to $find_real_end == true
555 if (!$is_group
556 && ! isset($analyzed_sql[0]['queryflags']['union'])
557 && ! isset($analyzed_sql[0]['table_ref'][1]['table_name'])
558 && (empty($analyzed_sql[0]['where_clause'])
559 || $analyzed_sql[0]['where_clause'] == '1 ')
560 && ! isset($find_real_end)
563 // "j u s t b r o w s i n g"
564 $unlim_num_rows = PMA_Table::countRecords($db, $table);
566 } else { // n o t " j u s t b r o w s i n g "
568 // add select expression after the SQL_CALC_FOUND_ROWS
570 // for UNION, just adding SQL_CALC_FOUND_ROWS
571 // after the first SELECT works.
573 // take the left part, could be:
574 // SELECT
575 // (SELECT
576 $count_query = PMA_SQP_formatHtml($parsed_sql, 'query_only', 0, $analyzed_sql[0]['position_of_first_select'] + 1);
577 $count_query .= ' SQL_CALC_FOUND_ROWS ';
578 // add everything that was after the first SELECT
579 $count_query .= PMA_SQP_formatHtml($parsed_sql, 'query_only', $analyzed_sql[0]['position_of_first_select']+1);
580 // ensure there is no semicolon at the end of the
581 // count query because we'll probably add
582 // a LIMIT 1 clause after it
583 $count_query = rtrim($count_query);
584 $count_query = rtrim($count_query, ';');
586 // if using SQL_CALC_FOUND_ROWS, add a LIMIT to avoid
587 // long delays. Returned count will be complete anyway.
588 // (but a LIMIT would disrupt results in an UNION)
590 if (! isset($analyzed_sql[0]['queryflags']['union'])) {
591 $count_query .= ' LIMIT 1';
594 // run the count query
596 PMA_DBI_try_query($count_query);
597 // if (mysql_error()) {
598 // void.
599 // I tried the case
600 // (SELECT `User`, `Host`, `Db`, `Select_priv` FROM `db`)
601 // UNION (SELECT `User`, `Host`, "%" AS "Db",
602 // `Select_priv`
603 // FROM `user`) ORDER BY `User`, `Host`, `Db`;
604 // and although the generated count_query is wrong
605 // the SELECT FOUND_ROWS() work! (maybe it gets the
606 // count from the latest query that worked)
608 // another case where the count_query is wrong:
609 // SELECT COUNT(*), f1 from t1 group by f1
610 // and you click to sort on count(*)
611 // }
612 $unlim_num_rows = PMA_DBI_fetch_value('SELECT FOUND_ROWS()');
613 } // end else "just browsing"
615 } else { // not $is_select
616 $unlim_num_rows = 0;
617 } // end rows total count
619 // if a table or database gets dropped, check column comments.
620 if (isset($purge) && $purge == '1') {
622 * Cleanup relations.
624 require_once './libraries/relation_cleanup.lib.php';
626 if (strlen($table) && strlen($db)) {
627 PMA_relationsCleanupTable($db, $table);
628 } elseif (strlen($db)) {
629 PMA_relationsCleanupDatabase($db);
630 } else {
631 // VOID. No DB/Table gets deleted.
632 } // end if relation-stuff
633 } // end if ($purge)
635 // If a column gets dropped, do relation magic.
636 if (isset($dropped_column) && strlen($db) && strlen($table) && !empty($dropped_column)) {
637 require_once './libraries/relation_cleanup.lib.php';
638 PMA_relationsCleanupColumn($db, $table, $dropped_column);
640 } // end if column was dropped
641 } // end else "didn't ask to see php code"
643 // No rows returned -> move back to the calling page
644 if (0 == $num_rows || $is_affected) {
645 if ($is_delete) {
646 $message = PMA_Message::deleted_rows($num_rows);
647 } elseif ($is_insert) {
648 if ($is_replace) {
649 /* For replace we get DELETED + INSERTED row count, so we have to call it affected */
650 $message = PMA_Message::affected_rows($num_rows);
651 } else {
652 $message = PMA_Message::inserted_rows($num_rows);
654 $insert_id = PMA_DBI_insert_id();
655 if ($insert_id != 0) {
656 // insert_id is id of FIRST record inserted in one insert, so if we inserted multiple rows, we had to increment this
657 $message->addMessage('[br]');
658 // need to use a temporary because the Message class
659 // currently supports adding parameters only to the first
660 // message
661 $_inserted = PMA_Message::notice(__('Inserted row id: %1$d'));
662 $_inserted->addParam($insert_id + $num_rows - 1);
663 $message->addMessage($_inserted);
665 } elseif ($is_affected) {
666 $message = PMA_Message::affected_rows($num_rows);
668 // Ok, here is an explanation for the !$is_select.
669 // The form generated by sql_query_form.lib.php
670 // and db_sql.php has many submit buttons
671 // on the same form, and some confusion arises from the
672 // fact that $message_to_show is sent for every case.
673 // The $message_to_show containing a success message and sent with
674 // the form should not have priority over errors
675 } elseif (!empty($message_to_show) && !$is_select) {
676 $message = PMA_Message::rawSuccess(htmlspecialchars($message_to_show));
677 } elseif (!empty($GLOBALS['show_as_php'])) {
678 $message = PMA_Message::success(__('Showing as PHP code'));
679 } elseif (isset($GLOBALS['show_as_php'])) {
680 /* User disable showing as PHP, query is only displayed */
681 $message = PMA_Message::notice(__('Showing SQL query'));
682 } elseif (!empty($GLOBALS['validatequery'])) {
683 $message = PMA_Message::notice(__('Validated SQL'));
684 } else {
685 $message = PMA_Message::success(__('MySQL returned an empty result set (i.e. zero rows).'));
688 if (isset($GLOBALS['querytime'])) {
689 $_querytime = PMA_Message::notice(__('Query took %01.4f sec'));
690 $_querytime->addParam($GLOBALS['querytime']);
691 $message->addMessage('(');
692 $message->addMessage($_querytime);
693 $message->addMessage(')');
696 if ($GLOBALS['is_ajax_request'] == true) {
699 * If we are in inline editing, we need to process the relational and
700 * transformed fields, if they were edited. After that, output the correct
701 * link/transformed value and exit
703 * Logic taken from libraries/display_tbl.lib.php
706 if (isset($_REQUEST['rel_fields_list']) && $_REQUEST['rel_fields_list'] != '') {
707 //handle relations work here for updated row.
708 require_once './libraries/relation.lib.php';
710 $map = PMA_getForeigners($db, $table, '', 'both');
712 $rel_fields = array();
713 parse_str($_REQUEST['rel_fields_list'], $rel_fields);
715 foreach ( $rel_fields as $rel_field => $rel_field_value) {
717 $where_comparison = "='" . $rel_field_value . "'";
718 $display_field = PMA_getDisplayField($map[$rel_field]['foreign_db'], $map[$rel_field]['foreign_table']);
720 // Field to display from the foreign table?
721 if (isset($display_field) && strlen($display_field)) {
722 $dispsql = 'SELECT ' . PMA_backquote($display_field)
723 . ' FROM ' . PMA_backquote($map[$rel_field]['foreign_db'])
724 . '.' . PMA_backquote($map[$rel_field]['foreign_table'])
725 . ' WHERE ' . PMA_backquote($map[$rel_field]['foreign_field'])
726 . $where_comparison;
727 $dispresult = PMA_DBI_try_query($dispsql, null, PMA_DBI_QUERY_STORE);
728 if ($dispresult && PMA_DBI_num_rows($dispresult) > 0) {
729 list($dispval) = PMA_DBI_fetch_row($dispresult, 0);
730 } else {
731 //$dispval = __('Link not found');
733 @PMA_DBI_free_result($dispresult);
734 } else {
735 $dispval = '';
736 } // end if... else...
738 if ('K' == $_SESSION['tmp_user_values']['relational_display']) {
739 // user chose "relational key" in the display options, so
740 // the title contains the display field
741 $title = (! empty($dispval))? ' title="' . htmlspecialchars($dispval) . '"' : '';
742 } else {
743 $title = ' title="' . htmlspecialchars($rel_field_value) . '"';
746 $_url_params = array(
747 'db' => $map[$rel_field]['foreign_db'],
748 'table' => $map[$rel_field]['foreign_table'],
749 'pos' => '0',
750 'sql_query' => 'SELECT * FROM '
751 . PMA_backquote($map[$rel_field]['foreign_db']) . '.' . PMA_backquote($map[$rel_field]['foreign_table'])
752 . ' WHERE ' . PMA_backquote($map[$rel_field]['foreign_field'])
753 . $where_comparison
755 $output = '<a href="sql.php' . PMA_generate_common_url($_url_params) . '"' . $title . '>';
757 if ('D' == $_SESSION['tmp_user_values']['relational_display']) {
758 // user chose "relational display field" in the
759 // display options, so show display field in the cell
760 $output .= (!empty($dispval)) ? htmlspecialchars($dispval) : '';
761 } else {
762 // otherwise display data in the cell
763 $output .= htmlspecialchars($rel_field_value);
765 $output .= '</a>';
766 $extra_data['relations'][$rel_field] = $output;
770 if (isset($_REQUEST['do_transformations']) && $_REQUEST['do_transformations'] == true ) {
771 require_once './libraries/transformations.lib.php';
772 //if some posted fields need to be transformed, generate them here.
773 $mime_map = PMA_getMIME($db, $table);
775 if ($mime_map === false) {
776 $mime_map = array();
779 $edited_values = array();
780 parse_str($_REQUEST['transform_fields_list'], $edited_values);
782 foreach($mime_map as $transformation) {
783 $include_file = PMA_securePath($transformation['transformation']);
784 $column_name = $transformation['column_name'];
785 $column_data = $edited_values[$column_name];
787 $_url_params = array(
788 'db' => $db,
789 'table' => $table,
790 'where_clause' => $_REQUEST['where_clause'],
791 'transform_key' => $column_name,
794 if (file_exists('./libraries/transformations/' . $include_file)) {
795 $transformfunction_name = str_replace('.inc.php', '', $transformation['transformation']);
797 require_once './libraries/transformations/' . $include_file;
799 if (function_exists('PMA_transformation_' . $transformfunction_name)) {
800 $transform_function = 'PMA_transformation_' . $transformfunction_name;
801 $transform_options = PMA_transformation_getOptions((isset($transformation['transformation_options']) ? $transformation['transformation_options'] : ''));
802 $transform_options['wrapper_link'] = PMA_generate_common_url($_url_params);
806 $extra_data['transformations'][$column_name] = $transform_function($column_data, $transform_options);
810 if ($cfg['ShowSQL']) {
811 $extra_data['sql_query'] = PMA_showMessage($message, $GLOBALS['sql_query'], 'success');
813 if (isset($GLOBALS['reload']) && $GLOBALS['reload'] == 1) {
814 $extra_data['reload'] = 1;
815 $extra_data['db'] = $GLOBALS['db'];
817 PMA_ajaxResponse($message, $message->isSuccess(), (isset($extra_data) ? $extra_data : ''));
820 if ($is_gotofile) {
821 $goto = PMA_securePath($goto);
822 // Checks for a valid target script
823 $is_db = $is_table = false;
824 if (isset($_REQUEST['purge']) && $_REQUEST['purge'] == '1') {
825 $table = '';
826 unset($url_params['table']);
828 include 'libraries/db_table_exists.lib.php';
830 if (strpos($goto, 'tbl_') === 0 && ! $is_table) {
831 if (strlen($table)) {
832 $table = '';
834 $goto = 'db_sql.php';
836 if (strpos($goto, 'db_') === 0 && ! $is_db) {
837 if (strlen($db)) {
838 $db = '';
840 $goto = 'main.php';
842 // Loads to target script
843 if ($goto != 'main.php') {
844 require_once './libraries/header.inc.php';
846 $active_page = $goto;
847 require './' . $goto;
848 } else {
849 // avoid a redirect loop when last record was deleted
850 if (0 == $num_rows && 'sql.php' == $cfg['DefaultTabTable']) {
851 $goto = str_replace('sql.php','tbl_structure.php',$goto);
853 PMA_sendHeaderLocation($cfg['PmaAbsoluteUri'] . str_replace('&amp;', '&', $goto) . '&message=' . urlencode($message));
854 } // end else
855 exit();
856 } // end no rows returned
858 // At least one row is returned -> displays a table with results
859 else {
860 //If we are retrieving the full value of a truncated field or the original
861 // value of a transformed field, show it here and exit
862 if ($GLOBALS['inline_edit'] == true && $GLOBALS['cfg']['AjaxEnable']) {
863 $row = PMA_DBI_fetch_row($result);
864 $extra_data = array();
865 $extra_data['value'] = $row[0];
866 PMA_ajaxResponse(NULL, true, $extra_data);
869 // Displays the headers
870 if (isset($show_query)) {
871 unset($show_query);
873 if (isset($printview) && $printview == '1') {
874 require_once './libraries/header_printview.inc.php';
875 } else {
877 $GLOBALS['js_include'][] = 'functions.js';
878 $GLOBALS['js_include'][] = 'makegrid.js';
879 $GLOBALS['js_include'][] = 'sql.js';
881 unset($message);
883 if (! $GLOBALS['is_ajax_request'] || ! $GLOBALS['cfg']['AjaxEnable']) {
884 if (strlen($table)) {
885 require './libraries/tbl_common.php';
886 $url_query .= '&amp;goto=tbl_sql.php&amp;back=tbl_sql.php';
887 require './libraries/tbl_info.inc.php';
888 require './libraries/tbl_links.inc.php';
889 } elseif (strlen($db)) {
890 require './libraries/db_common.inc.php';
891 require './libraries/db_info.inc.php';
892 } else {
893 require './libraries/server_common.inc.php';
894 require './libraries/server_links.inc.php';
897 else {
898 require_once './libraries/header.inc.php';
899 //we don't need to buffer the output in PMA_showMessage here.
900 //set a global variable and check against it in the function
901 $GLOBALS['buffer_message'] = false;
905 if (strlen($db)) {
906 $cfgRelation = PMA_getRelationsParam();
909 // Gets the list of fields properties
910 if (isset($result) && $result) {
911 $fields_meta = PMA_DBI_get_fields_meta($result);
912 $fields_cnt = count($fields_meta);
915 if (! $GLOBALS['is_ajax_request']) {
916 //begin the sqlqueryresults div here. container div
917 echo '<div id="sqlqueryresults"';
918 if ($GLOBALS['cfg']['AjaxEnable']) {
919 echo ' class="ajax"';
921 echo '>';
924 // Display previous update query (from tbl_replace)
925 if (isset($disp_query) && $cfg['ShowSQL'] == true) {
926 PMA_showMessage($disp_message, $disp_query, 'success');
929 if (isset($profiling_results)) {
930 // pma_token/url_query needed for chart export
932 <script type="text/javascript">
933 pma_token = '<?php echo $_SESSION[' PMA_token ']; ?>';
934 url_query = '<?php echo isset($url_query)?$url_query:PMA_generate_common_url($db);?>';
935 $(document).ready(makeProfilingChart);
936 </script>
937 <?php
938 echo '<fieldset><legend>' . __('Profiling') . '</legend>' . "\n";
939 echo '<div style="float: left;">';
940 echo '<table>' . "\n";
941 echo ' <tr>' . "\n";
942 echo ' <th>' . __('Status') . PMA_showMySQLDocu('general-thread-states','general-thread-states') . '</th>' . "\n";
943 echo ' <th>' . __('Time') . '</th>' . "\n";
944 echo ' </tr>' . "\n";
946 $chart_json = Array();
947 foreach ($profiling_results as $one_result) {
948 echo ' <tr>' . "\n";
949 echo '<td>' . ucwords($one_result['Status']) . '</td>' . "\n";
950 echo '<td align="right">' . (PMA_formatNumber($one_result['Duration'],3,1)) . 's</td>' . "\n";
951 $chart_json[ucwords($one_result['Status'])] = $one_result['Duration'];
954 echo '</table>' . "\n";
955 echo '</div>';
956 //require_once './libraries/chart.lib.php';
957 echo '<div id="profilingchart" style="display:none;">';
958 //PMA_chart_profiling($profiling_results);
959 echo json_encode($chart_json);
960 echo '</div>';
961 echo '</fieldset>' . "\n";
964 // Displays the results in a table
965 if (empty($disp_mode)) {
966 // see the "PMA_setDisplayMode()" function in
967 // libraries/display_tbl.lib.php
968 $disp_mode = 'urdr111101';
971 // hide edit and delete links for information_schema
972 if (strtolower($db) == 'information_schema' || (PMA_DRIZZLE && strtolower($db) == 'data_dictionary')) {
973 $disp_mode = 'nnnn110111';
976 if (isset($label)) {
977 $message = PMA_message::success(__('Bookmark %s created'));
978 $message->addParam($label);
979 $message->display();
982 PMA_displayTable($result, $disp_mode, $analyzed_sql);
983 PMA_DBI_free_result($result);
985 // BEGIN INDEX CHECK See if indexes should be checked.
986 if (isset($query_type) && $query_type == 'check_tbl' && isset($selected) && is_array($selected)) {
987 foreach ($selected as $idx => $tbl_name) {
988 $check = PMA_Index::findDuplicates($tbl_name, $db);
989 if (! empty($check)) {
990 printf(__('Problems with indexes of table `%s`'), $tbl_name);
991 echo $check;
994 } // End INDEX CHECK
996 // Bookmark support if required
997 if ($disp_mode[7] == '1'
998 && (! empty($cfg['Bookmark']) && empty($id_bookmark))
999 && !empty($sql_query)) {
1000 echo "\n";
1002 $goto = 'sql.php?'
1003 . PMA_generate_common_url($db, $table)
1004 . '&amp;sql_query=' . urlencode($sql_query)
1005 . '&amp;id_bookmark=1';
1008 <form action="sql.php" method="post" onsubmit="return emptyFormElements(this, 'fields[label]');">
1009 <?php echo PMA_generate_common_hidden_inputs(); ?>
1010 <input type="hidden" name="goto" value="<?php echo $goto; ?>" />
1011 <input type="hidden" name="fields[dbase]" value="<?php echo htmlspecialchars($db); ?>" />
1012 <input type="hidden" name="fields[user]" value="<?php echo $cfg['Bookmark']['user']; ?>" />
1013 <input type="hidden" name="fields[query]" value="<?php echo urlencode(isset($complete_query) ? $complete_query : $sql_query); ?>" />
1014 <fieldset>
1015 <legend><?php
1016 echo ($cfg['PropertiesIconic'] ? '<img class="icon ic_b_bookmark" src="themes/dot.gif" alt="' . __('Bookmark this SQL query') . '" />' : '')
1017 . __('Bookmark this SQL query');
1019 </legend>
1021 <div class="formelement">
1022 <label for="fields_label_"><?php echo __('Label'); ?>:</label>
1023 <input type="text" id="fields_label_" name="fields[label]" value="" />
1024 </div>
1026 <div class="formelement">
1027 <input type="checkbox" name="bkm_all_users" id="bkm_all_users" value="true" />
1028 <label for="bkm_all_users"><?php echo __('Let every user access this bookmark'); ?></label>
1029 </div>
1031 <div class="clearfloat"></div>
1032 </fieldset>
1033 <fieldset class="tblFooters">
1034 <input type="submit" name="store_bkm" value="<?php echo __('Bookmark this SQL query'); ?>" />
1035 </fieldset>
1036 </form>
1037 <?php
1038 } // end bookmark support
1040 // Do print the page if required
1041 if (isset($printview) && $printview == '1') {
1043 <script type="text/javascript">
1044 //<![CDATA[
1045 // Do print the page
1046 window.onload = function()
1048 if (typeof(window.print) != 'undefined') {
1049 window.print();
1052 //]]>
1053 </script>
1054 <?php
1055 } // end print case
1057 if ($GLOBALS['is_ajax_request'] != true) {
1058 echo '</div>'; // end sqlqueryresults div
1060 } // end rows returned
1063 * Displays the footer
1065 if (! isset($_REQUEST['table_maintenance'])) {
1066 require './libraries/footer.inc.php';