3.4.0-rc2
[phpmyadmin/alexukf.git] / sql.php
blob9587d32f4e77342e44af804f8ab9b06d3072032c
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="warning">' . __('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 // Do append a "LIMIT" clause?
360 if ((! $cfg['ShowAll'] || $_SESSION['tmp_user_values']['max_rows'] != 'all')
361 && ! ($is_count || $is_export || $is_func || $is_analyse)
362 && isset($analyzed_sql[0]['queryflags']['select_from'])
363 && ! isset($analyzed_sql[0]['queryflags']['offset'])
364 && empty($analyzed_sql[0]['limit_clause'])
366 $sql_limit_to_append = ' LIMIT ' . $_SESSION['tmp_user_values']['pos'] . ', ' . $_SESSION['tmp_user_values']['max_rows'] . " ";
368 $full_sql_query = $analyzed_sql[0]['section_before_limit'] . "\n" . $sql_limit_to_append . $analyzed_sql[0]['section_after_limit'];
370 * @todo pretty printing of this modified query
372 if (isset($display_query)) {
373 // if the analysis of the original query revealed that we found
374 // a section_after_limit, we now have to analyze $display_query
375 // to display it correctly
377 if (!empty($analyzed_sql[0]['section_after_limit']) && trim($analyzed_sql[0]['section_after_limit']) != ';') {
378 $analyzed_display_query = PMA_SQP_analyze(PMA_SQP_parse($display_query));
379 $display_query = $analyzed_display_query[0]['section_before_limit'] . "\n" . $sql_limit_to_append . $analyzed_display_query[0]['section_after_limit'];
383 } else {
384 $full_sql_query = $sql_query;
385 } // end if...else
387 if (strlen($db)) {
388 PMA_DBI_select_db($db);
391 // E x e c u t e t h e q u e r y
393 // Only if we didn't ask to see the php code (mikebeck)
394 if (isset($GLOBALS['show_as_php']) || !empty($GLOBALS['validatequery'])) {
395 unset($result);
396 $num_rows = 0;
397 } else {
398 if (isset($_SESSION['profiling']) && PMA_profilingSupported()) {
399 PMA_DBI_query('SET PROFILING=1;');
402 // Measure query time.
403 $querytime_before = array_sum(explode(' ', microtime()));
405 $result = @PMA_DBI_try_query($full_sql_query, null, PMA_DBI_QUERY_STORE);
407 $querytime_after = array_sum(explode(' ', microtime()));
409 $GLOBALS['querytime'] = $querytime_after - $querytime_before;
411 // Displays an error message if required and stop parsing the script
412 if ($error = PMA_DBI_getError()) {
413 if ($is_gotofile) {
414 if (strpos($goto, 'db_') === 0 && strlen($table)) {
415 $table = '';
417 $active_page = $goto;
418 $message = PMA_Message::rawError($error);
420 if( $GLOBALS['is_ajax_request'] == true) {
421 PMA_ajaxResponse($message, false);
425 * Go to target path.
427 require './' . PMA_securePath($goto);
428 } else {
429 $full_err_url = (preg_match('@^(db|tbl)_@', $err_url))
430 ? $err_url . '&amp;show_query=1&amp;sql_query=' . urlencode($sql_query)
431 : $err_url;
432 PMA_mysqlDie($error, $full_sql_query, '', $full_err_url);
434 exit;
436 unset($error);
438 // Gets the number of rows affected/returned
439 // (This must be done immediately after the query because
440 // mysql_affected_rows() reports about the last query done)
442 if (!$is_affected) {
443 $num_rows = ($result) ? @PMA_DBI_num_rows($result) : 0;
444 } elseif (!isset($num_rows)) {
445 $num_rows = @PMA_DBI_affected_rows();
448 // Grabs the profiling results
449 if (isset($_SESSION['profiling']) && PMA_profilingSupported()) {
450 $profiling_results = PMA_DBI_fetch_result('SHOW PROFILE;');
453 // Checks if the current database has changed
454 // This could happen if the user sends a query like "USE `database`;"
456 * commented out auto-switching to active database - really required?
457 * bug #1814718 win: table list disappears (mixed case db names)
458 * https://sourceforge.net/support/tracker.php?aid=1814718
459 * @todo RELEASE test and comit or rollback before release
460 $current_db = PMA_DBI_fetch_value('SELECT DATABASE()');
461 if ($db !== $current_db) {
462 $db = $current_db;
463 $reload = 1;
465 unset($current_db);
468 // tmpfile remove after convert encoding appended by Y.Kawada
469 if (function_exists('PMA_kanji_file_conv')
470 && (isset($textfile) && file_exists($textfile))) {
471 unlink($textfile);
474 // Counts the total number of rows for the same 'SELECT' query without the
475 // 'LIMIT' clause that may have been programatically added
477 if (empty($sql_limit_to_append)) {
478 $unlim_num_rows = $num_rows;
479 // if we did not append a limit, set this to get a correct
480 // "Showing rows..." message
481 //$_SESSION['tmp_user_values']['max_rows'] = 'all';
482 } elseif ($is_select) {
484 // c o u n t q u e r y
486 // If we are "just browsing", there is only one table,
487 // and no WHERE clause (or just 'WHERE 1 '),
488 // we do a quick count (which uses MaxExactCount) because
489 // SQL_CALC_FOUND_ROWS is not quick on large InnoDB tables
491 // However, do not count again if we did it previously
492 // due to $find_real_end == true
494 if (!$is_group
495 && !isset($analyzed_sql[0]['queryflags']['union'])
496 && !isset($analyzed_sql[0]['table_ref'][1]['table_name'])
497 && (empty($analyzed_sql[0]['where_clause'])
498 || $analyzed_sql[0]['where_clause'] == '1 ')
499 && !isset($find_real_end)
502 // "j u s t b r o w s i n g"
503 $unlim_num_rows = PMA_Table::countRecords($db, $table);
505 } else { // n o t " j u s t b r o w s i n g "
507 // add select expression after the SQL_CALC_FOUND_ROWS
509 // for UNION, just adding SQL_CALC_FOUND_ROWS
510 // after the first SELECT works.
512 // take the left part, could be:
513 // SELECT
514 // (SELECT
515 $count_query = PMA_SQP_formatHtml($parsed_sql, 'query_only', 0, $analyzed_sql[0]['position_of_first_select'] + 1);
516 $count_query .= ' SQL_CALC_FOUND_ROWS ';
517 // add everything that was after the first SELECT
518 $count_query .= PMA_SQP_formatHtml($parsed_sql, 'query_only', $analyzed_sql[0]['position_of_first_select']+1);
519 // ensure there is no semicolon at the end of the
520 // count query because we'll probably add
521 // a LIMIT 1 clause after it
522 $count_query = rtrim($count_query);
523 $count_query = rtrim($count_query, ';');
525 // if using SQL_CALC_FOUND_ROWS, add a LIMIT to avoid
526 // long delays. Returned count will be complete anyway.
527 // (but a LIMIT would disrupt results in an UNION)
529 if (!isset($analyzed_sql[0]['queryflags']['union'])) {
530 $count_query .= ' LIMIT 1';
533 // run the count query
535 PMA_DBI_try_query($count_query);
536 // if (mysql_error()) {
537 // void.
538 // I tried the case
539 // (SELECT `User`, `Host`, `Db`, `Select_priv` FROM `db`)
540 // UNION (SELECT `User`, `Host`, "%" AS "Db",
541 // `Select_priv`
542 // FROM `user`) ORDER BY `User`, `Host`, `Db`;
543 // and although the generated count_query is wrong
544 // the SELECT FOUND_ROWS() work! (maybe it gets the
545 // count from the latest query that worked)
547 // another case where the count_query is wrong:
548 // SELECT COUNT(*), f1 from t1 group by f1
549 // and you click to sort on count(*)
550 // }
551 $unlim_num_rows = PMA_DBI_fetch_value('SELECT FOUND_ROWS()');
552 } // end else "just browsing"
554 } else { // not $is_select
555 $unlim_num_rows = 0;
556 } // end rows total count
558 // if a table or database gets dropped, check column comments.
559 if (isset($purge) && $purge == '1') {
561 * Cleanup relations.
563 require_once './libraries/relation_cleanup.lib.php';
565 if (strlen($table) && strlen($db)) {
566 PMA_relationsCleanupTable($db, $table);
567 } elseif (strlen($db)) {
568 PMA_relationsCleanupDatabase($db);
569 } else {
570 // VOID. No DB/Table gets deleted.
571 } // end if relation-stuff
572 } // end if ($purge)
574 // If a column gets dropped, do relation magic.
575 if (isset($dropped_column) && strlen($db) && strlen($table) && !empty($dropped_column)) {
576 require_once './libraries/relation_cleanup.lib.php';
577 PMA_relationsCleanupColumn($db, $table, $dropped_column);
579 } // end if column was dropped
580 } // end else "didn't ask to see php code"
582 // No rows returned -> move back to the calling page
583 if (0 == $num_rows || $is_affected) {
584 if ($is_delete) {
585 $message = PMA_Message::deleted_rows($num_rows);
586 } elseif ($is_insert) {
587 if ($is_replace) {
588 /* For replace we get DELETED + INSERTED row count, so we have to call it affected */
589 $message = PMA_Message::affected_rows($num_rows);
590 } else {
591 $message = PMA_Message::inserted_rows($num_rows);
593 $insert_id = PMA_DBI_insert_id();
594 if ($insert_id != 0) {
595 // insert_id is id of FIRST record inserted in one insert, so if we inserted multiple rows, we had to increment this
596 $message->addMessage('[br]');
597 // need to use a temporary because the Message class
598 // currently supports adding parameters only to the first
599 // message
600 $_inserted = PMA_Message::notice(__('Inserted row id: %1$d'));
601 $_inserted->addParam($insert_id + $num_rows - 1);
602 $message->addMessage($_inserted);
604 } elseif ($is_affected) {
605 $message = PMA_Message::affected_rows($num_rows);
607 // Ok, here is an explanation for the !$is_select.
608 // The form generated by sql_query_form.lib.php
609 // and db_sql.php has many submit buttons
610 // on the same form, and some confusion arises from the
611 // fact that $message_to_show is sent for every case.
612 // The $message_to_show containing a success message and sent with
613 // the form should not have priority over errors
614 } elseif (!empty($message_to_show) && !$is_select) {
615 $message = PMA_Message::rawSuccess(htmlspecialchars($message_to_show));
616 } elseif (!empty($GLOBALS['show_as_php'])) {
617 $message = PMA_Message::success(__('Showing as PHP code'));
618 } elseif (isset($GLOBALS['show_as_php'])) {
619 /* User disable showing as PHP, query is only displayed */
620 $message = PMA_Message::notice(__('Showing SQL query'));
621 } elseif (!empty($GLOBALS['validatequery'])) {
622 $message = PMA_Message::notice(__('Validated SQL'));
623 } else {
624 $message = PMA_Message::success(__('MySQL returned an empty result set (i.e. zero rows).'));
627 if (isset($GLOBALS['querytime'])) {
628 $_querytime = PMA_Message::notice(__('Query took %01.4f sec'));
629 $_querytime->addParam($GLOBALS['querytime']);
630 $message->addMessage('(');
631 $message->addMessage($_querytime);
632 $message->addMessage(')');
635 if( $GLOBALS['is_ajax_request'] == true) {
638 * If we are in inline editing, we need to process the relational and
639 * transformed fields, if they were edited. After that, output the correct
640 * link/transformed value and exit
642 * Logic taken from libraries/display_tbl.lib.php
645 if(isset($_REQUEST['rel_fields_list']) && $_REQUEST['rel_fields_list'] != '') {
646 //handle relations work here for updated row.
647 require_once './libraries/relation.lib.php';
649 $map = PMA_getForeigners($db, $table, '', 'both');
651 $rel_fields = array();
652 parse_str($_REQUEST['rel_fields_list'], $rel_fields);
654 foreach( $rel_fields as $rel_field => $rel_field_value) {
656 $where_comparison = "='" . $rel_field_value . "'";
657 $display_field = PMA_getDisplayField($map[$rel_field]['foreign_db'], $map[$rel_field]['foreign_table']);
659 // Field to display from the foreign table?
660 if (isset($display_field) && strlen($display_field)) {
661 $dispsql = 'SELECT ' . PMA_backquote($display_field)
662 . ' FROM ' . PMA_backquote($map[$rel_field]['foreign_db'])
663 . '.' . PMA_backquote($map[$rel_field]['foreign_table'])
664 . ' WHERE ' . PMA_backquote($map[$rel_field]['foreign_field'])
665 . $where_comparison;
666 $dispresult = PMA_DBI_try_query($dispsql, null, PMA_DBI_QUERY_STORE);
667 if ($dispresult && PMA_DBI_num_rows($dispresult) > 0) {
668 list($dispval) = PMA_DBI_fetch_row($dispresult, 0);
669 } else {
670 //$dispval = __('Link not found');
672 @PMA_DBI_free_result($dispresult);
673 } else {
674 $dispval = '';
675 } // end if... else...
677 if ('K' == $_SESSION['tmp_user_values']['relational_display']) {
678 // user chose "relational key" in the display options, so
679 // the title contains the display field
680 $title = (! empty($dispval))? ' title="' . htmlspecialchars($dispval) . '"' : '';
681 } else {
682 $title = ' title="' . htmlspecialchars($rel_field_value) . '"';
685 $_url_params = array(
686 'db' => $map[$rel_field]['foreign_db'],
687 'table' => $map[$rel_field]['foreign_table'],
688 'pos' => '0',
689 'sql_query' => 'SELECT * FROM '
690 . PMA_backquote($map[$rel_field]['foreign_db']) . '.' . PMA_backquote($map[$rel_field]['foreign_table'])
691 . ' WHERE ' . PMA_backquote($map[$rel_field]['foreign_field'])
692 . $where_comparison
694 $output = '<a href="sql.php' . PMA_generate_common_url($_url_params) . '"' . $title . '>';
696 if ('D' == $_SESSION['tmp_user_values']['relational_display']) {
697 // user chose "relational display field" in the
698 // display options, so show display field in the cell
699 $output .= (!empty($dispval)) ? htmlspecialchars($dispval) : '';
700 } else {
701 // otherwise display data in the cell
702 $output .= htmlspecialchars($rel_field_value);
704 $output .= '</a>';
705 $extra_data['relations'][$rel_field] = $output;
709 if(isset($_REQUEST['do_transformations']) && $_REQUEST['do_transformations'] == true ) {
710 require_once './libraries/transformations.lib.php';
711 //if some posted fields need to be transformed, generate them here.
712 $mime_map = PMA_getMIME($db, $table);
714 if ($mime_map === FALSE) {
715 $mime_map = array();
718 $edited_values = array();
719 parse_str($_REQUEST['transform_fields_list'], $edited_values);
721 foreach($mime_map as $transformation) {
722 $include_file = $transformation['transformation'];
723 $column_name = $transformation['column_name'];
724 $column_data = $edited_values[$column_name];
726 $_url_params = array(
727 'db' => $db,
728 'table' => $table,
729 'where_clause' => $_REQUEST['where_clause'],
730 'transform_key' => $column_name,
733 if (file_exists('./libraries/transformations/' . $include_file)) {
734 $transformfunction_name = str_replace('.inc.php', '', $transformation['transformation']);
736 require_once './libraries/transformations/' . $include_file;
738 if (function_exists('PMA_transformation_' . $transformfunction_name)) {
739 $transform_function = 'PMA_transformation_' . $transformfunction_name;
740 $transform_options = PMA_transformation_getOptions((isset($transformation['transformation_options']) ? $transformation['transformation_options'] : ''));
741 $transform_options['wrapper_link'] = PMA_generate_common_url($_url_params);
745 $extra_data['transformations'][$column_name] = $transform_function($column_data, $transform_options);
749 if ($cfg['ShowSQL']) {
750 $extra_data['sql_query'] = PMA_showMessage($message, $GLOBALS['sql_query'], 'success');
752 if (isset($GLOBALS['reload']) && $GLOBALS['reload'] == 1) {
753 $extra_data['reload'] = 1;
754 $extra_data['db'] = $GLOBALS['db'];
756 PMA_ajaxResponse($message, $message->isSuccess(), (isset($extra_data) ? $extra_data : ''));
759 if ($is_gotofile) {
760 $goto = PMA_securePath($goto);
761 // Checks for a valid target script
762 $is_db = $is_table = false;
763 if (isset($_REQUEST['purge'])) {
764 $table = '';
765 unset($url_params['table']);
767 include 'libraries/db_table_exists.lib.php';
769 if (strpos($goto, 'tbl_') === 0 && ! $is_table) {
770 if (strlen($table)) {
771 $table = '';
773 $goto = 'db_sql.php';
775 if (strpos($goto, 'db_') === 0 && ! $is_db) {
776 if (strlen($db)) {
777 $db = '';
779 $goto = 'main.php';
781 // Loads to target script
782 if ($goto != 'main.php') {
783 require_once './libraries/header.inc.php';
785 $active_page = $goto;
786 require './' . $goto;
787 } else {
788 // avoid a redirect loop when last record was deleted
789 if (0 == $num_rows && 'sql.php' == $cfg['DefaultTabTable']) {
790 $goto = str_replace('sql.php','tbl_structure.php',$goto);
792 PMA_sendHeaderLocation($cfg['PmaAbsoluteUri'] . str_replace('&amp;', '&', $goto) . '&message=' . urlencode($message));
793 } // end else
794 exit();
795 } // end no rows returned
797 // At least one row is returned -> displays a table with results
798 else {
799 //If we are retrieving the full value of a truncated field or the original
800 // value of a transformed field, show it here and exit
801 if( $GLOBALS['inline_edit'] == true && $GLOBALS['cfg']['AjaxEnable']) {
802 $row = PMA_DBI_fetch_row($result);
803 $extra_data = array();
804 $extra_data['value'] = $row[0];
805 PMA_ajaxResponse(NULL, true, $extra_data);
808 // Displays the headers
809 if (isset($show_query)) {
810 unset($show_query);
812 if (isset($printview) && $printview == '1') {
813 require_once './libraries/header_printview.inc.php';
814 } else {
816 $GLOBALS['js_include'][] = 'functions.js';
817 $GLOBALS['js_include'][] = 'sql.js';
819 unset($message);
821 if( ! $GLOBALS['is_ajax_request'] || ! $GLOBALS['cfg']['AjaxEnable']) {
822 if (strlen($table)) {
823 require './libraries/tbl_common.php';
824 $url_query .= '&amp;goto=tbl_sql.php&amp;back=tbl_sql.php';
825 require './libraries/tbl_info.inc.php';
826 require './libraries/tbl_links.inc.php';
827 } elseif (strlen($db)) {
828 require './libraries/db_common.inc.php';
829 require './libraries/db_info.inc.php';
830 } else {
831 require './libraries/server_common.inc.php';
832 require './libraries/server_links.inc.php';
835 else {
836 require_once './libraries/header.inc.php';
837 //we don't need to buffer the output in PMA_showMessage here.
838 //set a global variable and check against it in the function
839 $GLOBALS['buffer_message'] = false;
843 if (strlen($db)) {
844 $cfgRelation = PMA_getRelationsParam();
847 // Gets the list of fields properties
848 if (isset($result) && $result) {
849 $fields_meta = PMA_DBI_get_fields_meta($result);
850 $fields_cnt = count($fields_meta);
853 if( ! $GLOBALS['is_ajax_request']) {
854 //begin the sqlqueryresults div here. container div
855 echo '<div id="sqlqueryresults"';
856 if ($GLOBALS['cfg']['AjaxEnable']) {
857 echo ' class="ajax"';
859 echo '>';
862 // Display previous update query (from tbl_replace)
863 if (isset($disp_query) && $cfg['ShowSQL'] == true) {
864 PMA_showMessage($disp_message, $disp_query, 'success');
867 if (isset($profiling_results)) {
868 PMA_profilingResults($profiling_results, true);
871 // Displays the results in a table
872 if (empty($disp_mode)) {
873 // see the "PMA_setDisplayMode()" function in
874 // libraries/display_tbl.lib.php
875 $disp_mode = 'urdr111101';
878 // hide edit and delete links for information_schema
879 if ($db == 'information_schema') {
880 $disp_mode = 'nnnn110111';
883 if (isset($label)) {
884 $message = PMA_message::success(__('Bookmark %s created'));
885 $message->addParam($label);
886 $message->display();
889 PMA_displayTable($result, $disp_mode, $analyzed_sql);
890 PMA_DBI_free_result($result);
892 // BEGIN INDEX CHECK See if indexes should be checked.
893 if (isset($query_type) && $query_type == 'check_tbl' && isset($selected) && is_array($selected)) {
894 foreach ($selected as $idx => $tbl_name) {
895 $check = PMA_Index::findDuplicates($tbl_name, $db);
896 if (! empty($check)) {
897 printf(__('Problems with indexes of table `%s`'), $tbl_name);
898 echo $check;
901 } // End INDEX CHECK
903 // Bookmark support if required
904 if ($disp_mode[7] == '1'
905 && (! empty($cfg['Bookmark']) && empty($id_bookmark))
906 && !empty($sql_query)) {
907 echo "\n";
909 $goto = 'sql.php?'
910 . PMA_generate_common_url($db, $table)
911 . '&amp;sql_query=' . urlencode($sql_query)
912 . '&amp;id_bookmark=1';
915 <form action="sql.php" method="post" onsubmit="return emptyFormElements(this, 'fields[label]');">
916 <?php echo PMA_generate_common_hidden_inputs(); ?>
917 <input type="hidden" name="goto" value="<?php echo $goto; ?>" />
918 <input type="hidden" name="fields[dbase]" value="<?php echo htmlspecialchars($db); ?>" />
919 <input type="hidden" name="fields[user]" value="<?php echo $cfg['Bookmark']['user']; ?>" />
920 <input type="hidden" name="fields[query]" value="<?php echo urlencode(isset($complete_query) ? $complete_query : $sql_query); ?>" />
921 <fieldset>
922 <legend><?php
923 echo ($cfg['PropertiesIconic'] ? '<img class="icon" src="' . $pmaThemeImage . 'b_bookmark.png" width="16" height="16" alt="' . __('Bookmark this SQL query') . '" />' : '')
924 . __('Bookmark this SQL query');
926 </legend>
928 <div class="formelement">
929 <label for="fields_label_"><?php echo __('Label'); ?>:</label>
930 <input type="text" id="fields_label_" name="fields[label]" value="" />
931 </div>
933 <div class="formelement">
934 <input type="checkbox" name="bkm_all_users" id="bkm_all_users" value="true" />
935 <label for="bkm_all_users"><?php echo __('Let every user access this bookmark'); ?></label>
936 </div>
938 <div class="clearfloat"></div>
939 </fieldset>
940 <fieldset class="tblFooters">
941 <input type="submit" name="store_bkm" value="<?php echo __('Bookmark this SQL query'); ?>" />
942 </fieldset>
943 </form>
944 <?php
945 } // end bookmark support
947 // Do print the page if required
948 if (isset($printview) && $printview == '1') {
950 <script type="text/javascript">
951 //<![CDATA[
952 // Do print the page
953 window.onload = function()
955 if (typeof(window.print) != 'undefined') {
956 window.print();
959 //]]>
960 </script>
961 <?php
962 } // end print case
964 if( $GLOBALS['is_ajax_request'] != true) {
965 echo '</div>'; // end sqlqueryresults div
967 } // end rows returned
970 * Displays the footer
972 if(!isset($_REQUEST['table_maintenance'])) {
973 require './libraries/footer.inc.php';