Add missing 'server' argument to PMA_reloadRecentTable
[phpmyadmin.git] / sql.php
blob61a4668ec6cc3acd502110c947eb446deeb123e9
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'][] = 'pMap.js';
20 /**
21 * Defines the url to return to in case of error in a sql statement
23 // Security checkings
24 if (! empty($goto)) {
25 $is_gotofile = preg_replace('@^([^?]+).*$@s', '\\1', $goto);
26 if (! @file_exists('./' . $is_gotofile)) {
27 unset($goto);
28 } else {
29 $is_gotofile = ($is_gotofile == $goto);
31 } else {
32 $goto = (! strlen($table)) ? $cfg['DefaultTabDatabase'] : $cfg['DefaultTabTable'];
33 $is_gotofile = true;
34 } // end if
36 if (! isset($err_url)) {
37 $err_url = (!empty($back) ? $back : $goto)
38 . '?' . PMA_generate_common_url($db)
39 . ((strpos(' ' . $goto, 'db_') != 1 && strlen($table)) ? '&amp;table=' . urlencode($table) : '');
40 } // end if
42 // Coming from a bookmark dialog
43 if (isset($fields['query'])) {
44 $sql_query = $fields['query'];
47 // This one is just to fill $db
48 if (isset($fields['dbase'])) {
49 $db = $fields['dbase'];
52 /**
53 * During inline edit, if we have a relational field, show the dropdown for it
55 * Logic taken from libraries/display_tbl_lib.php
57 * This doesn't seem to be the right place to do this, but I can't think of any
58 * better place either.
60 if (isset($_REQUEST['get_relational_values']) && $_REQUEST['get_relational_values'] == true) {
61 require_once 'libraries/relation.lib.php';
63 $column = $_REQUEST['column'];
64 $foreigners = PMA_getForeigners($db, $table, $column);
66 $display_field = PMA_getDisplayField($foreigners[$column]['foreign_db'], $foreigners[$column]['foreign_table']);
68 $foreignData = PMA_getForeignData($foreigners, $column, false, '', '');
70 if ($_SESSION['tmp_user_values']['relational_display'] == 'D'
71 && (isset($display_field) && strlen($display_field)
72 && (isset($_REQUEST['relation_key_or_display_column']) && $_REQUEST['relation_key_or_display_column']))) {
73 $curr_value = $_REQUEST['relation_key_or_display_column'];
74 } else {
75 $curr_value = $_REQUEST['curr_value'];
77 if ($foreignData['disp_row'] == null) {
78 //Handle the case when number of values is more than $cfg['ForeignKeyMaxLimit']
79 $_url_params = array(
80 'db' => $db,
81 'table' => $table,
82 'field' => $column
85 $dropdown = '<span class="curr_value">' . htmlspecialchars($_REQUEST['curr_value']) . '</span> <a href="browse_foreigners.php' . PMA_generate_common_url($_url_params) . '"'
86 . ' target="_blank" class="browse_foreign" '
87 .'>' . __('Browse foreign values') . '</a>';
89 else {
90 $dropdown = PMA_foreignDropdown($foreignData['disp_row'], $foreignData['foreign_field'], $foreignData['foreign_display'], $curr_value, $cfg['ForeignKeyMaxLimit']);
91 $dropdown = '<select>' . $dropdown . '</select>';
94 $extra_data['dropdown'] = $dropdown;
95 PMA_ajaxResponse(NULL, true, $extra_data);
98 /**
99 * Just like above, find possible values for enum fields during inline edit.
101 * Logic taken from libraries/display_tbl_lib.php
103 if(isset($_REQUEST['get_enum_values']) && $_REQUEST['get_enum_values'] == true) {
104 $field_info_query = 'SHOW FIELDS FROM `' . $db . '`.`' . $table . '` LIKE \'' . $_REQUEST['column'] . '\' ;';
106 $field_info_result = PMA_DBI_fetch_result($field_info_query, null, null, null, PMA_DBI_QUERY_STORE);
108 $search = array('enum', '(', ')', "'");
110 $values = explode(',', str_replace($search, '', $field_info_result[0]['Type']));
112 $dropdown = '<option value="">&nbsp;</option>';
113 foreach($values as $value) {
114 $dropdown .= '<option value="' . htmlspecialchars($value) . '"';
115 if($value == $_REQUEST['curr_value']) {
116 $dropdown .= ' selected="selected"';
118 $dropdown .= '>' . $value . '</option>';
121 $dropdown = '<select>' . $dropdown . '</select>';
123 $extra_data['dropdown'] = $dropdown;
124 PMA_ajaxResponse(NULL, true, $extra_data);
128 * Find possible values for set fields during inline edit.
130 if(isset($_REQUEST['get_set_values']) && $_REQUEST['get_set_values'] == true) {
131 $field_info_query = 'SHOW FIELDS FROM `' . $db . '`.`' . $table . '` LIKE \'' . $_REQUEST['column'] . '\' ;';
133 $field_info_result = PMA_DBI_fetch_result($field_info_query, null, null, null, PMA_DBI_QUERY_STORE);
135 $selected_values = explode(',', $_REQUEST['curr_value']);
137 $search = array('set', '(', ')', "'");
138 $values = explode(',', str_replace($search, '', $field_info_result[0]['Type']));
140 $select = '';
141 foreach($values as $value) {
142 $select .= '<option value="' . htmlspecialchars($value) . '"';
143 if(in_array($value, $selected_values, true)) {
144 $select .= ' selected="selected"';
146 $select .= '>' . $value . '</option>';
149 $select_size = (sizeof($values) > 10) ? 10 : sizeof($values);
150 $select = '<select multiple="multiple" size="' . $select_size . '">' . $select . '</select>';
152 $extra_data['select'] = $select;
153 PMA_ajaxResponse(NULL, true, $extra_data);
155 // Default to browse if no query set and we have table
156 // (needed for browsing from DefaultTabTable)
157 if (empty($sql_query) && strlen($table) && strlen($db)) {
158 require_once './libraries/bookmark.lib.php';
159 $book_sql_query = PMA_Bookmark_get($db, '\'' . PMA_sqlAddslashes($table) . '\'',
160 'label', false, true);
162 if (! empty($book_sql_query)) {
163 $GLOBALS['using_bookmark_message'] = PMA_message::notice(__('Using bookmark "%s" as default browse query.'));
164 $GLOBALS['using_bookmark_message']->addParam($table);
165 $GLOBALS['using_bookmark_message']->addMessage(PMA_showDocu('faq6_22'));
166 $sql_query = $book_sql_query;
167 } else {
168 $sql_query = 'SELECT * FROM ' . PMA_backquote($table);
170 unset($book_sql_query);
172 // set $goto to what will be displayed if query returns 0 rows
173 $goto = 'tbl_structure.php';
174 } else {
175 // Now we can check the parameters
176 PMA_checkParameters(array('sql_query'));
179 // instead of doing the test twice
180 $is_drop_database = preg_match('/DROP[[:space:]]+(DATABASE|SCHEMA)[[:space:]]+/i',
181 $sql_query);
184 * Check rights in case of DROP DATABASE
186 * This test may be bypassed if $is_js_confirmed = 1 (already checked with js)
187 * but since a malicious user may pass this variable by url/form, we don't take
188 * into account this case.
190 if (!defined('PMA_CHK_DROP')
191 && !$cfg['AllowUserDropDatabase']
192 && $is_drop_database
193 && !$is_superuser) {
194 require_once './libraries/header.inc.php';
195 PMA_mysqlDie(__('"DROP DATABASE" statements are disabled.'), '', '', $err_url);
196 } // end if
198 require_once './libraries/display_tbl.lib.php';
199 PMA_displayTable_checkConfigParams();
202 * Need to find the real end of rows?
204 if (isset($find_real_end) && $find_real_end) {
205 $unlim_num_rows = PMA_Table::countRecords($db, $table, $force_exact = true);
206 $_SESSION['tmp_user_values']['pos'] = @((ceil($unlim_num_rows / $_SESSION['tmp_user_values']['max_rows']) - 1) * $_SESSION['tmp_user_values']['max_rows']);
211 * Bookmark add
213 if (isset($store_bkm)) {
214 PMA_Bookmark_save($fields, (isset($bkm_all_users) && $bkm_all_users == 'true' ? true : false));
215 // go back to sql.php to redisplay query; do not use &amp; in this case:
216 PMA_sendHeaderLocation($cfg['PmaAbsoluteUri'] . $goto . '&label=' . $fields['label']);
217 } // end if
220 * Parse and analyze the query
222 require_once './libraries/parse_analyze.lib.php';
225 * Sets or modifies the $goto variable if required
227 if ($goto == 'sql.php') {
228 $is_gotofile = false;
229 $goto = 'sql.php?'
230 . PMA_generate_common_url($db, $table)
231 . '&amp;sql_query=' . urlencode($sql_query);
232 } // end if
236 * Go back to further page if table should not be dropped
238 if (isset($btnDrop) && $btnDrop == __('No')) {
239 if (!empty($back)) {
240 $goto = $back;
242 if ($is_gotofile) {
243 if (strpos($goto, 'db_') === 0 && strlen($table)) {
244 $table = '';
246 $active_page = $goto;
247 require './' . PMA_securePath($goto);
248 } else {
249 PMA_sendHeaderLocation($cfg['PmaAbsoluteUri'] . str_replace('&amp;', '&', $goto));
251 exit();
252 } // end if
256 * Displays the confirm page if required
258 * This part of the script is bypassed if $is_js_confirmed = 1 (already checked
259 * with js) because possible security issue is not so important here: at most,
260 * the confirm message isn't displayed.
262 * Also bypassed if only showing php code.or validating a SQL query
264 if (! $cfg['Confirm'] || isset($_REQUEST['is_js_confirmed']) || isset($btnDrop)
265 // if we are coming from a "Create PHP code" or a "Without PHP Code"
266 // dialog, we won't execute the query anyway, so don't confirm
267 || isset($GLOBALS['show_as_php'])
268 || !empty($GLOBALS['validatequery'])) {
269 $do_confirm = false;
270 } else {
271 $do_confirm = isset($analyzed_sql[0]['queryflags']['need_confirm']);
274 if ($do_confirm) {
275 $stripped_sql_query = $sql_query;
276 require_once './libraries/header.inc.php';
277 if ($is_drop_database) {
278 echo '<h1 class="error">' . __('You are about to DESTROY a complete database!') . '</h1>';
280 echo '<form action="sql.php" method="post">' . "\n"
281 .PMA_generate_common_hidden_inputs($db, $table);
283 <input type="hidden" name="sql_query" value="<?php echo htmlspecialchars($sql_query); ?>" />
284 <input type="hidden" name="message_to_show" value="<?php echo isset($message_to_show) ? PMA_sanitize($message_to_show, true) : ''; ?>" />
285 <input type="hidden" name="goto" value="<?php echo $goto; ?>" />
286 <input type="hidden" name="back" value="<?php echo isset($back) ? PMA_sanitize($back, true) : ''; ?>" />
287 <input type="hidden" name="reload" value="<?php echo isset($reload) ? PMA_sanitize($reload, true) : 0; ?>" />
288 <input type="hidden" name="purge" value="<?php echo isset($purge) ? PMA_sanitize($purge, true) : ''; ?>" />
289 <input type="hidden" name="dropped_column" value="<?php echo isset($dropped_column) ? PMA_sanitize($dropped_column, true) : ''; ?>" />
290 <input type="hidden" name="show_query" value="<?php echo isset($show_query) ? PMA_sanitize($show_query, true) : ''; ?>" />
291 <?php
292 echo '<fieldset class="confirmation">' . "\n"
293 .' <legend>' . __('Do you really want to ') . '</legend>'
294 .' <tt>' . htmlspecialchars($stripped_sql_query) . '</tt>' . "\n"
295 .'</fieldset>' . "\n"
296 .'<fieldset class="tblFooters">' . "\n";
298 <input type="submit" name="btnDrop" value="<?php echo __('Yes'); ?>" id="buttonYes" />
299 <input type="submit" name="btnDrop" value="<?php echo __('No'); ?>" id="buttonNo" />
300 <?php
301 echo '</fieldset>' . "\n"
302 . '</form>' . "\n";
305 * Displays the footer and exit
307 require './libraries/footer.inc.php';
308 } // end if $do_confirm
311 // Defines some variables
312 // A table has to be created, renamed, dropped -> navi frame should be reloaded
314 * @todo use the parser/analyzer
317 if (empty($reload)
318 && preg_match('/^(CREATE|ALTER|DROP)\s+(VIEW|TABLE|DATABASE|SCHEMA)\s+/i', $sql_query)) {
319 $reload = 1;
322 // SK -- Patch: $is_group added for use in calculation of total number of
323 // rows.
324 // $is_count is changed for more correct "LIMIT" clause
325 // appending in queries like
326 // "SELECT COUNT(...) FROM ... GROUP BY ..."
329 * @todo detect all this with the parser, to avoid problems finding
330 * those strings in comments or backquoted identifiers
333 $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;
334 if ($is_select) { // see line 141
335 $is_group = preg_match('@(GROUP[[:space:]]+BY|HAVING|SELECT[[:space:]]+DISTINCT)[[:space:]]+@i', $sql_query);
336 $is_func = !$is_group && (preg_match('@[[:space:]]+(SUM|AVG|STD|STDDEV|MIN|MAX|BIT_OR|BIT_AND)\s*\(@i', $sql_query));
337 $is_count = !$is_group && (preg_match('@^SELECT[[:space:]]+COUNT\((.*\.+)?.*\)@i', $sql_query));
338 $is_export = (preg_match('@[[:space:]]+INTO[[:space:]]+OUTFILE[[:space:]]+@i', $sql_query));
339 $is_analyse = (preg_match('@[[:space:]]+PROCEDURE[[:space:]]+ANALYSE@i', $sql_query));
340 } elseif (preg_match('@^EXPLAIN[[:space:]]+@i', $sql_query)) {
341 $is_explain = true;
342 } elseif (preg_match('@^DELETE[[:space:]]+@i', $sql_query)) {
343 $is_delete = true;
344 $is_affected = true;
345 } elseif (preg_match('@^(INSERT|LOAD[[:space:]]+DATA|REPLACE)[[:space:]]+@i', $sql_query)) {
346 $is_insert = true;
347 $is_affected = true;
348 if (preg_match('@^(REPLACE)[[:space:]]+@i', $sql_query)) {
349 $is_replace = true;
351 } elseif (preg_match('@^UPDATE[[:space:]]+@i', $sql_query)) {
352 $is_affected = true;
353 } elseif (preg_match('@^[[:space:]]*SHOW[[:space:]]+@i', $sql_query)) {
354 $is_show = true;
355 } elseif (preg_match('@^(CHECK|ANALYZE|REPAIR|OPTIMIZE)[[:space:]]+TABLE[[:space:]]+@i', $sql_query)) {
356 $is_maint = true;
359 // Handle remembered sorting order, only for single table query
360 if ($GLOBALS['cfg']['RememberSorting']
361 && basename($GLOBALS['PMA_PHP_SELF']) == 'sql.php'
362 && ! ($is_count || $is_export || $is_func || $is_analyse)
363 && isset($analyzed_sql[0]['queryflags']['select_from'])
364 && count($analyzed_sql[0]['table_ref']) == 1
366 $pmatable = new PMA_Table($table, $db);
367 if (empty($analyzed_sql[0]['order_by_clause'])) {
368 $sorted_col = $pmatable->getUiProp(PMA_Table::PROP_SORTED_COLUMN);
369 if ($sorted_col) {
370 // retrieve the remembered sorting order for current table
371 $sql_order_to_append = ' ORDER BY ' . $sorted_col . ' ';
372 $sql_query = $analyzed_sql[0]['section_before_limit'] . $sql_order_to_append . $analyzed_sql[0]['section_after_limit'];
374 // update the $analyzed_sql
375 $analyzed_sql[0]['section_before_limit'] .= $sql_order_to_append;
376 $analyzed_sql[0]['order_by_clause'] = $sorted_col;
378 } else {
379 // store the remembered table into session
380 $pmatable->setUiProp(PMA_Table::PROP_SORTED_COLUMN, $analyzed_sql[0]['order_by_clause']);
384 // Do append a "LIMIT" clause?
385 if ((! $cfg['ShowAll'] || $_SESSION['tmp_user_values']['max_rows'] != 'all')
386 && ! ($is_count || $is_export || $is_func || $is_analyse)
387 && isset($analyzed_sql[0]['queryflags']['select_from'])
388 && ! isset($analyzed_sql[0]['queryflags']['offset'])
389 && empty($analyzed_sql[0]['limit_clause'])
391 $sql_limit_to_append = ' LIMIT ' . $_SESSION['tmp_user_values']['pos'] . ', ' . $_SESSION['tmp_user_values']['max_rows'] . " ";
393 $full_sql_query = $analyzed_sql[0]['section_before_limit'] . "\n" . $sql_limit_to_append . $analyzed_sql[0]['section_after_limit'];
395 * @todo pretty printing of this modified query
397 if (isset($display_query)) {
398 // if the analysis of the original query revealed that we found
399 // a section_after_limit, we now have to analyze $display_query
400 // to display it correctly
402 if (!empty($analyzed_sql[0]['section_after_limit']) && trim($analyzed_sql[0]['section_after_limit']) != ';') {
403 $analyzed_display_query = PMA_SQP_analyze(PMA_SQP_parse($display_query));
404 $display_query = $analyzed_display_query[0]['section_before_limit'] . "\n" . $sql_limit_to_append . $analyzed_display_query[0]['section_after_limit'];
408 } else {
409 $full_sql_query = $sql_query;
410 } // end if...else
412 if (strlen($db)) {
413 PMA_DBI_select_db($db);
416 // E x e c u t e t h e q u e r y
418 // Only if we didn't ask to see the php code (mikebeck)
419 if (isset($GLOBALS['show_as_php']) || !empty($GLOBALS['validatequery'])) {
420 unset($result);
421 $num_rows = 0;
422 } else {
423 if (isset($_SESSION['profiling']) && PMA_profilingSupported()) {
424 PMA_DBI_query('SET PROFILING=1;');
427 // Measure query time.
428 $querytime_before = array_sum(explode(' ', microtime()));
430 $result = @PMA_DBI_try_query($full_sql_query, null, PMA_DBI_QUERY_STORE);
432 $querytime_after = array_sum(explode(' ', microtime()));
434 $GLOBALS['querytime'] = $querytime_after - $querytime_before;
436 // Displays an error message if required and stop parsing the script
437 if ($error = PMA_DBI_getError()) {
438 if ($is_gotofile) {
439 if (strpos($goto, 'db_') === 0 && strlen($table)) {
440 $table = '';
442 $active_page = $goto;
443 $message = PMA_Message::rawError($error);
445 if( $GLOBALS['is_ajax_request'] == true) {
446 PMA_ajaxResponse($message, false);
450 * Go to target path.
452 require './' . PMA_securePath($goto);
453 } else {
454 $full_err_url = (preg_match('@^(db|tbl)_@', $err_url))
455 ? $err_url . '&amp;show_query=1&amp;sql_query=' . urlencode($sql_query)
456 : $err_url;
457 PMA_mysqlDie($error, $full_sql_query, '', $full_err_url);
459 exit;
461 unset($error);
463 // Gets the number of rows affected/returned
464 // (This must be done immediately after the query because
465 // mysql_affected_rows() reports about the last query done)
467 if (!$is_affected) {
468 $num_rows = ($result) ? @PMA_DBI_num_rows($result) : 0;
469 } elseif (! isset($num_rows)) {
470 $num_rows = @PMA_DBI_affected_rows();
473 // Grabs the profiling results
474 if (isset($_SESSION['profiling']) && PMA_profilingSupported()) {
475 $profiling_results = PMA_DBI_fetch_result('SHOW PROFILE;');
478 // Checks if the current database has changed
479 // This could happen if the user sends a query like "USE `database`;"
481 * commented out auto-switching to active database - really required?
482 * bug #1814718 win: table list disappears (mixed case db names)
483 * https://sourceforge.net/support/tracker.php?aid=1814718
484 * @todo RELEASE test and comit or rollback before release
485 $current_db = PMA_DBI_fetch_value('SELECT DATABASE()');
486 if ($db !== $current_db) {
487 $db = $current_db;
488 $reload = 1;
490 unset($current_db);
493 // tmpfile remove after convert encoding appended by Y.Kawada
494 if (function_exists('PMA_kanji_file_conv')
495 && (isset($textfile) && file_exists($textfile))) {
496 unlink($textfile);
499 // Counts the total number of rows for the same 'SELECT' query without the
500 // 'LIMIT' clause that may have been programatically added
502 if (empty($sql_limit_to_append)) {
503 $unlim_num_rows = $num_rows;
504 // if we did not append a limit, set this to get a correct
505 // "Showing rows..." message
506 //$_SESSION['tmp_user_values']['max_rows'] = 'all';
507 } elseif ($is_select) {
509 // c o u n t q u e r y
511 // If we are "just browsing", there is only one table,
512 // and no WHERE clause (or just 'WHERE 1 '),
513 // we do a quick count (which uses MaxExactCount) because
514 // SQL_CALC_FOUND_ROWS is not quick on large InnoDB tables
516 // However, do not count again if we did it previously
517 // due to $find_real_end == true
519 if (!$is_group
520 && ! isset($analyzed_sql[0]['queryflags']['union'])
521 && ! isset($analyzed_sql[0]['table_ref'][1]['table_name'])
522 && (empty($analyzed_sql[0]['where_clause'])
523 || $analyzed_sql[0]['where_clause'] == '1 ')
524 && ! isset($find_real_end)
527 // "j u s t b r o w s i n g"
528 $unlim_num_rows = PMA_Table::countRecords($db, $table);
530 } else { // n o t " j u s t b r o w s i n g "
532 // add select expression after the SQL_CALC_FOUND_ROWS
534 // for UNION, just adding SQL_CALC_FOUND_ROWS
535 // after the first SELECT works.
537 // take the left part, could be:
538 // SELECT
539 // (SELECT
540 $count_query = PMA_SQP_formatHtml($parsed_sql, 'query_only', 0, $analyzed_sql[0]['position_of_first_select'] + 1);
541 $count_query .= ' SQL_CALC_FOUND_ROWS ';
542 // add everything that was after the first SELECT
543 $count_query .= PMA_SQP_formatHtml($parsed_sql, 'query_only', $analyzed_sql[0]['position_of_first_select']+1);
544 // ensure there is no semicolon at the end of the
545 // count query because we'll probably add
546 // a LIMIT 1 clause after it
547 $count_query = rtrim($count_query);
548 $count_query = rtrim($count_query, ';');
550 // if using SQL_CALC_FOUND_ROWS, add a LIMIT to avoid
551 // long delays. Returned count will be complete anyway.
552 // (but a LIMIT would disrupt results in an UNION)
554 if (! isset($analyzed_sql[0]['queryflags']['union'])) {
555 $count_query .= ' LIMIT 1';
558 // run the count query
560 PMA_DBI_try_query($count_query);
561 // if (mysql_error()) {
562 // void.
563 // I tried the case
564 // (SELECT `User`, `Host`, `Db`, `Select_priv` FROM `db`)
565 // UNION (SELECT `User`, `Host`, "%" AS "Db",
566 // `Select_priv`
567 // FROM `user`) ORDER BY `User`, `Host`, `Db`;
568 // and although the generated count_query is wrong
569 // the SELECT FOUND_ROWS() work! (maybe it gets the
570 // count from the latest query that worked)
572 // another case where the count_query is wrong:
573 // SELECT COUNT(*), f1 from t1 group by f1
574 // and you click to sort on count(*)
575 // }
576 $unlim_num_rows = PMA_DBI_fetch_value('SELECT FOUND_ROWS()');
577 } // end else "just browsing"
579 } else { // not $is_select
580 $unlim_num_rows = 0;
581 } // end rows total count
583 // if a table or database gets dropped, check column comments.
584 if (isset($purge) && $purge == '1') {
586 * Cleanup relations.
588 require_once './libraries/relation_cleanup.lib.php';
590 if (strlen($table) && strlen($db)) {
591 PMA_relationsCleanupTable($db, $table);
592 } elseif (strlen($db)) {
593 PMA_relationsCleanupDatabase($db);
594 } else {
595 // VOID. No DB/Table gets deleted.
596 } // end if relation-stuff
597 } // end if ($purge)
599 // If a column gets dropped, do relation magic.
600 if (isset($dropped_column) && strlen($db) && strlen($table) && !empty($dropped_column)) {
601 require_once './libraries/relation_cleanup.lib.php';
602 PMA_relationsCleanupColumn($db, $table, $dropped_column);
604 } // end if column was dropped
605 } // end else "didn't ask to see php code"
607 // No rows returned -> move back to the calling page
608 if (0 == $num_rows || $is_affected) {
609 if ($is_delete) {
610 $message = PMA_Message::deleted_rows($num_rows);
611 } elseif ($is_insert) {
612 if ($is_replace) {
613 /* For replace we get DELETED + INSERTED row count, so we have to call it affected */
614 $message = PMA_Message::affected_rows($num_rows);
615 } else {
616 $message = PMA_Message::inserted_rows($num_rows);
618 $insert_id = PMA_DBI_insert_id();
619 if ($insert_id != 0) {
620 // insert_id is id of FIRST record inserted in one insert, so if we inserted multiple rows, we had to increment this
621 $message->addMessage('[br]');
622 // need to use a temporary because the Message class
623 // currently supports adding parameters only to the first
624 // message
625 $_inserted = PMA_Message::notice(__('Inserted row id: %1$d'));
626 $_inserted->addParam($insert_id + $num_rows - 1);
627 $message->addMessage($_inserted);
629 } elseif ($is_affected) {
630 $message = PMA_Message::affected_rows($num_rows);
632 // Ok, here is an explanation for the !$is_select.
633 // The form generated by sql_query_form.lib.php
634 // and db_sql.php has many submit buttons
635 // on the same form, and some confusion arises from the
636 // fact that $message_to_show is sent for every case.
637 // The $message_to_show containing a success message and sent with
638 // the form should not have priority over errors
639 } elseif (!empty($message_to_show) && !$is_select) {
640 $message = PMA_Message::rawSuccess(htmlspecialchars($message_to_show));
641 } elseif (!empty($GLOBALS['show_as_php'])) {
642 $message = PMA_Message::success(__('Showing as PHP code'));
643 } elseif (isset($GLOBALS['show_as_php'])) {
644 /* User disable showing as PHP, query is only displayed */
645 $message = PMA_Message::notice(__('Showing SQL query'));
646 } elseif (!empty($GLOBALS['validatequery'])) {
647 $message = PMA_Message::notice(__('Validated SQL'));
648 } else {
649 $message = PMA_Message::success(__('MySQL returned an empty result set (i.e. zero rows).'));
652 if (isset($GLOBALS['querytime'])) {
653 $_querytime = PMA_Message::notice(__('Query took %01.4f sec'));
654 $_querytime->addParam($GLOBALS['querytime']);
655 $message->addMessage('(');
656 $message->addMessage($_querytime);
657 $message->addMessage(')');
660 if( $GLOBALS['is_ajax_request'] == true) {
663 * If we are in inline editing, we need to process the relational and
664 * transformed fields, if they were edited. After that, output the correct
665 * link/transformed value and exit
667 * Logic taken from libraries/display_tbl.lib.php
670 if(isset($_REQUEST['rel_fields_list']) && $_REQUEST['rel_fields_list'] != '') {
671 //handle relations work here for updated row.
672 require_once './libraries/relation.lib.php';
674 $map = PMA_getForeigners($db, $table, '', 'both');
676 $rel_fields = array();
677 parse_str($_REQUEST['rel_fields_list'], $rel_fields);
679 foreach( $rel_fields as $rel_field => $rel_field_value) {
681 $where_comparison = "='" . $rel_field_value . "'";
682 $display_field = PMA_getDisplayField($map[$rel_field]['foreign_db'], $map[$rel_field]['foreign_table']);
684 // Field to display from the foreign table?
685 if (isset($display_field) && strlen($display_field)) {
686 $dispsql = 'SELECT ' . PMA_backquote($display_field)
687 . ' FROM ' . PMA_backquote($map[$rel_field]['foreign_db'])
688 . '.' . PMA_backquote($map[$rel_field]['foreign_table'])
689 . ' WHERE ' . PMA_backquote($map[$rel_field]['foreign_field'])
690 . $where_comparison;
691 $dispresult = PMA_DBI_try_query($dispsql, null, PMA_DBI_QUERY_STORE);
692 if ($dispresult && PMA_DBI_num_rows($dispresult) > 0) {
693 list($dispval) = PMA_DBI_fetch_row($dispresult, 0);
694 } else {
695 //$dispval = __('Link not found');
697 @PMA_DBI_free_result($dispresult);
698 } else {
699 $dispval = '';
700 } // end if... else...
702 if ('K' == $_SESSION['tmp_user_values']['relational_display']) {
703 // user chose "relational key" in the display options, so
704 // the title contains the display field
705 $title = (! empty($dispval))? ' title="' . htmlspecialchars($dispval) . '"' : '';
706 } else {
707 $title = ' title="' . htmlspecialchars($rel_field_value) . '"';
710 $_url_params = array(
711 'db' => $map[$rel_field]['foreign_db'],
712 'table' => $map[$rel_field]['foreign_table'],
713 'pos' => '0',
714 'sql_query' => 'SELECT * FROM '
715 . PMA_backquote($map[$rel_field]['foreign_db']) . '.' . PMA_backquote($map[$rel_field]['foreign_table'])
716 . ' WHERE ' . PMA_backquote($map[$rel_field]['foreign_field'])
717 . $where_comparison
719 $output = '<a href="sql.php' . PMA_generate_common_url($_url_params) . '"' . $title . '>';
721 if ('D' == $_SESSION['tmp_user_values']['relational_display']) {
722 // user chose "relational display field" in the
723 // display options, so show display field in the cell
724 $output .= (!empty($dispval)) ? htmlspecialchars($dispval) : '';
725 } else {
726 // otherwise display data in the cell
727 $output .= htmlspecialchars($rel_field_value);
729 $output .= '</a>';
730 $extra_data['relations'][$rel_field] = $output;
734 if(isset($_REQUEST['do_transformations']) && $_REQUEST['do_transformations'] == true ) {
735 require_once './libraries/transformations.lib.php';
736 //if some posted fields need to be transformed, generate them here.
737 $mime_map = PMA_getMIME($db, $table);
739 if ($mime_map === false) {
740 $mime_map = array();
743 $edited_values = array();
744 parse_str($_REQUEST['transform_fields_list'], $edited_values);
746 foreach($mime_map as $transformation) {
747 $include_file = $transformation['transformation'];
748 $column_name = $transformation['column_name'];
749 $column_data = $edited_values[$column_name];
751 $_url_params = array(
752 'db' => $db,
753 'table' => $table,
754 'where_clause' => $_REQUEST['where_clause'],
755 'transform_key' => $column_name,
758 if (file_exists('./libraries/transformations/' . $include_file)) {
759 $transformfunction_name = str_replace('.inc.php', '', $transformation['transformation']);
761 require_once './libraries/transformations/' . $include_file;
763 if (function_exists('PMA_transformation_' . $transformfunction_name)) {
764 $transform_function = 'PMA_transformation_' . $transformfunction_name;
765 $transform_options = PMA_transformation_getOptions((isset($transformation['transformation_options']) ? $transformation['transformation_options'] : ''));
766 $transform_options['wrapper_link'] = PMA_generate_common_url($_url_params);
770 $extra_data['transformations'][$column_name] = $transform_function($column_data, $transform_options);
774 if ($cfg['ShowSQL']) {
775 $extra_data['sql_query'] = PMA_showMessage($message, $GLOBALS['sql_query'], 'success');
777 if (isset($GLOBALS['reload']) && $GLOBALS['reload'] == 1) {
778 $extra_data['reload'] = 1;
779 $extra_data['db'] = $GLOBALS['db'];
781 PMA_ajaxResponse($message, $message->isSuccess(), (isset($extra_data) ? $extra_data : ''));
784 if ($is_gotofile) {
785 $goto = PMA_securePath($goto);
786 // Checks for a valid target script
787 $is_db = $is_table = false;
788 if (isset($_REQUEST['purge'])) {
789 $table = '';
790 unset($url_params['table']);
792 include 'libraries/db_table_exists.lib.php';
794 if (strpos($goto, 'tbl_') === 0 && ! $is_table) {
795 if (strlen($table)) {
796 $table = '';
798 $goto = 'db_sql.php';
800 if (strpos($goto, 'db_') === 0 && ! $is_db) {
801 if (strlen($db)) {
802 $db = '';
804 $goto = 'main.php';
806 // Loads to target script
807 if ($goto != 'main.php') {
808 require_once './libraries/header.inc.php';
810 $active_page = $goto;
811 require './' . $goto;
812 } else {
813 // avoid a redirect loop when last record was deleted
814 if (0 == $num_rows && 'sql.php' == $cfg['DefaultTabTable']) {
815 $goto = str_replace('sql.php','tbl_structure.php',$goto);
817 PMA_sendHeaderLocation($cfg['PmaAbsoluteUri'] . str_replace('&amp;', '&', $goto) . '&message=' . urlencode($message));
818 } // end else
819 exit();
820 } // end no rows returned
822 // At least one row is returned -> displays a table with results
823 else {
824 //If we are retrieving the full value of a truncated field or the original
825 // value of a transformed field, show it here and exit
826 if( $GLOBALS['inline_edit'] == true && $GLOBALS['cfg']['AjaxEnable']) {
827 $row = PMA_DBI_fetch_row($result);
828 $extra_data = array();
829 $extra_data['value'] = $row[0];
830 PMA_ajaxResponse(NULL, true, $extra_data);
833 // Displays the headers
834 if (isset($show_query)) {
835 unset($show_query);
837 if (isset($printview) && $printview == '1') {
838 require_once './libraries/header_printview.inc.php';
839 } else {
841 $GLOBALS['js_include'][] = 'functions.js';
842 $GLOBALS['js_include'][] = 'sql.js';
844 unset($message);
846 if( ! $GLOBALS['is_ajax_request'] || ! $GLOBALS['cfg']['AjaxEnable']) {
847 if (strlen($table)) {
848 require './libraries/tbl_common.php';
849 $url_query .= '&amp;goto=tbl_sql.php&amp;back=tbl_sql.php';
850 require './libraries/tbl_info.inc.php';
851 require './libraries/tbl_links.inc.php';
852 } elseif (strlen($db)) {
853 require './libraries/db_common.inc.php';
854 require './libraries/db_info.inc.php';
855 } else {
856 require './libraries/server_common.inc.php';
857 require './libraries/server_links.inc.php';
860 else {
861 require_once './libraries/header.inc.php';
862 //we don't need to buffer the output in PMA_showMessage here.
863 //set a global variable and check against it in the function
864 $GLOBALS['buffer_message'] = false;
868 if (strlen($db)) {
869 $cfgRelation = PMA_getRelationsParam();
872 // Gets the list of fields properties
873 if (isset($result) && $result) {
874 $fields_meta = PMA_DBI_get_fields_meta($result);
875 $fields_cnt = count($fields_meta);
878 if( ! $GLOBALS['is_ajax_request']) {
879 //begin the sqlqueryresults div here. container div
880 echo '<div id="sqlqueryresults"';
881 if ($GLOBALS['cfg']['AjaxEnable']) {
882 echo ' class="ajax"';
884 echo '>';
887 // Display previous update query (from tbl_replace)
888 if (isset($disp_query) && $cfg['ShowSQL'] == true) {
889 PMA_showMessage($disp_message, $disp_query, 'success');
892 if (isset($profiling_results)) {
893 PMA_profilingResults($profiling_results, true);
896 // Displays the results in a table
897 if (empty($disp_mode)) {
898 // see the "PMA_setDisplayMode()" function in
899 // libraries/display_tbl.lib.php
900 $disp_mode = 'urdr111101';
903 // hide edit and delete links for information_schema
904 if ($db == 'information_schema') {
905 $disp_mode = 'nnnn110111';
908 if (isset($label)) {
909 $message = PMA_message::success(__('Bookmark %s created'));
910 $message->addParam($label);
911 $message->display();
914 PMA_displayTable($result, $disp_mode, $analyzed_sql);
915 PMA_DBI_free_result($result);
917 // BEGIN INDEX CHECK See if indexes should be checked.
918 if (isset($query_type) && $query_type == 'check_tbl' && isset($selected) && is_array($selected)) {
919 foreach ($selected as $idx => $tbl_name) {
920 $check = PMA_Index::findDuplicates($tbl_name, $db);
921 if (! empty($check)) {
922 printf(__('Problems with indexes of table `%s`'), $tbl_name);
923 echo $check;
926 } // End INDEX CHECK
928 // Bookmark support if required
929 if ($disp_mode[7] == '1'
930 && (! empty($cfg['Bookmark']) && empty($id_bookmark))
931 && !empty($sql_query)) {
932 echo "\n";
934 $goto = 'sql.php?'
935 . PMA_generate_common_url($db, $table)
936 . '&amp;sql_query=' . urlencode($sql_query)
937 . '&amp;id_bookmark=1';
940 <form action="sql.php" method="post" onsubmit="return emptyFormElements(this, 'fields[label]');">
941 <?php echo PMA_generate_common_hidden_inputs(); ?>
942 <input type="hidden" name="goto" value="<?php echo $goto; ?>" />
943 <input type="hidden" name="fields[dbase]" value="<?php echo htmlspecialchars($db); ?>" />
944 <input type="hidden" name="fields[user]" value="<?php echo $cfg['Bookmark']['user']; ?>" />
945 <input type="hidden" name="fields[query]" value="<?php echo urlencode(isset($complete_query) ? $complete_query : $sql_query); ?>" />
946 <fieldset>
947 <legend><?php
948 echo ($cfg['PropertiesIconic'] ? '<img class="icon" src="' . $pmaThemeImage . 'b_bookmark.png" width="16" height="16" alt="' . __('Bookmark this SQL query') . '" />' : '')
949 . __('Bookmark this SQL query');
951 </legend>
953 <div class="formelement">
954 <label for="fields_label_"><?php echo __('Label'); ?>:</label>
955 <input type="text" id="fields_label_" name="fields[label]" value="" />
956 </div>
958 <div class="formelement">
959 <input type="checkbox" name="bkm_all_users" id="bkm_all_users" value="true" />
960 <label for="bkm_all_users"><?php echo __('Let every user access this bookmark'); ?></label>
961 </div>
963 <div class="clearfloat"></div>
964 </fieldset>
965 <fieldset class="tblFooters">
966 <input type="submit" name="store_bkm" value="<?php echo __('Bookmark this SQL query'); ?>" />
967 </fieldset>
968 </form>
969 <?php
970 } // end bookmark support
972 // Do print the page if required
973 if (isset($printview) && $printview == '1') {
975 <script type="text/javascript">
976 //<![CDATA[
977 // Do print the page
978 window.onload = function()
980 if (typeof(window.print) != 'undefined') {
981 window.print();
984 //]]>
985 </script>
986 <?php
987 } // end print case
989 if( $GLOBALS['is_ajax_request'] != true) {
990 echo '</div>'; // end sqlqueryresults div
992 } // end rows returned
995 * Displays the footer
997 if(! isset($_REQUEST['table_maintenance'])) {
998 require './libraries/footer.inc.php';