Merge remote-tracking branch 'origin/master' into drizzle
[phpmyadmin.git] / sql.php
blobfb28f9cab07b25b69218ca6538dffca89260c01d
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_order']) && $_REQUEST['set_col_order'] == true) {
168 $pmatable = new PMA_Table($table, $db);
169 $col_order = explode(',', $_REQUEST['col_order']);
170 $retval = $pmatable->setUiProp(PMA_Table::PROP_COLUMN_ORDER, $col_order, $_REQUEST['table_create_time']);
171 PMA_ajaxResponse(NULL, ($retval == true));
174 // Default to browse if no query set and we have table
175 // (needed for browsing from DefaultTabTable)
176 if (empty($sql_query) && strlen($table) && strlen($db)) {
177 require_once './libraries/bookmark.lib.php';
178 $book_sql_query = PMA_Bookmark_get($db, '\'' . PMA_sqlAddSlashes($table) . '\'',
179 'label', false, true);
181 if (! empty($book_sql_query)) {
182 $GLOBALS['using_bookmark_message'] = PMA_message::notice(__('Using bookmark "%s" as default browse query.'));
183 $GLOBALS['using_bookmark_message']->addParam($table);
184 $GLOBALS['using_bookmark_message']->addMessage(PMA_showDocu('faq6_22'));
185 $sql_query = $book_sql_query;
186 } else {
187 $sql_query = 'SELECT * FROM ' . PMA_backquote($table);
189 unset($book_sql_query);
191 // set $goto to what will be displayed if query returns 0 rows
192 $goto = 'tbl_structure.php';
193 } else {
194 // Now we can check the parameters
195 PMA_checkParameters(array('sql_query'));
198 // instead of doing the test twice
199 $is_drop_database = preg_match('/DROP[[:space:]]+(DATABASE|SCHEMA)[[:space:]]+/i',
200 $sql_query);
203 * Check rights in case of DROP DATABASE
205 * This test may be bypassed if $is_js_confirmed = 1 (already checked with js)
206 * but since a malicious user may pass this variable by url/form, we don't take
207 * into account this case.
209 if (!defined('PMA_CHK_DROP')
210 && !$cfg['AllowUserDropDatabase']
211 && $is_drop_database
212 && !$is_superuser) {
213 require_once './libraries/header.inc.php';
214 PMA_mysqlDie(__('"DROP DATABASE" statements are disabled.'), '', '', $err_url);
215 } // end if
217 require_once './libraries/display_tbl.lib.php';
218 PMA_displayTable_checkConfigParams();
221 * Need to find the real end of rows?
223 if (isset($find_real_end) && $find_real_end) {
224 $unlim_num_rows = PMA_Table::countRecords($db, $table, $force_exact = true);
225 $_SESSION['tmp_user_values']['pos'] = @((ceil($unlim_num_rows / $_SESSION['tmp_user_values']['max_rows']) - 1) * $_SESSION['tmp_user_values']['max_rows']);
230 * Bookmark add
232 if (isset($store_bkm)) {
233 PMA_Bookmark_save($fields, (isset($bkm_all_users) && $bkm_all_users == 'true' ? true : false));
234 // go back to sql.php to redisplay query; do not use &amp; in this case:
235 PMA_sendHeaderLocation($cfg['PmaAbsoluteUri'] . $goto . '&label=' . $fields['label']);
236 } // end if
239 * Parse and analyze the query
241 require_once './libraries/parse_analyze.lib.php';
244 * Sets or modifies the $goto variable if required
246 if ($goto == 'sql.php') {
247 $is_gotofile = false;
248 $goto = 'sql.php?'
249 . PMA_generate_common_url($db, $table)
250 . '&amp;sql_query=' . urlencode($sql_query);
251 } // end if
255 * Go back to further page if table should not be dropped
257 if (isset($btnDrop) && $btnDrop == __('No')) {
258 if (!empty($back)) {
259 $goto = $back;
261 if ($is_gotofile) {
262 if (strpos($goto, 'db_') === 0 && strlen($table)) {
263 $table = '';
265 $active_page = $goto;
266 require './' . PMA_securePath($goto);
267 } else {
268 PMA_sendHeaderLocation($cfg['PmaAbsoluteUri'] . str_replace('&amp;', '&', $goto));
270 exit();
271 } // end if
275 * Displays the confirm page if required
277 * This part of the script is bypassed if $is_js_confirmed = 1 (already checked
278 * with js) because possible security issue is not so important here: at most,
279 * the confirm message isn't displayed.
281 * Also bypassed if only showing php code.or validating a SQL query
283 if (! $cfg['Confirm'] || isset($_REQUEST['is_js_confirmed']) || isset($btnDrop)
284 // if we are coming from a "Create PHP code" or a "Without PHP Code"
285 // dialog, we won't execute the query anyway, so don't confirm
286 || isset($GLOBALS['show_as_php'])
287 || !empty($GLOBALS['validatequery'])) {
288 $do_confirm = false;
289 } else {
290 $do_confirm = isset($analyzed_sql[0]['queryflags']['need_confirm']);
293 if ($do_confirm) {
294 $stripped_sql_query = $sql_query;
295 require_once './libraries/header.inc.php';
296 if ($is_drop_database) {
297 echo '<h1 class="error">' . __('You are about to DESTROY a complete database!') . '</h1>';
299 echo '<form action="sql.php" method="post">' . "\n"
300 .PMA_generate_common_hidden_inputs($db, $table);
302 <input type="hidden" name="sql_query" value="<?php echo htmlspecialchars($sql_query); ?>" />
303 <input type="hidden" name="message_to_show" value="<?php echo isset($message_to_show) ? PMA_sanitize($message_to_show, true) : ''; ?>" />
304 <input type="hidden" name="goto" value="<?php echo $goto; ?>" />
305 <input type="hidden" name="back" value="<?php echo isset($back) ? PMA_sanitize($back, true) : ''; ?>" />
306 <input type="hidden" name="reload" value="<?php echo isset($reload) ? PMA_sanitize($reload, true) : 0; ?>" />
307 <input type="hidden" name="purge" value="<?php echo isset($purge) ? PMA_sanitize($purge, true) : ''; ?>" />
308 <input type="hidden" name="dropped_column" value="<?php echo isset($dropped_column) ? PMA_sanitize($dropped_column, true) : ''; ?>" />
309 <input type="hidden" name="show_query" value="<?php echo isset($show_query) ? PMA_sanitize($show_query, true) : ''; ?>" />
310 <?php
311 echo '<fieldset class="confirmation">' . "\n"
312 .' <legend>' . __('Do you really want to ') . '</legend>'
313 .' <tt>' . htmlspecialchars($stripped_sql_query) . '</tt>' . "\n"
314 .'</fieldset>' . "\n"
315 .'<fieldset class="tblFooters">' . "\n";
317 <input type="submit" name="btnDrop" value="<?php echo __('Yes'); ?>" id="buttonYes" />
318 <input type="submit" name="btnDrop" value="<?php echo __('No'); ?>" id="buttonNo" />
319 <?php
320 echo '</fieldset>' . "\n"
321 . '</form>' . "\n";
324 * Displays the footer and exit
326 require './libraries/footer.inc.php';
327 } // end if $do_confirm
330 // Defines some variables
331 // A table has to be created, renamed, dropped -> navi frame should be reloaded
333 * @todo use the parser/analyzer
336 if (empty($reload)
337 && preg_match('/^(CREATE|ALTER|DROP)\s+(VIEW|TABLE|DATABASE|SCHEMA)\s+/i', $sql_query)) {
338 $reload = 1;
341 // SK -- Patch: $is_group added for use in calculation of total number of
342 // rows.
343 // $is_count is changed for more correct "LIMIT" clause
344 // appending in queries like
345 // "SELECT COUNT(...) FROM ... GROUP BY ..."
348 * @todo detect all this with the parser, to avoid problems finding
349 * those strings in comments or backquoted identifiers
352 $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;
353 if ($is_select) { // see line 141
354 $is_group = preg_match('@(GROUP[[:space:]]+BY|HAVING|SELECT[[:space:]]+DISTINCT)[[:space:]]+@i', $sql_query);
355 $is_func = !$is_group && (preg_match('@[[:space:]]+(SUM|AVG|STD|STDDEV|MIN|MAX|BIT_OR|BIT_AND)\s*\(@i', $sql_query));
356 $is_count = !$is_group && (preg_match('@^SELECT[[:space:]]+COUNT\((.*\.+)?.*\)@i', $sql_query));
357 $is_export = (preg_match('@[[:space:]]+INTO[[:space:]]+OUTFILE[[:space:]]+@i', $sql_query));
358 $is_analyse = (preg_match('@[[:space:]]+PROCEDURE[[:space:]]+ANALYSE@i', $sql_query));
359 } elseif (preg_match('@^EXPLAIN[[:space:]]+@i', $sql_query)) {
360 $is_explain = true;
361 } elseif (preg_match('@^DELETE[[:space:]]+@i', $sql_query)) {
362 $is_delete = true;
363 $is_affected = true;
364 } elseif (preg_match('@^(INSERT|LOAD[[:space:]]+DATA|REPLACE)[[:space:]]+@i', $sql_query)) {
365 $is_insert = true;
366 $is_affected = true;
367 if (preg_match('@^(REPLACE)[[:space:]]+@i', $sql_query)) {
368 $is_replace = true;
370 } elseif (preg_match('@^UPDATE[[:space:]]+@i', $sql_query)) {
371 $is_affected = true;
372 } elseif (preg_match('@^[[:space:]]*SHOW[[:space:]]+@i', $sql_query)) {
373 $is_show = true;
374 } elseif (preg_match('@^(CHECK|ANALYZE|REPAIR|OPTIMIZE)[[:space:]]+TABLE[[:space:]]+@i', $sql_query)) {
375 $is_maint = true;
378 // assign default full_sql_query
379 $full_sql_query = $sql_query;
381 // Handle remembered sorting order, only for single table query
382 if ($GLOBALS['cfg']['RememberSorting']
383 && ! ($is_count || $is_export || $is_func || $is_analyse)
384 && count($analyzed_sql[0]['select_expr']) == 0
385 && isset($analyzed_sql[0]['queryflags']['select_from'])
386 && count($analyzed_sql[0]['table_ref']) == 1
388 $pmatable = new PMA_Table($table, $db);
389 if (empty($analyzed_sql[0]['order_by_clause'])) {
390 $sorted_col = $pmatable->getUiProp(PMA_Table::PROP_SORTED_COLUMN);
391 if ($sorted_col) {
392 // retrieve the remembered sorting order for current table
393 $sql_order_to_append = ' ORDER BY ' . $sorted_col . ' ';
394 $full_sql_query = $analyzed_sql[0]['section_before_limit'] . $sql_order_to_append . $analyzed_sql[0]['section_after_limit'];
396 // update the $analyzed_sql
397 $analyzed_sql[0]['section_before_limit'] .= $sql_order_to_append;
398 $analyzed_sql[0]['order_by_clause'] = $sorted_col;
400 } else {
401 // store the remembered table into session
402 $pmatable->setUiProp(PMA_Table::PROP_SORTED_COLUMN, $analyzed_sql[0]['order_by_clause']);
406 // Do append a "LIMIT" clause?
407 if ((! $cfg['ShowAll'] || $_SESSION['tmp_user_values']['max_rows'] != 'all')
408 && ! ($is_count || $is_export || $is_func || $is_analyse)
409 && isset($analyzed_sql[0]['queryflags']['select_from'])
410 && ! isset($analyzed_sql[0]['queryflags']['offset'])
411 && empty($analyzed_sql[0]['limit_clause'])
413 $sql_limit_to_append = ' LIMIT ' . $_SESSION['tmp_user_values']['pos'] . ', ' . $_SESSION['tmp_user_values']['max_rows'] . " ";
415 $full_sql_query = $analyzed_sql[0]['section_before_limit'] . "\n" . $sql_limit_to_append . $analyzed_sql[0]['section_after_limit'];
417 * @todo pretty printing of this modified query
419 if (isset($display_query)) {
420 // if the analysis of the original query revealed that we found
421 // a section_after_limit, we now have to analyze $display_query
422 // to display it correctly
424 if (!empty($analyzed_sql[0]['section_after_limit']) && trim($analyzed_sql[0]['section_after_limit']) != ';') {
425 $analyzed_display_query = PMA_SQP_analyze(PMA_SQP_parse($display_query));
426 $display_query = $analyzed_display_query[0]['section_before_limit'] . "\n" . $sql_limit_to_append . $analyzed_display_query[0]['section_after_limit'];
432 if (strlen($db)) {
433 PMA_DBI_select_db($db);
436 // E x e c u t e t h e q u e r y
438 // Only if we didn't ask to see the php code (mikebeck)
439 if (isset($GLOBALS['show_as_php']) || !empty($GLOBALS['validatequery'])) {
440 unset($result);
441 $num_rows = 0;
442 } else {
443 if (isset($_SESSION['profiling']) && PMA_profilingSupported()) {
444 PMA_DBI_query('SET PROFILING=1;');
447 // Measure query time.
448 $querytime_before = array_sum(explode(' ', microtime()));
450 $result = @PMA_DBI_try_query($full_sql_query, null, PMA_DBI_QUERY_STORE);
452 // If a stored procedure was called, there may be more results that are
453 // queued up and waiting to be flushed from the buffer. So let's do that.
454 while (true) {
455 if(! PMA_DBI_more_results()) {
456 break;
458 PMA_DBI_next_result();
461 $querytime_after = array_sum(explode(' ', microtime()));
463 $GLOBALS['querytime'] = $querytime_after - $querytime_before;
465 // Displays an error message if required and stop parsing the script
466 if ($error = PMA_DBI_getError()) {
467 if ($is_gotofile) {
468 if (strpos($goto, 'db_') === 0 && strlen($table)) {
469 $table = '';
471 $active_page = $goto;
472 $message = PMA_Message::rawError($error);
474 if( $GLOBALS['is_ajax_request'] == true) {
475 PMA_ajaxResponse($message, false);
479 * Go to target path.
481 require './' . PMA_securePath($goto);
482 } else {
483 $full_err_url = (preg_match('@^(db|tbl)_@', $err_url))
484 ? $err_url . '&amp;show_query=1&amp;sql_query=' . urlencode($sql_query)
485 : $err_url;
486 PMA_mysqlDie($error, $full_sql_query, '', $full_err_url);
488 exit;
490 unset($error);
492 // Gets the number of rows affected/returned
493 // (This must be done immediately after the query because
494 // mysql_affected_rows() reports about the last query done)
496 if (!$is_affected) {
497 $num_rows = ($result) ? @PMA_DBI_num_rows($result) : 0;
498 } elseif (! isset($num_rows)) {
499 $num_rows = @PMA_DBI_affected_rows();
502 // Grabs the profiling results
503 if (isset($_SESSION['profiling']) && PMA_profilingSupported()) {
504 $profiling_results = PMA_DBI_fetch_result('SHOW PROFILE;');
507 // Checks if the current database has changed
508 // This could happen if the user sends a query like "USE `database`;"
510 * commented out auto-switching to active database - really required?
511 * bug #1814718 win: table list disappears (mixed case db names)
512 * https://sourceforge.net/support/tracker.php?aid=1814718
513 * @todo RELEASE test and comit or rollback before release
514 $current_db = PMA_DBI_fetch_value('SELECT DATABASE()');
515 if ($db !== $current_db) {
516 $db = $current_db;
517 $reload = 1;
519 unset($current_db);
522 // tmpfile remove after convert encoding appended by Y.Kawada
523 if (function_exists('PMA_kanji_file_conv')
524 && (isset($textfile) && file_exists($textfile))) {
525 unlink($textfile);
528 // Counts the total number of rows for the same 'SELECT' query without the
529 // 'LIMIT' clause that may have been programatically added
531 if (empty($sql_limit_to_append)) {
532 $unlim_num_rows = $num_rows;
533 // if we did not append a limit, set this to get a correct
534 // "Showing rows..." message
535 //$_SESSION['tmp_user_values']['max_rows'] = 'all';
536 } elseif ($is_select) {
538 // c o u n t q u e r y
540 // If we are "just browsing", there is only one table,
541 // and no WHERE clause (or just 'WHERE 1 '),
542 // we do a quick count (which uses MaxExactCount) because
543 // SQL_CALC_FOUND_ROWS is not quick on large InnoDB tables
545 // However, do not count again if we did it previously
546 // due to $find_real_end == true
548 if (!$is_group
549 && ! isset($analyzed_sql[0]['queryflags']['union'])
550 && ! isset($analyzed_sql[0]['table_ref'][1]['table_name'])
551 && (empty($analyzed_sql[0]['where_clause'])
552 || $analyzed_sql[0]['where_clause'] == '1 ')
553 && ! isset($find_real_end)
556 // "j u s t b r o w s i n g"
557 $unlim_num_rows = PMA_Table::countRecords($db, $table);
559 } else { // n o t " j u s t b r o w s i n g "
561 // add select expression after the SQL_CALC_FOUND_ROWS
563 // for UNION, just adding SQL_CALC_FOUND_ROWS
564 // after the first SELECT works.
566 // take the left part, could be:
567 // SELECT
568 // (SELECT
569 $count_query = PMA_SQP_formatHtml($parsed_sql, 'query_only', 0, $analyzed_sql[0]['position_of_first_select'] + 1);
570 $count_query .= ' SQL_CALC_FOUND_ROWS ';
571 // add everything that was after the first SELECT
572 $count_query .= PMA_SQP_formatHtml($parsed_sql, 'query_only', $analyzed_sql[0]['position_of_first_select']+1);
573 // ensure there is no semicolon at the end of the
574 // count query because we'll probably add
575 // a LIMIT 1 clause after it
576 $count_query = rtrim($count_query);
577 $count_query = rtrim($count_query, ';');
579 // if using SQL_CALC_FOUND_ROWS, add a LIMIT to avoid
580 // long delays. Returned count will be complete anyway.
581 // (but a LIMIT would disrupt results in an UNION)
583 if (! isset($analyzed_sql[0]['queryflags']['union'])) {
584 $count_query .= ' LIMIT 1';
587 // run the count query
589 PMA_DBI_try_query($count_query);
590 // if (mysql_error()) {
591 // void.
592 // I tried the case
593 // (SELECT `User`, `Host`, `Db`, `Select_priv` FROM `db`)
594 // UNION (SELECT `User`, `Host`, "%" AS "Db",
595 // `Select_priv`
596 // FROM `user`) ORDER BY `User`, `Host`, `Db`;
597 // and although the generated count_query is wrong
598 // the SELECT FOUND_ROWS() work! (maybe it gets the
599 // count from the latest query that worked)
601 // another case where the count_query is wrong:
602 // SELECT COUNT(*), f1 from t1 group by f1
603 // and you click to sort on count(*)
604 // }
605 $unlim_num_rows = PMA_DBI_fetch_value('SELECT FOUND_ROWS()');
606 } // end else "just browsing"
608 } else { // not $is_select
609 $unlim_num_rows = 0;
610 } // end rows total count
612 // if a table or database gets dropped, check column comments.
613 if (isset($purge) && $purge == '1') {
615 * Cleanup relations.
617 require_once './libraries/relation_cleanup.lib.php';
619 if (strlen($table) && strlen($db)) {
620 PMA_relationsCleanupTable($db, $table);
621 } elseif (strlen($db)) {
622 PMA_relationsCleanupDatabase($db);
623 } else {
624 // VOID. No DB/Table gets deleted.
625 } // end if relation-stuff
626 } // end if ($purge)
628 // If a column gets dropped, do relation magic.
629 if (isset($dropped_column) && strlen($db) && strlen($table) && !empty($dropped_column)) {
630 require_once './libraries/relation_cleanup.lib.php';
631 PMA_relationsCleanupColumn($db, $table, $dropped_column);
633 } // end if column was dropped
634 } // end else "didn't ask to see php code"
636 // No rows returned -> move back to the calling page
637 if (0 == $num_rows || $is_affected) {
638 if ($is_delete) {
639 $message = PMA_Message::deleted_rows($num_rows);
640 } elseif ($is_insert) {
641 if ($is_replace) {
642 /* For replace we get DELETED + INSERTED row count, so we have to call it affected */
643 $message = PMA_Message::affected_rows($num_rows);
644 } else {
645 $message = PMA_Message::inserted_rows($num_rows);
647 $insert_id = PMA_DBI_insert_id();
648 if ($insert_id != 0) {
649 // insert_id is id of FIRST record inserted in one insert, so if we inserted multiple rows, we had to increment this
650 $message->addMessage('[br]');
651 // need to use a temporary because the Message class
652 // currently supports adding parameters only to the first
653 // message
654 $_inserted = PMA_Message::notice(__('Inserted row id: %1$d'));
655 $_inserted->addParam($insert_id + $num_rows - 1);
656 $message->addMessage($_inserted);
658 } elseif ($is_affected) {
659 $message = PMA_Message::affected_rows($num_rows);
661 // Ok, here is an explanation for the !$is_select.
662 // The form generated by sql_query_form.lib.php
663 // and db_sql.php has many submit buttons
664 // on the same form, and some confusion arises from the
665 // fact that $message_to_show is sent for every case.
666 // The $message_to_show containing a success message and sent with
667 // the form should not have priority over errors
668 } elseif (!empty($message_to_show) && !$is_select) {
669 $message = PMA_Message::rawSuccess(htmlspecialchars($message_to_show));
670 } elseif (!empty($GLOBALS['show_as_php'])) {
671 $message = PMA_Message::success(__('Showing as PHP code'));
672 } elseif (isset($GLOBALS['show_as_php'])) {
673 /* User disable showing as PHP, query is only displayed */
674 $message = PMA_Message::notice(__('Showing SQL query'));
675 } elseif (!empty($GLOBALS['validatequery'])) {
676 $message = PMA_Message::notice(__('Validated SQL'));
677 } else {
678 $message = PMA_Message::success(__('MySQL returned an empty result set (i.e. zero rows).'));
681 if (isset($GLOBALS['querytime'])) {
682 $_querytime = PMA_Message::notice(__('Query took %01.4f sec'));
683 $_querytime->addParam($GLOBALS['querytime']);
684 $message->addMessage('(');
685 $message->addMessage($_querytime);
686 $message->addMessage(')');
689 if( $GLOBALS['is_ajax_request'] == true) {
692 * If we are in inline editing, we need to process the relational and
693 * transformed fields, if they were edited. After that, output the correct
694 * link/transformed value and exit
696 * Logic taken from libraries/display_tbl.lib.php
699 if(isset($_REQUEST['rel_fields_list']) && $_REQUEST['rel_fields_list'] != '') {
700 //handle relations work here for updated row.
701 require_once './libraries/relation.lib.php';
703 $map = PMA_getForeigners($db, $table, '', 'both');
705 $rel_fields = array();
706 parse_str($_REQUEST['rel_fields_list'], $rel_fields);
708 foreach( $rel_fields as $rel_field => $rel_field_value) {
710 $where_comparison = "='" . $rel_field_value . "'";
711 $display_field = PMA_getDisplayField($map[$rel_field]['foreign_db'], $map[$rel_field]['foreign_table']);
713 // Field to display from the foreign table?
714 if (isset($display_field) && strlen($display_field)) {
715 $dispsql = 'SELECT ' . PMA_backquote($display_field)
716 . ' FROM ' . PMA_backquote($map[$rel_field]['foreign_db'])
717 . '.' . PMA_backquote($map[$rel_field]['foreign_table'])
718 . ' WHERE ' . PMA_backquote($map[$rel_field]['foreign_field'])
719 . $where_comparison;
720 $dispresult = PMA_DBI_try_query($dispsql, null, PMA_DBI_QUERY_STORE);
721 if ($dispresult && PMA_DBI_num_rows($dispresult) > 0) {
722 list($dispval) = PMA_DBI_fetch_row($dispresult, 0);
723 } else {
724 //$dispval = __('Link not found');
726 @PMA_DBI_free_result($dispresult);
727 } else {
728 $dispval = '';
729 } // end if... else...
731 if ('K' == $_SESSION['tmp_user_values']['relational_display']) {
732 // user chose "relational key" in the display options, so
733 // the title contains the display field
734 $title = (! empty($dispval))? ' title="' . htmlspecialchars($dispval) . '"' : '';
735 } else {
736 $title = ' title="' . htmlspecialchars($rel_field_value) . '"';
739 $_url_params = array(
740 'db' => $map[$rel_field]['foreign_db'],
741 'table' => $map[$rel_field]['foreign_table'],
742 'pos' => '0',
743 'sql_query' => 'SELECT * FROM '
744 . PMA_backquote($map[$rel_field]['foreign_db']) . '.' . PMA_backquote($map[$rel_field]['foreign_table'])
745 . ' WHERE ' . PMA_backquote($map[$rel_field]['foreign_field'])
746 . $where_comparison
748 $output = '<a href="sql.php' . PMA_generate_common_url($_url_params) . '"' . $title . '>';
750 if ('D' == $_SESSION['tmp_user_values']['relational_display']) {
751 // user chose "relational display field" in the
752 // display options, so show display field in the cell
753 $output .= (!empty($dispval)) ? htmlspecialchars($dispval) : '';
754 } else {
755 // otherwise display data in the cell
756 $output .= htmlspecialchars($rel_field_value);
758 $output .= '</a>';
759 $extra_data['relations'][$rel_field] = $output;
763 if(isset($_REQUEST['do_transformations']) && $_REQUEST['do_transformations'] == true ) {
764 require_once './libraries/transformations.lib.php';
765 //if some posted fields need to be transformed, generate them here.
766 $mime_map = PMA_getMIME($db, $table);
768 if ($mime_map === false) {
769 $mime_map = array();
772 $edited_values = array();
773 parse_str($_REQUEST['transform_fields_list'], $edited_values);
775 foreach($mime_map as $transformation) {
776 $include_file = $transformation['transformation'];
777 $column_name = $transformation['column_name'];
778 $column_data = $edited_values[$column_name];
780 $_url_params = array(
781 'db' => $db,
782 'table' => $table,
783 'where_clause' => $_REQUEST['where_clause'],
784 'transform_key' => $column_name,
787 if (file_exists('./libraries/transformations/' . $include_file)) {
788 $transformfunction_name = str_replace('.inc.php', '', $transformation['transformation']);
790 require_once './libraries/transformations/' . $include_file;
792 if (function_exists('PMA_transformation_' . $transformfunction_name)) {
793 $transform_function = 'PMA_transformation_' . $transformfunction_name;
794 $transform_options = PMA_transformation_getOptions((isset($transformation['transformation_options']) ? $transformation['transformation_options'] : ''));
795 $transform_options['wrapper_link'] = PMA_generate_common_url($_url_params);
799 $extra_data['transformations'][$column_name] = $transform_function($column_data, $transform_options);
803 if ($cfg['ShowSQL']) {
804 $extra_data['sql_query'] = PMA_showMessage($message, $GLOBALS['sql_query'], 'success');
806 if (isset($GLOBALS['reload']) && $GLOBALS['reload'] == 1) {
807 $extra_data['reload'] = 1;
808 $extra_data['db'] = $GLOBALS['db'];
810 PMA_ajaxResponse($message, $message->isSuccess(), (isset($extra_data) ? $extra_data : ''));
813 if ($is_gotofile) {
814 $goto = PMA_securePath($goto);
815 // Checks for a valid target script
816 $is_db = $is_table = false;
817 if (isset($_REQUEST['purge'])) {
818 $table = '';
819 unset($url_params['table']);
821 include 'libraries/db_table_exists.lib.php';
823 if (strpos($goto, 'tbl_') === 0 && ! $is_table) {
824 if (strlen($table)) {
825 $table = '';
827 $goto = 'db_sql.php';
829 if (strpos($goto, 'db_') === 0 && ! $is_db) {
830 if (strlen($db)) {
831 $db = '';
833 $goto = 'main.php';
835 // Loads to target script
836 if ($goto != 'main.php') {
837 require_once './libraries/header.inc.php';
839 $active_page = $goto;
840 require './' . $goto;
841 } else {
842 // avoid a redirect loop when last record was deleted
843 if (0 == $num_rows && 'sql.php' == $cfg['DefaultTabTable']) {
844 $goto = str_replace('sql.php','tbl_structure.php',$goto);
846 PMA_sendHeaderLocation($cfg['PmaAbsoluteUri'] . str_replace('&amp;', '&', $goto) . '&message=' . urlencode($message));
847 } // end else
848 exit();
849 } // end no rows returned
851 // At least one row is returned -> displays a table with results
852 else {
853 //If we are retrieving the full value of a truncated field or the original
854 // value of a transformed field, show it here and exit
855 if( $GLOBALS['inline_edit'] == true && $GLOBALS['cfg']['AjaxEnable']) {
856 $row = PMA_DBI_fetch_row($result);
857 $extra_data = array();
858 $extra_data['value'] = $row[0];
859 PMA_ajaxResponse(NULL, true, $extra_data);
862 // Displays the headers
863 if (isset($show_query)) {
864 unset($show_query);
866 if (isset($printview) && $printview == '1') {
867 require_once './libraries/header_printview.inc.php';
868 } else {
870 $GLOBALS['js_include'][] = 'functions.js';
871 $GLOBALS['js_include'][] = 'makegrid.js';
872 $GLOBALS['js_include'][] = 'sql.js';
874 unset($message);
876 if( ! $GLOBALS['is_ajax_request'] || ! $GLOBALS['cfg']['AjaxEnable']) {
877 if (strlen($table)) {
878 require './libraries/tbl_common.php';
879 $url_query .= '&amp;goto=tbl_sql.php&amp;back=tbl_sql.php';
880 require './libraries/tbl_info.inc.php';
881 require './libraries/tbl_links.inc.php';
882 } elseif (strlen($db)) {
883 require './libraries/db_common.inc.php';
884 require './libraries/db_info.inc.php';
885 } else {
886 require './libraries/server_common.inc.php';
887 require './libraries/server_links.inc.php';
890 else {
891 require_once './libraries/header.inc.php';
892 //we don't need to buffer the output in PMA_showMessage here.
893 //set a global variable and check against it in the function
894 $GLOBALS['buffer_message'] = false;
898 if (strlen($db)) {
899 $cfgRelation = PMA_getRelationsParam();
902 // Gets the list of fields properties
903 if (isset($result) && $result) {
904 $fields_meta = PMA_DBI_get_fields_meta($result);
905 $fields_cnt = count($fields_meta);
908 if( ! $GLOBALS['is_ajax_request']) {
909 //begin the sqlqueryresults div here. container div
910 echo '<div id="sqlqueryresults"';
911 if ($GLOBALS['cfg']['AjaxEnable']) {
912 echo ' class="ajax"';
914 echo '>';
917 // Display previous update query (from tbl_replace)
918 if (isset($disp_query) && $cfg['ShowSQL'] == true) {
919 PMA_showMessage($disp_message, $disp_query, 'success');
922 if (isset($profiling_results)) {
923 // pma_token/url_query needed for chart export
925 <script type="text/javascript">
926 pma_token = '<?php echo $_SESSION[' PMA_token ']; ?>';
927 url_query = '<?php echo isset($url_query)?$url_query:PMA_generate_common_url($db);?>';
928 $(document).ready(createProfilingChart);
929 </script>
930 <?php
931 echo '<fieldset><legend>' . __('Profiling') . '</legend>' . "\n";
932 echo '<div style="float: left;">';
933 echo '<table>' . "\n";
934 echo ' <tr>' . "\n";
935 echo ' <th>' . __('Status') . '</th>' . "\n";
936 echo ' <th>' . __('Time') . '</th>' . "\n";
937 echo ' </tr>' . "\n";
939 $chart_json = Array();
940 foreach($profiling_results as $one_result) {
941 echo ' <tr>' . "\n";
942 echo '<td>' . ucwords($one_result['Status']) . '</td>' . "\n";
943 echo '<td align="right">' . (PMA_formatNumber($one_result['Duration'],3,1)) . 's</td>' . "\n";
944 $chart_json[ucwords($one_result['Status'])] = $one_result['Duration'];
947 echo '</table>' . "\n";
948 echo '</div>';
949 //require_once './libraries/chart.lib.php';
950 echo '<div id="profilingchart" style="display:none;">';
951 //PMA_chart_profiling($profiling_results);
952 echo json_encode($chart_json);
953 echo '</div>';
954 echo '</fieldset>' . "\n";
957 // Displays the results in a table
958 if (empty($disp_mode)) {
959 // see the "PMA_setDisplayMode()" function in
960 // libraries/display_tbl.lib.php
961 $disp_mode = 'urdr111101';
964 // hide edit and delete links for information_schema
965 if (strtolower($db) == 'information_schema' || (PMA_DRIZZLE && strtolower($db) == 'data_dictionary')) {
966 $disp_mode = 'nnnn110111';
969 if (isset($label)) {
970 $message = PMA_message::success(__('Bookmark %s created'));
971 $message->addParam($label);
972 $message->display();
975 PMA_displayTable($result, $disp_mode, $analyzed_sql);
976 PMA_DBI_free_result($result);
978 // BEGIN INDEX CHECK See if indexes should be checked.
979 if (isset($query_type) && $query_type == 'check_tbl' && isset($selected) && is_array($selected)) {
980 foreach ($selected as $idx => $tbl_name) {
981 $check = PMA_Index::findDuplicates($tbl_name, $db);
982 if (! empty($check)) {
983 printf(__('Problems with indexes of table `%s`'), $tbl_name);
984 echo $check;
987 } // End INDEX CHECK
989 // Bookmark support if required
990 if ($disp_mode[7] == '1'
991 && (! empty($cfg['Bookmark']) && empty($id_bookmark))
992 && !empty($sql_query)) {
993 echo "\n";
995 $goto = 'sql.php?'
996 . PMA_generate_common_url($db, $table)
997 . '&amp;sql_query=' . urlencode($sql_query)
998 . '&amp;id_bookmark=1';
1001 <form action="sql.php" method="post" onsubmit="return emptyFormElements(this, 'fields[label]');">
1002 <?php echo PMA_generate_common_hidden_inputs(); ?>
1003 <input type="hidden" name="goto" value="<?php echo $goto; ?>" />
1004 <input type="hidden" name="fields[dbase]" value="<?php echo htmlspecialchars($db); ?>" />
1005 <input type="hidden" name="fields[user]" value="<?php echo $cfg['Bookmark']['user']; ?>" />
1006 <input type="hidden" name="fields[query]" value="<?php echo urlencode(isset($complete_query) ? $complete_query : $sql_query); ?>" />
1007 <fieldset>
1008 <legend><?php
1009 echo ($cfg['PropertiesIconic'] ? '<img class="icon" src="' . $pmaThemeImage . 'b_bookmark.png" width="16" height="16" alt="' . __('Bookmark this SQL query') . '" />' : '')
1010 . __('Bookmark this SQL query');
1012 </legend>
1014 <div class="formelement">
1015 <label for="fields_label_"><?php echo __('Label'); ?>:</label>
1016 <input type="text" id="fields_label_" name="fields[label]" value="" />
1017 </div>
1019 <div class="formelement">
1020 <input type="checkbox" name="bkm_all_users" id="bkm_all_users" value="true" />
1021 <label for="bkm_all_users"><?php echo __('Let every user access this bookmark'); ?></label>
1022 </div>
1024 <div class="clearfloat"></div>
1025 </fieldset>
1026 <fieldset class="tblFooters">
1027 <input type="submit" name="store_bkm" value="<?php echo __('Bookmark this SQL query'); ?>" />
1028 </fieldset>
1029 </form>
1030 <?php
1031 } // end bookmark support
1033 // Do print the page if required
1034 if (isset($printview) && $printview == '1') {
1036 <script type="text/javascript">
1037 //<![CDATA[
1038 // Do print the page
1039 window.onload = function()
1041 if (typeof(window.print) != 'undefined') {
1042 window.print();
1045 //]]>
1046 </script>
1047 <?php
1048 } // end print case
1050 if( $GLOBALS['is_ajax_request'] != true) {
1051 echo '</div>'; // end sqlqueryresults div
1053 } // end rows returned
1056 * Displays the footer
1058 if(! isset($_REQUEST['table_maintenance'])) {
1059 require './libraries/footer.inc.php';