Translation update done using Pootle.
[phpmyadmin-themes.git] / sql.php
blob3a8bac4b6c0ed92b55fcf2e4703731f3a0b7442d
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 $foreignData = PMA_getForeignData($foreigners, $column, false, '', '');
68 $dropdown = PMA_foreignDropdown($foreignData['disp_row'], $foreignData['foreign_field'], $foreignData['foreign_display'], $_REQUEST['curr_value'], $cfg['ForeignKeyMaxLimit']);
70 if( $dropdown == '<option value="">&nbsp;</option>'."\n" ) {
71 //Handle the case when number of values is more than $cfg['ForeignKeyMaxLimit']
72 $_url_params = array(
73 'db' => $db,
74 'table' => $table,
75 'field' => $column
78 $dropdown = '<span class="curr_value">' . htmlspecialchars($_REQUEST['curr_value']) . '</span> <a href="browse_foreigners.php' . PMA_generate_common_url($_url_params) . '"'
79 . ' target="_blank" class="browse_foreign" '
80 .'>' . __('Browse foreign values') . '</a>';
82 else {
83 $dropdown = '<select>' . $dropdown . '</select>';
86 $extra_data['dropdown'] = $dropdown;
87 PMA_ajaxResponse(NULL, true, $extra_data);
90 /**
91 * Just like above, find possible values for enum fields during inline edit.
93 * Logic taken from libraries/display_tbl_lib.php
95 if(isset($_REQUEST['get_enum_values']) && $_REQUEST['get_enum_values'] == true) {
96 $field_info_query = 'SHOW FIELDS FROM `' . $db . '`.`' . $table . '` LIKE \'' . $_REQUEST['column'] . '\' ;';
98 $field_info_result = PMA_DBI_fetch_result($field_info_query, null, null, null, PMA_DBI_QUERY_STORE);
100 $search = array('enum', '(', ')', "'");
102 $values = explode(',', str_replace($search, '', $field_info_result[0]['Type']));
104 $dropdown = '';
105 foreach($values as $value) {
106 $dropdown .= '<option value="' . htmlspecialchars($value) . '"';
107 if($value == $_REQUEST['curr_value']) {
108 $dropdown .= ' selected="selected"';
110 $dropdown .= '>' . $value . '</option>';
113 $dropdown = '<select>' . $dropdown . '</select>';
115 $extra_data['dropdown'] = $dropdown;
116 PMA_ajaxResponse(NULL, true, $extra_data);
119 // Default to browse if no query set and we have table
120 // (needed for browsing from DefaultTabTable)
121 if (empty($sql_query) && strlen($table) && strlen($db)) {
122 require_once './libraries/bookmark.lib.php';
123 $book_sql_query = PMA_Bookmark_get($db, '\'' . PMA_sqlAddslashes($table) . '\'',
124 'label', FALSE, TRUE);
126 if (! empty($book_sql_query)) {
127 $GLOBALS['using_bookmark_message'] = PMA_message::notice(__('Using bookmark "%s" as default browse query.'));
128 $GLOBALS['using_bookmark_message']->addParam($table);
129 $GLOBALS['using_bookmark_message']->addMessage(PMA_showDocu('faq6_22'));
130 $sql_query = $book_sql_query;
131 } else {
132 $sql_query = 'SELECT * FROM ' . PMA_backquote($table);
134 unset($book_sql_query);
136 // set $goto to what will be displayed if query returns 0 rows
137 $goto = 'tbl_structure.php';
138 } else {
139 // Now we can check the parameters
140 PMA_checkParameters(array('sql_query'));
143 // instead of doing the test twice
144 $is_drop_database = preg_match('/DROP[[:space:]]+(DATABASE|SCHEMA)[[:space:]]+/i',
145 $sql_query);
148 * Check rights in case of DROP DATABASE
150 * This test may be bypassed if $is_js_confirmed = 1 (already checked with js)
151 * but since a malicious user may pass this variable by url/form, we don't take
152 * into account this case.
154 if (!defined('PMA_CHK_DROP')
155 && !$cfg['AllowUserDropDatabase']
156 && $is_drop_database
157 && !$is_superuser) {
158 require_once './libraries/header.inc.php';
159 PMA_mysqlDie(__('"DROP DATABASE" statements are disabled.'), '', '', $err_url);
160 } // end if
162 require_once './libraries/display_tbl.lib.php';
163 PMA_displayTable_checkConfigParams();
166 * Need to find the real end of rows?
168 if (isset($find_real_end) && $find_real_end) {
169 $unlim_num_rows = PMA_Table::countRecords($db, $table, $force_exact = true);
170 $_SESSION['tmp_user_values']['pos'] = @((ceil($unlim_num_rows / $_SESSION['tmp_user_values']['max_rows']) - 1) * $_SESSION['tmp_user_values']['max_rows']);
175 * Bookmark add
177 if (isset($store_bkm)) {
178 PMA_Bookmark_save($fields, (isset($bkm_all_users) && $bkm_all_users == 'true' ? true : false));
179 // go back to sql.php to redisplay query; do not use &amp; in this case:
180 PMA_sendHeaderLocation($cfg['PmaAbsoluteUri'] . $goto . '&label=' . $fields['label']);
181 } // end if
184 * Parse and analyze the query
186 require_once './libraries/parse_analyze.lib.php';
189 * Sets or modifies the $goto variable if required
191 if ($goto == 'sql.php') {
192 $is_gotofile = false;
193 $goto = 'sql.php?'
194 . PMA_generate_common_url($db, $table)
195 . '&amp;sql_query=' . urlencode($sql_query);
196 } // end if
200 * Go back to further page if table should not be dropped
202 if (isset($btnDrop) && $btnDrop == __('No')) {
203 if (!empty($back)) {
204 $goto = $back;
206 if ($is_gotofile) {
207 if (strpos($goto, 'db_') === 0 && strlen($table)) {
208 $table = '';
210 $active_page = $goto;
211 require './' . PMA_securePath($goto);
212 } else {
213 PMA_sendHeaderLocation($cfg['PmaAbsoluteUri'] . str_replace('&amp;', '&', $goto));
215 exit();
216 } // end if
220 * Displays the confirm page if required
222 * This part of the script is bypassed if $is_js_confirmed = 1 (already checked
223 * with js) because possible security issue is not so important here: at most,
224 * the confirm message isn't displayed.
226 * Also bypassed if only showing php code.or validating a SQL query
228 if (! $cfg['Confirm'] || isset($_REQUEST['is_js_confirmed']) || isset($btnDrop)
229 // if we are coming from a "Create PHP code" or a "Without PHP Code"
230 // dialog, we won't execute the query anyway, so don't confirm
231 || isset($GLOBALS['show_as_php'])
232 || !empty($GLOBALS['validatequery'])) {
233 $do_confirm = false;
234 } else {
235 $do_confirm = isset($analyzed_sql[0]['queryflags']['need_confirm']);
238 if ($do_confirm) {
239 $stripped_sql_query = $sql_query;
240 require_once './libraries/header.inc.php';
241 if ($is_drop_database) {
242 echo '<h1 class="warning">' . __('You are about to DESTROY a complete database!') . '</h1>';
244 echo '<form action="sql.php" method="post">' . "\n"
245 .PMA_generate_common_hidden_inputs($db, $table);
247 <input type="hidden" name="sql_query" value="<?php echo htmlspecialchars($sql_query); ?>" />
248 <input type="hidden" name="message_to_show" value="<?php echo isset($message_to_show) ? PMA_sanitize($message_to_show, true) : ''; ?>" />
249 <input type="hidden" name="goto" value="<?php echo $goto; ?>" />
250 <input type="hidden" name="back" value="<?php echo isset($back) ? PMA_sanitize($back, true) : ''; ?>" />
251 <input type="hidden" name="reload" value="<?php echo isset($reload) ? PMA_sanitize($reload, true) : 0; ?>" />
252 <input type="hidden" name="purge" value="<?php echo isset($purge) ? PMA_sanitize($purge, true) : ''; ?>" />
253 <input type="hidden" name="dropped_column" value="<?php echo isset($dropped_column) ? PMA_sanitize($dropped_column, true) : ''; ?>" />
254 <input type="hidden" name="show_query" value="<?php echo isset($show_query) ? PMA_sanitize($show_query, true) : ''; ?>" />
255 <?php
256 echo '<fieldset class="confirmation">' . "\n"
257 .' <legend>' . __('Do you really want to ') . '</legend>'
258 .' <tt>' . htmlspecialchars($stripped_sql_query) . '</tt>' . "\n"
259 .'</fieldset>' . "\n"
260 .'<fieldset class="tblFooters">' . "\n";
262 <input type="submit" name="btnDrop" value="<?php echo __('Yes'); ?>" id="buttonYes" />
263 <input type="submit" name="btnDrop" value="<?php echo __('No'); ?>" id="buttonNo" />
264 <?php
265 echo '</fieldset>' . "\n"
266 . '</form>' . "\n";
269 * Displays the footer and exit
271 require './libraries/footer.inc.php';
272 } // end if $do_confirm
275 // Defines some variables
276 // A table has to be created, renamed, dropped -> navi frame should be reloaded
278 * @todo use the parser/analyzer
281 if (empty($reload)
282 && preg_match('/^(CREATE|ALTER|DROP)\s+(VIEW|TABLE|DATABASE|SCHEMA)\s+/i', $sql_query)) {
283 $reload = 1;
286 // SK -- Patch: $is_group added for use in calculation of total number of
287 // rows.
288 // $is_count is changed for more correct "LIMIT" clause
289 // appending in queries like
290 // "SELECT COUNT(...) FROM ... GROUP BY ..."
293 * @todo detect all this with the parser, to avoid problems finding
294 * those strings in comments or backquoted identifiers
297 $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;
298 if ($is_select) { // see line 141
299 $is_group = preg_match('@(GROUP[[:space:]]+BY|HAVING|SELECT[[:space:]]+DISTINCT)[[:space:]]+@i', $sql_query);
300 $is_func = !$is_group && (preg_match('@[[:space:]]+(SUM|AVG|STD|STDDEV|MIN|MAX|BIT_OR|BIT_AND)\s*\(@i', $sql_query));
301 $is_count = !$is_group && (preg_match('@^SELECT[[:space:]]+COUNT\((.*\.+)?.*\)@i', $sql_query));
302 $is_export = (preg_match('@[[:space:]]+INTO[[:space:]]+OUTFILE[[:space:]]+@i', $sql_query));
303 $is_analyse = (preg_match('@[[:space:]]+PROCEDURE[[:space:]]+ANALYSE@i', $sql_query));
304 } elseif (preg_match('@^EXPLAIN[[:space:]]+@i', $sql_query)) {
305 $is_explain = true;
306 } elseif (preg_match('@^DELETE[[:space:]]+@i', $sql_query)) {
307 $is_delete = true;
308 $is_affected = true;
309 } elseif (preg_match('@^(INSERT|LOAD[[:space:]]+DATA|REPLACE)[[:space:]]+@i', $sql_query)) {
310 $is_insert = true;
311 $is_affected = true;
312 if (preg_match('@^(REPLACE)[[:space:]]+@i', $sql_query)) {
313 $is_replace = true;
315 } elseif (preg_match('@^UPDATE[[:space:]]+@i', $sql_query)) {
316 $is_affected = true;
317 } elseif (preg_match('@^[[:space:]]*SHOW[[:space:]]+@i', $sql_query)) {
318 $is_show = true;
319 } elseif (preg_match('@^(CHECK|ANALYZE|REPAIR|OPTIMIZE)[[:space:]]+TABLE[[:space:]]+@i', $sql_query)) {
320 $is_maint = true;
323 // Do append a "LIMIT" clause?
324 if ((! $cfg['ShowAll'] || $_SESSION['tmp_user_values']['max_rows'] != 'all')
325 && ! ($is_count || $is_export || $is_func || $is_analyse)
326 && isset($analyzed_sql[0]['queryflags']['select_from'])
327 && ! isset($analyzed_sql[0]['queryflags']['offset'])
328 && empty($analyzed_sql[0]['limit_clause'])
330 $sql_limit_to_append = ' LIMIT ' . $_SESSION['tmp_user_values']['pos'] . ', ' . $_SESSION['tmp_user_values']['max_rows'] . " ";
332 $full_sql_query = $analyzed_sql[0]['section_before_limit'] . "\n" . $sql_limit_to_append . $analyzed_sql[0]['section_after_limit'];
334 * @todo pretty printing of this modified query
336 if (isset($display_query)) {
337 // if the analysis of the original query revealed that we found
338 // a section_after_limit, we now have to analyze $display_query
339 // to display it correctly
341 if (!empty($analyzed_sql[0]['section_after_limit']) && trim($analyzed_sql[0]['section_after_limit']) != ';') {
342 $analyzed_display_query = PMA_SQP_analyze(PMA_SQP_parse($display_query));
343 $display_query = $analyzed_display_query[0]['section_before_limit'] . "\n" . $sql_limit_to_append . $analyzed_display_query[0]['section_after_limit'];
347 } else {
348 $full_sql_query = $sql_query;
349 } // end if...else
351 if (strlen($db)) {
352 PMA_DBI_select_db($db);
355 // E x e c u t e t h e q u e r y
357 // Only if we didn't ask to see the php code (mikebeck)
358 if (isset($GLOBALS['show_as_php']) || !empty($GLOBALS['validatequery'])) {
359 unset($result);
360 $num_rows = 0;
361 } else {
362 if (isset($_SESSION['profiling']) && PMA_profilingSupported()) {
363 PMA_DBI_query('SET PROFILING=1;');
366 // Measure query time.
367 // TODO-Item http://sourceforge.net/tracker/index.php?func=detail&aid=571934&group_id=23067&atid=377411
368 $querytime_before = array_sum(explode(' ', microtime()));
370 $result = @PMA_DBI_try_query($full_sql_query, null, PMA_DBI_QUERY_STORE);
372 $querytime_after = array_sum(explode(' ', microtime()));
374 $GLOBALS['querytime'] = $querytime_after - $querytime_before;
376 // Displays an error message if required and stop parsing the script
377 if ($error = PMA_DBI_getError()) {
378 if ($is_gotofile) {
379 if (strpos($goto, 'db_') === 0 && strlen($table)) {
380 $table = '';
382 $active_page = $goto;
383 $message = PMA_Message::rawError($error);
385 if( $GLOBALS['is_ajax_request'] == true) {
386 PMA_ajaxResponse($message, false);
390 * Go to target path.
392 require './' . PMA_securePath($goto);
393 } else {
395 * HTML header.
398 if($GLOBALS['is_ajax_request'] != true) {
399 require_once './libraries/header.inc.php';
401 $full_err_url = (preg_match('@^(db|tbl)_@', $err_url))
402 ? $err_url . '&amp;show_query=1&amp;sql_query=' . urlencode($sql_query)
403 : $err_url;
404 PMA_mysqlDie($error, $full_sql_query, '', $full_err_url);
406 exit;
408 unset($error);
410 // Gets the number of rows affected/returned
411 // (This must be done immediately after the query because
412 // mysql_affected_rows() reports about the last query done)
414 if (!$is_affected) {
415 $num_rows = ($result) ? @PMA_DBI_num_rows($result) : 0;
416 } elseif (!isset($num_rows)) {
417 $num_rows = @PMA_DBI_affected_rows();
420 // Grabs the profiling results
421 if (isset($_SESSION['profiling']) && PMA_profilingSupported()) {
422 $profiling_results = PMA_DBI_fetch_result('SHOW PROFILE;');
425 // Checks if the current database has changed
426 // This could happen if the user sends a query like "USE `database`;"
428 * commented out auto-switching to active database - really required?
429 * bug #1814718 win: table list disappears (mixed case db names)
430 * https://sourceforge.net/support/tracker.php?aid=1814718
431 * @todo RELEASE test and comit or rollback before release
432 $current_db = PMA_DBI_fetch_value('SELECT DATABASE()');
433 if ($db !== $current_db) {
434 $db = $current_db;
435 $reload = 1;
437 unset($current_db);
440 // tmpfile remove after convert encoding appended by Y.Kawada
441 if (function_exists('PMA_kanji_file_conv')
442 && (isset($textfile) && file_exists($textfile))) {
443 unlink($textfile);
446 // Counts the total number of rows for the same 'SELECT' query without the
447 // 'LIMIT' clause that may have been programatically added
449 if (empty($sql_limit_to_append)) {
450 $unlim_num_rows = $num_rows;
451 // if we did not append a limit, set this to get a correct
452 // "Showing rows..." message
453 //$_SESSION['tmp_user_values']['max_rows'] = 'all';
454 } elseif ($is_select) {
456 // c o u n t q u e r y
458 // If we are "just browsing", there is only one table,
459 // and no WHERE clause (or just 'WHERE 1 '),
460 // we do a quick count (which uses MaxExactCount) because
461 // SQL_CALC_FOUND_ROWS is not quick on large InnoDB tables
463 // However, do not count again if we did it previously
464 // due to $find_real_end == true
466 if (!$is_group
467 && !isset($analyzed_sql[0]['queryflags']['union'])
468 && !isset($analyzed_sql[0]['table_ref'][1]['table_name'])
469 && (empty($analyzed_sql[0]['where_clause'])
470 || $analyzed_sql[0]['where_clause'] == '1 ')
471 && !isset($find_real_end)
474 // "j u s t b r o w s i n g"
475 $unlim_num_rows = PMA_Table::countRecords($db, $table);
477 } else { // n o t " j u s t b r o w s i n g "
479 // add select expression after the SQL_CALC_FOUND_ROWS
481 // for UNION, just adding SQL_CALC_FOUND_ROWS
482 // after the first SELECT works.
484 // take the left part, could be:
485 // SELECT
486 // (SELECT
487 $count_query = PMA_SQP_formatHtml($parsed_sql, 'query_only', 0, $analyzed_sql[0]['position_of_first_select'] + 1);
488 $count_query .= ' SQL_CALC_FOUND_ROWS ';
489 // add everything that was after the first SELECT
490 $count_query .= PMA_SQP_formatHtml($parsed_sql, 'query_only', $analyzed_sql[0]['position_of_first_select']+1);
491 // ensure there is no semicolon at the end of the
492 // count query because we'll probably add
493 // a LIMIT 1 clause after it
494 $count_query = rtrim($count_query);
495 $count_query = rtrim($count_query, ';');
497 // if using SQL_CALC_FOUND_ROWS, add a LIMIT to avoid
498 // long delays. Returned count will be complete anyway.
499 // (but a LIMIT would disrupt results in an UNION)
501 if (!isset($analyzed_sql[0]['queryflags']['union'])) {
502 $count_query .= ' LIMIT 1';
505 // run the count query
507 PMA_DBI_try_query($count_query);
508 // if (mysql_error()) {
509 // void.
510 // I tried the case
511 // (SELECT `User`, `Host`, `Db`, `Select_priv` FROM `db`)
512 // UNION (SELECT `User`, `Host`, "%" AS "Db",
513 // `Select_priv`
514 // FROM `user`) ORDER BY `User`, `Host`, `Db`;
515 // and although the generated count_query is wrong
516 // the SELECT FOUND_ROWS() work! (maybe it gets the
517 // count from the latest query that worked)
519 // another case where the count_query is wrong:
520 // SELECT COUNT(*), f1 from t1 group by f1
521 // and you click to sort on count(*)
522 // }
523 $unlim_num_rows = PMA_DBI_fetch_value('SELECT FOUND_ROWS()');
524 } // end else "just browsing"
526 } else { // not $is_select
527 $unlim_num_rows = 0;
528 } // end rows total count
530 // if a table or database gets dropped, check column comments.
531 if (isset($purge) && $purge == '1') {
533 * Cleanup relations.
535 require_once './libraries/relation_cleanup.lib.php';
537 if (strlen($table) && strlen($db)) {
538 PMA_relationsCleanupTable($db, $table);
539 } elseif (strlen($db)) {
540 PMA_relationsCleanupDatabase($db);
541 } else {
542 // VOID. No DB/Table gets deleted.
543 } // end if relation-stuff
544 } // end if ($purge)
546 // If a column gets dropped, do relation magic.
547 if (isset($dropped_column) && strlen($db) && strlen($table) && !empty($dropped_column)) {
548 require_once './libraries/relation_cleanup.lib.php';
549 PMA_relationsCleanupColumn($db, $table, $dropped_column);
551 } // end if column was dropped
552 } // end else "didn't ask to see php code"
554 // No rows returned -> move back to the calling page
555 if (0 == $num_rows || $is_affected) {
556 if ($is_delete) {
557 $message = PMA_Message::deleted_rows($num_rows);
558 } elseif ($is_insert) {
559 if ($is_replace) {
560 /* For replace we get DELETED + INSERTED row count, so we have to call it affected */
561 $message = PMA_Message::affected_rows($num_rows);
562 } else {
563 $message = PMA_Message::inserted_rows($num_rows);
565 $insert_id = PMA_DBI_insert_id();
566 if ($insert_id != 0) {
567 // insert_id is id of FIRST record inserted in one insert, so if we inserted multiple rows, we had to increment this
568 $message->addMessage('[br]');
569 // need to use a temporary because the Message class
570 // currently supports adding parameters only to the first
571 // message
572 $_inserted = PMA_Message::notice(__('Inserted row id: %1$d'));
573 $_inserted->addParam($insert_id + $num_rows - 1);
574 $message->addMessage($_inserted);
576 } elseif ($is_affected) {
577 $message = PMA_Message::affected_rows($num_rows);
579 // Ok, here is an explanation for the !$is_select.
580 // The form generated by sql_query_form.lib.php
581 // and db_sql.php has many submit buttons
582 // on the same form, and some confusion arises from the
583 // fact that $message_to_show is sent for every case.
584 // The $message_to_show containing a success message and sent with
585 // the form should not have priority over errors
586 } elseif (!empty($message_to_show) && !$is_select) {
587 $message = PMA_Message::rawSuccess(htmlspecialchars($message_to_show));
588 } elseif (!empty($GLOBALS['show_as_php'])) {
589 $message = PMA_Message::success(__('Showing as PHP code'));
590 } elseif (isset($GLOBALS['show_as_php'])) {
591 /* User disable showing as PHP, query is only displayed */
592 $message = PMA_Message::notice(__('Showing SQL query'));
593 } elseif (!empty($GLOBALS['validatequery'])) {
594 $message = PMA_Message::notice(__('Validated SQL'));
595 } else {
596 $message = PMA_Message::success(__('MySQL returned an empty result set (i.e. zero rows).'));
599 if (isset($GLOBALS['querytime'])) {
600 $_querytime = PMA_Message::notice(__('Query took %01.4f sec'));
601 $_querytime->addParam($GLOBALS['querytime']);
602 $message->addMessage('(');
603 $message->addMessage($_querytime);
604 $message->addMessage(')');
607 if( $GLOBALS['is_ajax_request'] == true) {
610 * If we are in inline editing, we need to process the relational and
611 * transformed fields, if they were edited. After that, output the correct
612 * link/transformed value and exit
614 * Logic taken from libraries/display_tbl.lib.php
617 if(isset($_REQUEST['rel_fields_list']) && $_REQUEST['rel_fields_list'] != '') {
618 //handle relations work here for updated row.
619 require_once './libraries/relation.lib.php';
621 $map = PMA_getForeigners($db, $table, '', 'both');
623 $rel_fields = array();
624 parse_str($_REQUEST['rel_fields_list'], $rel_fields);
626 foreach( $rel_fields as $rel_field => $rel_field_value) {
628 $where_comparison = '=' . $rel_field_value;
629 $_url_params = array(
630 'db' => $map[$rel_field]['foreign_db'],
631 'table' => $map[$rel_field]['foreign_table'],
632 'pos' => '0',
633 'sql_query' => 'SELECT * FROM '
634 . PMA_backquote($map[$rel_field]['foreign_db']) . '.' . PMA_backquote($map[$rel_field]['foreign_table'])
635 . ' WHERE ' . PMA_backquote($map[$rel_field]['foreign_field'])
636 . $where_comparison
639 $extra_data['relations'][$rel_field] = '<a href="sql.php' . PMA_generate_common_url($_url_params) . '">';
640 $extra_data['relations'][$rel_field] .= '</a>';
644 if(isset($_REQUEST['do_transformations']) && $_REQUEST['do_transformations'] == true ) {
645 require_once './libraries/transformations.lib.php';
646 //if some posted fields need to be transformed, generate them here.
647 $mime_map = PMA_getMIME($db, $table);
649 if ($mime_map === FALSE) {
650 $mime_map = array();
653 $edited_values = array();
654 parse_str($_REQUEST['transform_fields_list'], $edited_values);
656 foreach($mime_map as $transformation) {
657 $include_file = $transformation['transformation'];
658 $column_name = $transformation['column_name'];
659 $column_data = $edited_values[$column_name];
661 $_url_params = array(
662 'db' => $db,
663 'table' => $table,
664 'where_clause' => $_REQUEST['where_clause'],
665 'transform_key' => $column_name,
668 if (file_exists('./libraries/transformations/' . $include_file)) {
669 $transformfunction_name = str_replace('.inc.php', '', $transformation['transformation']);
671 require_once './libraries/transformations/' . $include_file;
673 if (function_exists('PMA_transformation_' . $transformfunction_name)) {
674 $transform_function = 'PMA_transformation_' . $transformfunction_name;
675 $transform_options = PMA_transformation_getOptions((isset($transformation['transformation_options']) ? $transformation['transformation_options'] : ''));
676 $transform_options['wrapper_link'] = PMA_generate_common_url($_url_params);
680 $extra_data['transformations'][$column_name] = $transform_function($column_data, $transform_options);
684 if(isset($GLOBALS['display_query'])) {
685 $extra_data['sql_query'] = PMA_showMessage(NULL, $GLOBALS['display_query']);
687 if (isset($GLOBALS['reload']) && $GLOBALS['reload'] == 1) {
688 $extra_data['reload'] = 1;
689 $extra_data['db'] = $GLOBALS['db'];
691 PMA_ajaxResponse($message, $message->isSuccess(), (isset($extra_data) ? $extra_data : ''));
694 if ($is_gotofile) {
695 $goto = PMA_securePath($goto);
696 // Checks for a valid target script
697 $is_db = $is_table = false;
698 if (isset($_REQUEST['purge'])) {
699 $table = '';
700 unset($url_params['table']);
702 include 'libraries/db_table_exists.lib.php';
704 if (strpos($goto, 'tbl_') === 0 && ! $is_table) {
705 if (strlen($table)) {
706 $table = '';
708 $goto = 'db_sql.php';
710 if (strpos($goto, 'db_') === 0 && ! $is_db) {
711 if (strlen($db)) {
712 $db = '';
714 $goto = 'main.php';
716 // Loads to target script
717 if ($goto != 'main.php') {
718 require_once './libraries/header.inc.php';
720 $active_page = $goto;
721 require './' . $goto;
722 } else {
723 // avoid a redirect loop when last record was deleted
724 if (0 == $num_rows && 'sql.php' == $cfg['DefaultTabTable']) {
725 $goto = str_replace('sql.php','tbl_structure.php',$goto);
727 PMA_sendHeaderLocation($cfg['PmaAbsoluteUri'] . str_replace('&amp;', '&', $goto) . '&message=' . urlencode($message));
728 } // end else
729 exit();
730 } // end no rows returned
732 // At least one row is returned -> displays a table with results
733 else {
734 //If we are retrieving the full value of a truncated field or the original
735 // value of a transformed field, show it here and exit
736 if( $GLOBALS['inline_edit'] == true && $GLOBALS['cfg']['AjaxEnable']) {
737 $row = PMA_DBI_fetch_row($result);
738 $extra_data = array();
739 $extra_data['value'] = $row[0];
740 PMA_ajaxResponse(NULL, true, $extra_data);
743 // Displays the headers
744 if (isset($show_query)) {
745 unset($show_query);
747 if (isset($printview) && $printview == '1') {
748 require_once './libraries/header_printview.inc.php';
749 } else {
751 $GLOBALS['js_include'][] = 'functions.js';
752 $GLOBALS['js_include'][] = 'sql.js';
754 unset($message);
756 if( ! $GLOBALS['is_ajax_request'] || ! $GLOBALS['cfg']['AjaxEnable']) {
757 if (strlen($table)) {
758 require './libraries/tbl_common.php';
759 $url_query .= '&amp;goto=tbl_sql.php&amp;back=tbl_sql.php';
760 require './libraries/tbl_info.inc.php';
761 require './libraries/tbl_links.inc.php';
762 } elseif (strlen($db)) {
763 require './libraries/db_common.inc.php';
764 require './libraries/db_info.inc.php';
765 } else {
766 require './libraries/server_common.inc.php';
767 require './libraries/server_links.inc.php';
770 else {
771 //we don't need to buffer the output in PMA_showMessage here.
772 //set a global variable and check against it in the function
773 $GLOBALS['buffer_message'] = false;
777 if (strlen($db)) {
778 $cfgRelation = PMA_getRelationsParam();
781 // Gets the list of fields properties
782 if (isset($result) && $result) {
783 $fields_meta = PMA_DBI_get_fields_meta($result);
784 $fields_cnt = count($fields_meta);
787 if( ! $GLOBALS['is_ajax_request']) {
788 //begin the sqlqueryresults div here. container div
789 echo '<div id="sqlqueryresults"';
790 if ($GLOBALS['cfg']['AjaxEnable']) {
791 echo ' class="ajax"';
793 echo '>';
796 // Display previous update query (from tbl_replace)
797 if (isset($disp_query) && $cfg['ShowSQL'] == true) {
798 PMA_showMessage($disp_message, $disp_query, 'success');
801 if (isset($profiling_results)) {
802 PMA_profilingResults($profiling_results, true);
805 // Displays the results in a table
806 if (empty($disp_mode)) {
807 // see the "PMA_setDisplayMode()" function in
808 // libraries/display_tbl.lib.php
809 $disp_mode = 'urdr111101';
812 // hide edit and delete links for information_schema
813 if ($db == 'information_schema') {
814 $disp_mode = 'nnnn110111';
817 if (isset($label)) {
818 $message = PMA_message::success(__('Bookmark %s created'));
819 $message->addParam($label);
820 $message->display();
823 PMA_displayTable($result, $disp_mode, $analyzed_sql);
824 PMA_DBI_free_result($result);
826 // BEGIN INDEX CHECK See if indexes should be checked.
827 if (isset($query_type) && $query_type == 'check_tbl' && isset($selected) && is_array($selected)) {
828 foreach ($selected as $idx => $tbl_name) {
829 $check = PMA_Index::findDuplicates($tbl_name, $db);
830 if (! empty($check)) {
831 printf(__('Problems with indexes of table `%s`'), $tbl_name);
832 echo $check;
835 } // End INDEX CHECK
837 // Bookmark support if required
838 if ($disp_mode[7] == '1'
839 && (! empty($cfg['Bookmark']) && empty($id_bookmark))
840 && !empty($sql_query)) {
841 echo "\n";
843 $goto = 'sql.php?'
844 . PMA_generate_common_url($db, $table)
845 . '&amp;sql_query=' . urlencode($sql_query)
846 . '&amp;id_bookmark=1';
849 <form action="sql.php" method="post" onsubmit="return emptyFormElements(this, 'fields[label]');">
850 <?php echo PMA_generate_common_hidden_inputs(); ?>
851 <input type="hidden" name="goto" value="<?php echo $goto; ?>" />
852 <input type="hidden" name="fields[dbase]" value="<?php echo htmlspecialchars($db); ?>" />
853 <input type="hidden" name="fields[user]" value="<?php echo $cfg['Bookmark']['user']; ?>" />
854 <input type="hidden" name="fields[query]" value="<?php echo urlencode(isset($complete_query) ? $complete_query : $sql_query); ?>" />
855 <fieldset>
856 <legend><?php
857 echo ($cfg['PropertiesIconic'] ? '<img class="icon" src="' . $pmaThemeImage . 'b_bookmark.png" width="16" height="16" alt="' . __('Bookmark this SQL query') . '" />' : '')
858 . __('Bookmark this SQL query');
860 </legend>
862 <div class="formelement">
863 <label for="fields_label_"><?php echo __('Label'); ?>:</label>
864 <input type="text" id="fields_label_" name="fields[label]" value="" />
865 </div>
867 <div class="formelement">
868 <input type="checkbox" name="bkm_all_users" id="bkm_all_users" value="true" />
869 <label for="bkm_all_users"><?php echo __('Let every user access this bookmark'); ?></label>
870 </div>
872 <div class="clearfloat"></div>
873 </fieldset>
874 <fieldset class="tblFooters">
875 <input type="submit" name="store_bkm" value="<?php echo __('Bookmark this SQL query'); ?>" />
876 </fieldset>
877 </form>
878 <?php
879 } // end bookmark support
881 // Do print the page if required
882 if (isset($printview) && $printview == '1') {
884 <script type="text/javascript">
885 //<![CDATA[
886 // Do print the page
887 window.onload = function()
889 if (typeof(window.print) != 'undefined') {
890 window.print();
893 //]]>
894 </script>
895 <?php
896 } // end print case
898 if( $GLOBALS['is_ajax_request'] != true) {
899 echo '</div>'; // end sqlqueryresults div
901 } // end rows returned
904 * Displays the footer
906 require './libraries/footer.inc.php';