Fill in link to PHP doc
[phpmyadmin/mlewandow.git] / sql.php
blob427e72dbce6725081218a890ec9374c520357124
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 require_once './libraries/header.inc.php';
399 $full_err_url = (preg_match('@^(db|tbl)_@', $err_url))
400 ? $err_url . '&amp;show_query=1&amp;sql_query=' . urlencode($sql_query)
401 : $err_url;
402 PMA_mysqlDie($error, $full_sql_query, '', $full_err_url);
404 exit;
406 unset($error);
408 // Gets the number of rows affected/returned
409 // (This must be done immediately after the query because
410 // mysql_affected_rows() reports about the last query done)
412 if (!$is_affected) {
413 $num_rows = ($result) ? @PMA_DBI_num_rows($result) : 0;
414 } elseif (!isset($num_rows)) {
415 $num_rows = @PMA_DBI_affected_rows();
418 // Grabs the profiling results
419 if (isset($_SESSION['profiling']) && PMA_profilingSupported()) {
420 $profiling_results = PMA_DBI_fetch_result('SHOW PROFILE;');
423 // Checks if the current database has changed
424 // This could happen if the user sends a query like "USE `database`;"
426 * commented out auto-switching to active database - really required?
427 * bug #1814718 win: table list disappears (mixed case db names)
428 * https://sourceforge.net/support/tracker.php?aid=1814718
429 * @todo RELEASE test and comit or rollback before release
430 $current_db = PMA_DBI_fetch_value('SELECT DATABASE()');
431 if ($db !== $current_db) {
432 $db = $current_db;
433 $reload = 1;
435 unset($current_db);
438 // tmpfile remove after convert encoding appended by Y.Kawada
439 if (function_exists('PMA_kanji_file_conv')
440 && (isset($textfile) && file_exists($textfile))) {
441 unlink($textfile);
444 // Counts the total number of rows for the same 'SELECT' query without the
445 // 'LIMIT' clause that may have been programatically added
447 if (empty($sql_limit_to_append)) {
448 $unlim_num_rows = $num_rows;
449 // if we did not append a limit, set this to get a correct
450 // "Showing rows..." message
451 //$_SESSION['tmp_user_values']['max_rows'] = 'all';
452 } elseif ($is_select) {
454 // c o u n t q u e r y
456 // If we are "just browsing", there is only one table,
457 // and no WHERE clause (or just 'WHERE 1 '),
458 // we do a quick count (which uses MaxExactCount) because
459 // SQL_CALC_FOUND_ROWS is not quick on large InnoDB tables
461 // However, do not count again if we did it previously
462 // due to $find_real_end == true
464 if (!$is_group
465 && !isset($analyzed_sql[0]['queryflags']['union'])
466 && !isset($analyzed_sql[0]['table_ref'][1]['table_name'])
467 && (empty($analyzed_sql[0]['where_clause'])
468 || $analyzed_sql[0]['where_clause'] == '1 ')
469 && !isset($find_real_end)
472 // "j u s t b r o w s i n g"
473 $unlim_num_rows = PMA_Table::countRecords($db, $table);
475 } else { // n o t " j u s t b r o w s i n g "
477 // add select expression after the SQL_CALC_FOUND_ROWS
479 // for UNION, just adding SQL_CALC_FOUND_ROWS
480 // after the first SELECT works.
482 // take the left part, could be:
483 // SELECT
484 // (SELECT
485 $count_query = PMA_SQP_formatHtml($parsed_sql, 'query_only', 0, $analyzed_sql[0]['position_of_first_select'] + 1);
486 $count_query .= ' SQL_CALC_FOUND_ROWS ';
487 // add everything that was after the first SELECT
488 $count_query .= PMA_SQP_formatHtml($parsed_sql, 'query_only', $analyzed_sql[0]['position_of_first_select']+1);
489 // ensure there is no semicolon at the end of the
490 // count query because we'll probably add
491 // a LIMIT 1 clause after it
492 $count_query = rtrim($count_query);
493 $count_query = rtrim($count_query, ';');
495 // if using SQL_CALC_FOUND_ROWS, add a LIMIT to avoid
496 // long delays. Returned count will be complete anyway.
497 // (but a LIMIT would disrupt results in an UNION)
499 if (!isset($analyzed_sql[0]['queryflags']['union'])) {
500 $count_query .= ' LIMIT 1';
503 // run the count query
505 PMA_DBI_try_query($count_query);
506 // if (mysql_error()) {
507 // void.
508 // I tried the case
509 // (SELECT `User`, `Host`, `Db`, `Select_priv` FROM `db`)
510 // UNION (SELECT `User`, `Host`, "%" AS "Db",
511 // `Select_priv`
512 // FROM `user`) ORDER BY `User`, `Host`, `Db`;
513 // and although the generated count_query is wrong
514 // the SELECT FOUND_ROWS() work! (maybe it gets the
515 // count from the latest query that worked)
517 // another case where the count_query is wrong:
518 // SELECT COUNT(*), f1 from t1 group by f1
519 // and you click to sort on count(*)
520 // }
521 $unlim_num_rows = PMA_DBI_fetch_value('SELECT FOUND_ROWS()');
522 } // end else "just browsing"
524 } else { // not $is_select
525 $unlim_num_rows = 0;
526 } // end rows total count
528 // if a table or database gets dropped, check column comments.
529 if (isset($purge) && $purge == '1') {
531 * Cleanup relations.
533 require_once './libraries/relation_cleanup.lib.php';
535 if (strlen($table) && strlen($db)) {
536 PMA_relationsCleanupTable($db, $table);
537 } elseif (strlen($db)) {
538 PMA_relationsCleanupDatabase($db);
539 } else {
540 // VOID. No DB/Table gets deleted.
541 } // end if relation-stuff
542 } // end if ($purge)
544 // If a column gets dropped, do relation magic.
545 if (isset($dropped_column) && strlen($db) && strlen($table) && !empty($dropped_column)) {
546 require_once './libraries/relation_cleanup.lib.php';
547 PMA_relationsCleanupColumn($db, $table, $dropped_column);
549 } // end if column was dropped
550 } // end else "didn't ask to see php code"
552 // No rows returned -> move back to the calling page
553 if (0 == $num_rows || $is_affected) {
554 if ($is_delete) {
555 $message = PMA_Message::deleted_rows($num_rows);
556 } elseif ($is_insert) {
557 if ($is_replace) {
558 /* For replace we get DELETED + INSERTED row count, so we have to call it affected */
559 $message = PMA_Message::affected_rows($num_rows);
560 } else {
561 $message = PMA_Message::inserted_rows($num_rows);
563 $insert_id = PMA_DBI_insert_id();
564 if ($insert_id != 0) {
565 // insert_id is id of FIRST record inserted in one insert, so if we inserted multiple rows, we had to increment this
566 $message->addMessage('[br]');
567 // need to use a temporary because the Message class
568 // currently supports adding parameters only to the first
569 // message
570 $_inserted = PMA_Message::notice(__('Inserted row id: %1$d'));
571 $_inserted->addParam($insert_id + $num_rows - 1);
572 $message->addMessage($_inserted);
574 } elseif ($is_affected) {
575 $message = PMA_Message::affected_rows($num_rows);
577 // Ok, here is an explanation for the !$is_select.
578 // The form generated by sql_query_form.lib.php
579 // and db_sql.php has many submit buttons
580 // on the same form, and some confusion arises from the
581 // fact that $message_to_show is sent for every case.
582 // The $message_to_show containing a success message and sent with
583 // the form should not have priority over errors
584 } elseif (!empty($message_to_show) && !$is_select) {
585 $message = PMA_Message::rawSuccess(htmlspecialchars($message_to_show));
586 } elseif (!empty($GLOBALS['show_as_php'])) {
587 $message = PMA_Message::success(__('Showing as PHP code'));
588 } elseif (isset($GLOBALS['show_as_php'])) {
589 /* User disable showing as PHP, query is only displayed */
590 $message = PMA_Message::notice(__('Showing SQL query'));
591 } elseif (!empty($GLOBALS['validatequery'])) {
592 $message = PMA_Message::notice(__('Validated SQL'));
593 } else {
594 $message = PMA_Message::success(__('MySQL returned an empty result set (i.e. zero rows).'));
597 if (isset($GLOBALS['querytime'])) {
598 $_querytime = PMA_Message::notice(__('Query took %01.4f sec'));
599 $_querytime->addParam($GLOBALS['querytime']);
600 $message->addMessage('(');
601 $message->addMessage($_querytime);
602 $message->addMessage(')');
605 if( $GLOBALS['is_ajax_request'] == true) {
608 * If we are in inline editing, we need to process the relational and
609 * transformed fields, if they were edited. After that, output the correct
610 * link/transformed value and exit
612 * Logic taken from libraries/display_tbl.lib.php
615 if(isset($_REQUEST['rel_fields_list']) && $_REQUEST['rel_fields_list'] != '') {
616 //handle relations work here for updated row.
617 require_once './libraries/relation.lib.php';
619 $map = PMA_getForeigners($db, $table, '', 'both');
621 $rel_fields = array();
622 parse_str($_REQUEST['rel_fields_list'], $rel_fields);
624 foreach( $rel_fields as $rel_field => $rel_field_value) {
626 $where_comparison = '=' . $rel_field_value;
627 $_url_params = array(
628 'db' => $map[$rel_field]['foreign_db'],
629 'table' => $map[$rel_field]['foreign_table'],
630 'pos' => '0',
631 'sql_query' => 'SELECT * FROM '
632 . PMA_backquote($map[$rel_field]['foreign_db']) . '.' . PMA_backquote($map[$rel_field]['foreign_table'])
633 . ' WHERE ' . PMA_backquote($map[$rel_field]['foreign_field'])
634 . $where_comparison
637 $extra_data['relations'][$rel_field] = '<a href="sql.php' . PMA_generate_common_url($_url_params) . '">';
638 $extra_data['relations'][$rel_field] .= '</a>';
642 if(isset($_REQUEST['do_transformations']) && $_REQUEST['do_transformations'] == true ) {
643 require_once './libraries/transformations.lib.php';
644 //if some posted fields need to be transformed, generate them here.
645 $mime_map = PMA_getMIME($db, $table);
647 if ($mime_map === FALSE) {
648 $mime_map = array();
651 $edited_values = array();
652 parse_str($_REQUEST['transform_fields_list'], $edited_values);
654 foreach($mime_map as $transformation) {
655 $include_file = $transformation['transformation'];
656 $column_name = $transformation['column_name'];
657 $column_data = $edited_values[$column_name];
659 $_url_params = array(
660 'db' => $db,
661 'table' => $table,
662 'where_clause' => $_REQUEST['where_clause'],
663 'transform_key' => $column_name,
666 if (file_exists('./libraries/transformations/' . $include_file)) {
667 $transformfunction_name = str_replace('.inc.php', '', $transformation['transformation']);
669 require_once './libraries/transformations/' . $include_file;
671 if (function_exists('PMA_transformation_' . $transformfunction_name)) {
672 $transform_function = 'PMA_transformation_' . $transformfunction_name;
673 $transform_options = PMA_transformation_getOptions((isset($transformation['transformation_options']) ? $transformation['transformation_options'] : ''));
674 $transform_options['wrapper_link'] = PMA_generate_common_url($_url_params);
678 $extra_data['transformations'][$column_name] = $transform_function($column_data, $transform_options);
682 if(isset($GLOBALS['display_query'])) {
683 $extra_data['sql_query'] = PMA_showMessage(NULL, $GLOBALS['display_query']);
685 if (isset($GLOBALS['reload']) && $GLOBALS['reload'] == 1) {
686 $extra_data['reload'] = 1;
687 $extra_data['db'] = $GLOBALS['db'];
689 PMA_ajaxResponse($message, $message->isSuccess(), (isset($extra_data) ? $extra_data : ''));
692 if ($is_gotofile) {
693 $goto = PMA_securePath($goto);
694 // Checks for a valid target script
695 $is_db = $is_table = false;
696 if (isset($_REQUEST['purge'])) {
697 $table = '';
698 unset($url_params['table']);
700 include 'libraries/db_table_exists.lib.php';
702 if (strpos($goto, 'tbl_') === 0 && ! $is_table) {
703 if (strlen($table)) {
704 $table = '';
706 $goto = 'db_sql.php';
708 if (strpos($goto, 'db_') === 0 && ! $is_db) {
709 if (strlen($db)) {
710 $db = '';
712 $goto = 'main.php';
714 // Loads to target script
715 if ($goto != 'main.php') {
716 require_once './libraries/header.inc.php';
718 $active_page = $goto;
719 require './' . $goto;
720 } else {
721 // avoid a redirect loop when last record was deleted
722 if (0 == $num_rows && 'sql.php' == $cfg['DefaultTabTable']) {
723 $goto = str_replace('sql.php','tbl_structure.php',$goto);
725 PMA_sendHeaderLocation($cfg['PmaAbsoluteUri'] . str_replace('&amp;', '&', $goto) . '&message=' . urlencode($message));
726 } // end else
727 exit();
728 } // end no rows returned
730 // At least one row is returned -> displays a table with results
731 else {
732 //If we are retrieving the full value of a truncated field or the original
733 // value of a transformed field, show it here and exit
734 if( $GLOBALS['inline_edit'] == true && $GLOBALS['cfg']['AjaxEnable']) {
735 $row = PMA_DBI_fetch_row($result);
736 $extra_data = array();
737 $extra_data['value'] = $row[0];
738 PMA_ajaxResponse(NULL, true, $extra_data);
741 // Displays the headers
742 if (isset($show_query)) {
743 unset($show_query);
745 if (isset($printview) && $printview == '1') {
746 require_once './libraries/header_printview.inc.php';
747 } else {
749 $GLOBALS['js_include'][] = 'functions.js';
750 $GLOBALS['js_include'][] = 'sql.js';
752 unset($message);
754 if( ! $GLOBALS['is_ajax_request'] || ! $GLOBALS['cfg']['AjaxEnable']) {
755 if (strlen($table)) {
756 require './libraries/tbl_common.php';
757 $url_query .= '&amp;goto=tbl_sql.php&amp;back=tbl_sql.php';
758 require './libraries/tbl_info.inc.php';
759 require './libraries/tbl_links.inc.php';
760 } elseif (strlen($db)) {
761 require './libraries/db_common.inc.php';
762 require './libraries/db_info.inc.php';
763 } else {
764 require './libraries/server_common.inc.php';
765 require './libraries/server_links.inc.php';
768 else {
769 require_once './libraries/header.inc.php';
770 //we don't need to buffer the output in PMA_showMessage here.
771 //set a global variable and check against it in the function
772 $GLOBALS['buffer_message'] = false;
776 if (strlen($db)) {
777 $cfgRelation = PMA_getRelationsParam();
780 // Gets the list of fields properties
781 if (isset($result) && $result) {
782 $fields_meta = PMA_DBI_get_fields_meta($result);
783 $fields_cnt = count($fields_meta);
786 if( ! $GLOBALS['is_ajax_request']) {
787 //begin the sqlqueryresults div here. container div
788 echo '<div id="sqlqueryresults"';
789 if ($GLOBALS['cfg']['AjaxEnable']) {
790 echo ' class="ajax"';
792 echo '>';
795 // Display previous update query (from tbl_replace)
796 if (isset($disp_query) && $cfg['ShowSQL'] == true) {
797 PMA_showMessage($disp_message, $disp_query, 'success');
800 if (isset($profiling_results)) {
801 PMA_profilingResults($profiling_results, true);
804 // Displays the results in a table
805 if (empty($disp_mode)) {
806 // see the "PMA_setDisplayMode()" function in
807 // libraries/display_tbl.lib.php
808 $disp_mode = 'urdr111101';
811 // hide edit and delete links for information_schema
812 if ($db == 'information_schema') {
813 $disp_mode = 'nnnn110111';
816 if (isset($label)) {
817 $message = PMA_message::success(__('Bookmark %s created'));
818 $message->addParam($label);
819 $message->display();
822 PMA_displayTable($result, $disp_mode, $analyzed_sql);
823 PMA_DBI_free_result($result);
825 // BEGIN INDEX CHECK See if indexes should be checked.
826 if (isset($query_type) && $query_type == 'check_tbl' && isset($selected) && is_array($selected)) {
827 foreach ($selected as $idx => $tbl_name) {
828 $check = PMA_Index::findDuplicates($tbl_name, $db);
829 if (! empty($check)) {
830 printf(__('Problems with indexes of table `%s`'), $tbl_name);
831 echo $check;
834 } // End INDEX CHECK
836 // Bookmark support if required
837 if ($disp_mode[7] == '1'
838 && (! empty($cfg['Bookmark']) && empty($id_bookmark))
839 && !empty($sql_query)) {
840 echo "\n";
842 $goto = 'sql.php?'
843 . PMA_generate_common_url($db, $table)
844 . '&amp;sql_query=' . urlencode($sql_query)
845 . '&amp;id_bookmark=1';
848 <form action="sql.php" method="post" onsubmit="return emptyFormElements(this, 'fields[label]');">
849 <?php echo PMA_generate_common_hidden_inputs(); ?>
850 <input type="hidden" name="goto" value="<?php echo $goto; ?>" />
851 <input type="hidden" name="fields[dbase]" value="<?php echo htmlspecialchars($db); ?>" />
852 <input type="hidden" name="fields[user]" value="<?php echo $cfg['Bookmark']['user']; ?>" />
853 <input type="hidden" name="fields[query]" value="<?php echo urlencode(isset($complete_query) ? $complete_query : $sql_query); ?>" />
854 <fieldset>
855 <legend><?php
856 echo ($cfg['PropertiesIconic'] ? '<img class="icon" src="' . $pmaThemeImage . 'b_bookmark.png" width="16" height="16" alt="' . __('Bookmark this SQL query') . '" />' : '')
857 . __('Bookmark this SQL query');
859 </legend>
861 <div class="formelement">
862 <label for="fields_label_"><?php echo __('Label'); ?>:</label>
863 <input type="text" id="fields_label_" name="fields[label]" value="" />
864 </div>
866 <div class="formelement">
867 <input type="checkbox" name="bkm_all_users" id="bkm_all_users" value="true" />
868 <label for="bkm_all_users"><?php echo __('Let every user access this bookmark'); ?></label>
869 </div>
871 <div class="clearfloat"></div>
872 </fieldset>
873 <fieldset class="tblFooters">
874 <input type="submit" name="store_bkm" value="<?php echo __('Bookmark this SQL query'); ?>" />
875 </fieldset>
876 </form>
877 <?php
878 } // end bookmark support
880 // Do print the page if required
881 if (isset($printview) && $printview == '1') {
883 <script type="text/javascript">
884 //<![CDATA[
885 // Do print the page
886 window.onload = function()
888 if (typeof(window.print) != 'undefined') {
889 window.print();
892 //]]>
893 </script>
894 <?php
895 } // end print case
897 if( $GLOBALS['is_ajax_request'] != true) {
898 echo '</div>'; // end sqlqueryresults div
900 } // end rows returned
903 * Displays the footer
905 require './libraries/footer.inc.php';