Translation update done using Pootle.
[phpmyadmin.git] / sql.php
blob96fc6b506fcdde2978396626e053fc639778f86c
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'][] = 'jquery/timepicker.js';
19 $GLOBALS['js_include'][] = 'tbl_change.js';
20 $GLOBALS['js_include'][] = 'gis_data_editor.js';
22 if (isset($_SESSION['profiling'])) {
23 $GLOBALS['js_include'][] = 'highcharts/highcharts.js';
24 /* Files required for chart exporting */
25 $GLOBALS['js_include'][] = 'highcharts/exporting.js';
26 /* < IE 9 doesn't support canvas natively */
27 if (PMA_USR_BROWSER_AGENT == 'IE' && PMA_USR_BROWSER_VER < 9) {
28 $GLOBALS['js_include'][] = 'canvg/flashcanvas.js';
30 $GLOBALS['js_include'][] = 'canvg/canvg.js';
33 /**
34 * Defines the url to return to in case of error in a sql statement
36 // Security checkings
37 if (! empty($goto)) {
38 $is_gotofile = preg_replace('@^([^?]+).*$@s', '\\1', $goto);
39 if (! @file_exists('./' . $is_gotofile)) {
40 unset($goto);
41 } else {
42 $is_gotofile = ($is_gotofile == $goto);
44 } else {
45 $goto = (! strlen($table)) ? $cfg['DefaultTabDatabase'] : $cfg['DefaultTabTable'];
46 $is_gotofile = true;
47 } // end if
49 if (! isset($err_url)) {
50 $err_url = (! empty($back) ? $back : $goto)
51 . '?' . PMA_generate_common_url($db)
52 . ((strpos(' ' . $goto, 'db_') != 1 && strlen($table)) ? '&amp;table=' . urlencode($table) : '');
53 } // end if
55 // Coming from a bookmark dialog
56 if (isset($fields['query'])) {
57 $sql_query = $fields['query'];
60 // This one is just to fill $db
61 if (isset($fields['dbase'])) {
62 $db = $fields['dbase'];
65 /**
66 * During grid edit, if we have a relational field, show the dropdown for it
68 * Logic taken from libraries/display_tbl_lib.php
70 * This doesn't seem to be the right place to do this, but I can't think of any
71 * better place either.
73 if (isset($_REQUEST['get_relational_values']) && $_REQUEST['get_relational_values'] == true) {
74 include_once 'libraries/relation.lib.php';
76 $column = $_REQUEST['column'];
77 $foreigners = PMA_getForeigners($db, $table, $column);
79 $display_field = PMA_getDisplayField($foreigners[$column]['foreign_db'], $foreigners[$column]['foreign_table']);
81 $foreignData = PMA_getForeignData($foreigners, $column, false, '', '');
83 if ($_SESSION['tmp_user_values']['relational_display'] == 'D'
84 && isset($display_field)
85 && strlen($display_field)
86 && isset($_REQUEST['relation_key_or_display_column'])
87 && $_REQUEST['relation_key_or_display_column']
88 ) {
89 $curr_value = $_REQUEST['relation_key_or_display_column'];
90 } else {
91 $curr_value = $_REQUEST['curr_value'];
93 if ($foreignData['disp_row'] == null) {
94 //Handle the case when number of values is more than $cfg['ForeignKeyMaxLimit']
95 $_url_params = array(
96 'db' => $db,
97 'table' => $table,
98 'field' => $column
101 $dropdown = '<span class="curr_value">' . htmlspecialchars($_REQUEST['curr_value']) . '</span> <a href="browse_foreigners.php' . PMA_generate_common_url($_url_params) . '"'
102 . ' target="_blank" class="browse_foreign" '
103 .'>' . __('Browse foreign values') . '</a>';
104 } else {
105 $dropdown = PMA_foreignDropdown($foreignData['disp_row'], $foreignData['foreign_field'], $foreignData['foreign_display'], $curr_value, $cfg['ForeignKeyMaxLimit']);
106 $dropdown = '<select>' . $dropdown . '</select>';
109 $extra_data['dropdown'] = $dropdown;
110 PMA_ajaxResponse(null, true, $extra_data);
114 * Just like above, find possible values for enum fields during grid edit.
116 * Logic taken from libraries/display_tbl_lib.php
118 if (isset($_REQUEST['get_enum_values']) && $_REQUEST['get_enum_values'] == true) {
119 $field_info_query = PMA_DBI_get_columns_sql($db, $table, $_REQUEST['column']);
121 $field_info_result = PMA_DBI_fetch_result($field_info_query, null, null, null, PMA_DBI_QUERY_STORE);
123 $search = array('enum', '(', ')', "'");
125 $values = explode(',', str_replace($search, '', $field_info_result[0]['Type']));
127 $dropdown = '<option value="">&nbsp;</option>';
128 foreach ($values as $value) {
129 $dropdown .= '<option value="' . htmlspecialchars($value) . '"';
130 if ($value == $_REQUEST['curr_value']) {
131 $dropdown .= ' selected="selected"';
133 $dropdown .= '>' . $value . '</option>';
136 $dropdown = '<select>' . $dropdown . '</select>';
138 $extra_data['dropdown'] = $dropdown;
139 PMA_ajaxResponse(null, true, $extra_data);
143 * Find possible values for set fields during grid edit.
145 if (isset($_REQUEST['get_set_values']) && $_REQUEST['get_set_values'] == true) {
146 $field_info_query = PMA_DBI_get_columns_sql($db, $table, $_REQUEST['column']);
148 $field_info_result = PMA_DBI_fetch_result($field_info_query, null, null, null, PMA_DBI_QUERY_STORE);
150 $selected_values = explode(',', $_REQUEST['curr_value']);
152 $search = array('set', '(', ')', "'");
153 $values = explode(',', str_replace($search, '', $field_info_result[0]['Type']));
155 $select = '';
156 foreach ($values as $value) {
157 $select .= '<option value="' . htmlspecialchars($value) . '"';
158 if (in_array($value, $selected_values, true)) {
159 $select .= ' selected="selected"';
161 $select .= '>' . $value . '</option>';
164 $select_size = (sizeof($values) > 10) ? 10 : sizeof($values);
165 $select = '<select multiple="multiple" size="' . $select_size . '">' . $select . '</select>';
167 $extra_data['select'] = $select;
168 PMA_ajaxResponse(null, true, $extra_data);
172 * Check ajax request to set the column order
174 if (isset($_REQUEST['set_col_prefs']) && $_REQUEST['set_col_prefs'] == true) {
175 $pmatable = new PMA_Table($table, $db);
176 $retval = false;
178 // set column order
179 if (isset($_REQUEST['col_order'])) {
180 $col_order = explode(',', $_REQUEST['col_order']);
181 $retval = $pmatable->setUiProp(PMA_Table::PROP_COLUMN_ORDER, $col_order, $_REQUEST['table_create_time']);
182 if (gettype($retval) != 'boolean') {
183 PMA_ajaxResponse($retval->getString(), false);
187 // set column visibility
188 if ($retval === true && isset($_REQUEST['col_visib'])) {
189 $col_visib = explode(',', $_REQUEST['col_visib']);
190 $retval = $pmatable->setUiProp(PMA_Table::PROP_COLUMN_VISIB, $col_visib, $_REQUEST['table_create_time']);
191 if (gettype($retval) != 'boolean') {
192 PMA_ajaxResponse($retval->getString(), false);
196 PMA_ajaxResponse(null, ($retval == true));
199 // Default to browse if no query set and we have table
200 // (needed for browsing from DefaultTabTable)
201 if (empty($sql_query) && strlen($table) && strlen($db)) {
202 include_once './libraries/bookmark.lib.php';
203 $book_sql_query = PMA_Bookmark_get(
204 $db,
205 '\'' . PMA_sqlAddSlashes($table) . '\'',
206 'label',
207 false,
208 true
211 if (! empty($book_sql_query)) {
212 $GLOBALS['using_bookmark_message'] = PMA_message::notice(__('Using bookmark "%s" as default browse query.'));
213 $GLOBALS['using_bookmark_message']->addParam($table);
214 $GLOBALS['using_bookmark_message']->addMessage(PMA_showDocu('faq6_22'));
215 $sql_query = $book_sql_query;
216 } else {
217 $sql_query = 'SELECT * FROM ' . PMA_backquote($table);
219 unset($book_sql_query);
221 // set $goto to what will be displayed if query returns 0 rows
222 $goto = 'tbl_structure.php';
223 } else {
224 // Now we can check the parameters
225 PMA_checkParameters(array('sql_query'));
228 // instead of doing the test twice
229 $is_drop_database = preg_match(
230 '/DROP[[:space:]]+(DATABASE|SCHEMA)[[:space:]]+/i',
231 $sql_query
235 * Check rights in case of DROP DATABASE
237 * This test may be bypassed if $is_js_confirmed = 1 (already checked with js)
238 * but since a malicious user may pass this variable by url/form, we don't take
239 * into account this case.
241 if (! defined('PMA_CHK_DROP')
242 && ! $cfg['AllowUserDropDatabase']
243 && $is_drop_database
244 && ! $is_superuser
246 include_once './libraries/header.inc.php';
247 PMA_mysqlDie(__('"DROP DATABASE" statements are disabled.'), '', '', $err_url);
248 } // end if
250 require_once './libraries/display_tbl.lib.php';
251 PMA_displayTable_checkConfigParams();
254 * Need to find the real end of rows?
256 if (isset($find_real_end) && $find_real_end) {
257 $unlim_num_rows = PMA_Table::countRecords($db, $table, $force_exact = true);
258 $_SESSION['tmp_user_values']['pos'] = @((ceil($unlim_num_rows / $_SESSION['tmp_user_values']['max_rows']) - 1) * $_SESSION['tmp_user_values']['max_rows']);
263 * Bookmark add
265 if (isset($store_bkm)) {
266 PMA_Bookmark_save($fields, (isset($bkm_all_users) && $bkm_all_users == 'true' ? true : false));
267 // go back to sql.php to redisplay query; do not use &amp; in this case:
268 PMA_sendHeaderLocation($cfg['PmaAbsoluteUri'] . $goto . '&label=' . $fields['label']);
269 } // end if
272 * Parse and analyze the query
274 require_once './libraries/parse_analyze.lib.php';
277 * Sets or modifies the $goto variable if required
279 if ($goto == 'sql.php') {
280 $is_gotofile = false;
281 $goto = 'sql.php?'
282 . PMA_generate_common_url($db, $table)
283 . '&amp;sql_query=' . urlencode($sql_query);
284 } // end if
288 * Go back to further page if table should not be dropped
290 if (isset($btnDrop) && $btnDrop == __('No')) {
291 if (! empty($back)) {
292 $goto = $back;
294 if ($is_gotofile) {
295 if (strpos($goto, 'db_') === 0 && strlen($table)) {
296 $table = '';
298 $active_page = $goto;
299 include './' . PMA_securePath($goto);
300 } else {
301 PMA_sendHeaderLocation($cfg['PmaAbsoluteUri'] . str_replace('&amp;', '&', $goto));
303 exit();
304 } // end if
308 * Displays the confirm page if required
310 * This part of the script is bypassed if $is_js_confirmed = 1 (already checked
311 * with js) because possible security issue is not so important here: at most,
312 * the confirm message isn't displayed.
314 * Also bypassed if only showing php code.or validating a SQL query
316 if (! $cfg['Confirm']
317 || isset($_REQUEST['is_js_confirmed'])
318 || isset($btnDrop)
319 // if we are coming from a "Create PHP code" or a "Without PHP Code"
320 // dialog, we won't execute the query anyway, so don't confirm
321 || isset($GLOBALS['show_as_php'])
322 || ! empty($GLOBALS['validatequery'])
324 $do_confirm = false;
325 } else {
326 $do_confirm = isset($analyzed_sql[0]['queryflags']['need_confirm']);
329 if ($do_confirm) {
330 $stripped_sql_query = $sql_query;
331 include_once './libraries/header.inc.php';
332 if ($is_drop_database) {
333 echo '<h1 class="error">' . __('You are about to DESTROY a complete database!') . '</h1>';
335 echo '<form action="sql.php" method="post">' . "\n"
336 .PMA_generate_common_hidden_inputs($db, $table);
338 <input type="hidden" name="sql_query" value="<?php echo htmlspecialchars($sql_query); ?>" />
339 <input type="hidden" name="message_to_show" value="<?php echo isset($message_to_show) ? PMA_sanitize($message_to_show, true) : ''; ?>" />
340 <input type="hidden" name="goto" value="<?php echo $goto; ?>" />
341 <input type="hidden" name="back" value="<?php echo isset($back) ? PMA_sanitize($back, true) : ''; ?>" />
342 <input type="hidden" name="reload" value="<?php echo isset($reload) ? PMA_sanitize($reload, true) : 0; ?>" />
343 <input type="hidden" name="purge" value="<?php echo isset($purge) ? PMA_sanitize($purge, true) : ''; ?>" />
344 <input type="hidden" name="dropped_column" value="<?php echo isset($dropped_column) ? PMA_sanitize($dropped_column, true) : ''; ?>" />
345 <input type="hidden" name="show_query" value="<?php echo isset($show_query) ? PMA_sanitize($show_query, true) : ''; ?>" />
346 <?php
347 echo '<fieldset class="confirmation">' . "\n"
348 .' <legend>' . __('Do you really want to ') . '</legend>'
349 .' <tt>' . htmlspecialchars($stripped_sql_query) . '</tt>' . "\n"
350 .'</fieldset>' . "\n"
351 .'<fieldset class="tblFooters">' . "\n";
353 <input type="submit" name="btnDrop" value="<?php echo __('Yes'); ?>" id="buttonYes" />
354 <input type="submit" name="btnDrop" value="<?php echo __('No'); ?>" id="buttonNo" />
355 <?php
356 echo '</fieldset>' . "\n"
357 . '</form>' . "\n";
360 * Displays the footer and exit
362 include './libraries/footer.inc.php';
363 } // end if $do_confirm
366 // Defines some variables
367 // A table has to be created, renamed, dropped -> navi frame should be reloaded
369 * @todo use the parser/analyzer
372 if (empty($reload)
373 && preg_match('/^(CREATE|ALTER|DROP)\s+(VIEW|TABLE|DATABASE|SCHEMA)\s+/i', $sql_query)
375 $reload = 1;
378 // SK -- Patch: $is_group added for use in calculation of total number of
379 // rows.
380 // $is_count is changed for more correct "LIMIT" clause
381 // appending in queries like
382 // "SELECT COUNT(...) FROM ... GROUP BY ..."
385 * @todo detect all this with the parser, to avoid problems finding
386 * those strings in comments or backquoted identifiers
389 $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;
390 if ($is_select) { // see line 141
391 $is_group = preg_match('@(GROUP[[:space:]]+BY|HAVING|SELECT[[:space:]]+DISTINCT)[[:space:]]+@i', $sql_query);
392 $is_func = ! $is_group && (preg_match('@[[:space:]]+(SUM|AVG|STD|STDDEV|MIN|MAX|BIT_OR|BIT_AND)\s*\(@i', $sql_query));
393 $is_count = ! $is_group && (preg_match('@^SELECT[[:space:]]+COUNT\((.*\.+)?.*\)@i', $sql_query));
394 $is_export = (preg_match('@[[:space:]]+INTO[[:space:]]+OUTFILE[[:space:]]+@i', $sql_query));
395 $is_analyse = (preg_match('@[[:space:]]+PROCEDURE[[:space:]]+ANALYSE@i', $sql_query));
396 } elseif (preg_match('@^EXPLAIN[[:space:]]+@i', $sql_query)) {
397 $is_explain = true;
398 } elseif (preg_match('@^DELETE[[:space:]]+@i', $sql_query)) {
399 $is_delete = true;
400 $is_affected = true;
401 } elseif (preg_match('@^(INSERT|LOAD[[:space:]]+DATA|REPLACE)[[:space:]]+@i', $sql_query)) {
402 $is_insert = true;
403 $is_affected = true;
404 if (preg_match('@^(REPLACE)[[:space:]]+@i', $sql_query)) {
405 $is_replace = true;
407 } elseif (preg_match('@^UPDATE[[:space:]]+@i', $sql_query)) {
408 $is_affected = true;
409 } elseif (preg_match('@^[[:space:]]*SHOW[[:space:]]+@i', $sql_query)) {
410 $is_show = true;
411 } elseif (preg_match('@^(CHECK|ANALYZE|REPAIR|OPTIMIZE)[[:space:]]+TABLE[[:space:]]+@i', $sql_query)) {
412 $is_maint = true;
415 // assign default full_sql_query
416 $full_sql_query = $sql_query;
418 // Handle remembered sorting order, only for single table query
419 if ($GLOBALS['cfg']['RememberSorting']
420 && ! ($is_count || $is_export || $is_func || $is_analyse)
421 && count($analyzed_sql[0]['select_expr']) == 0
422 && isset($analyzed_sql[0]['queryflags']['select_from'])
423 && count($analyzed_sql[0]['table_ref']) == 1
425 $pmatable = new PMA_Table($table, $db);
426 if (empty($analyzed_sql[0]['order_by_clause'])) {
427 $sorted_col = $pmatable->getUiProp(PMA_Table::PROP_SORTED_COLUMN);
428 if ($sorted_col) {
429 // retrieve the remembered sorting order for current table
430 $sql_order_to_append = ' ORDER BY ' . $sorted_col . ' ';
431 $full_sql_query = $analyzed_sql[0]['section_before_limit'] . $sql_order_to_append
432 . $analyzed_sql[0]['section_after_limit'];
434 // update the $analyzed_sql
435 $analyzed_sql[0]['section_before_limit'] .= $sql_order_to_append;
436 $analyzed_sql[0]['order_by_clause'] = $sorted_col;
438 } else {
439 // store the remembered table into session
440 $pmatable->setUiProp(PMA_Table::PROP_SORTED_COLUMN, $analyzed_sql[0]['order_by_clause']);
444 // Do append a "LIMIT" clause?
445 if ((! $cfg['ShowAll'] || $_SESSION['tmp_user_values']['max_rows'] != 'all')
446 && ! ($is_count || $is_export || $is_func || $is_analyse)
447 && isset($analyzed_sql[0]['queryflags']['select_from'])
448 && ! isset($analyzed_sql[0]['queryflags']['offset'])
449 && empty($analyzed_sql[0]['limit_clause'])
451 $sql_limit_to_append = ' LIMIT ' . $_SESSION['tmp_user_values']['pos']
452 . ', ' . $_SESSION['tmp_user_values']['max_rows'] . " ";
454 $full_sql_query = $analyzed_sql[0]['section_before_limit'] . "\n"
455 . $sql_limit_to_append . $analyzed_sql[0]['section_after_limit'];
457 * @todo pretty printing of this modified query
459 if (isset($display_query)) {
460 // if the analysis of the original query revealed that we found
461 // a section_after_limit, we now have to analyze $display_query
462 // to display it correctly
464 if (! empty($analyzed_sql[0]['section_after_limit'])
465 && trim($analyzed_sql[0]['section_after_limit']) != ';'
467 $analyzed_display_query = PMA_SQP_analyze(PMA_SQP_parse($display_query));
468 $display_query = $analyzed_display_query[0]['section_before_limit']
469 . "\n" . $sql_limit_to_append . $analyzed_display_query[0]['section_after_limit'];
475 if (strlen($db)) {
476 PMA_DBI_select_db($db);
479 // E x e c u t e t h e q u e r y
481 // Only if we didn't ask to see the php code (mikebeck)
482 if (isset($GLOBALS['show_as_php']) || ! empty($GLOBALS['validatequery'])) {
483 unset($result);
484 $num_rows = 0;
485 $unlim_num_rows = 0;
486 } else {
487 if (isset($_SESSION['profiling']) && PMA_profilingSupported()) {
488 PMA_DBI_query('SET PROFILING=1;');
491 // Measure query time.
492 $querytime_before = array_sum(explode(' ', microtime()));
494 $result = @PMA_DBI_try_query($full_sql_query, null, PMA_DBI_QUERY_STORE);
496 // If a stored procedure was called, there may be more results that are
497 // queued up and waiting to be flushed from the buffer. So let's do that.
498 while (true) {
499 if (! PMA_DBI_more_results()) {
500 break;
502 PMA_DBI_next_result();
505 $querytime_after = array_sum(explode(' ', microtime()));
507 $GLOBALS['querytime'] = $querytime_after - $querytime_before;
509 // Displays an error message if required and stop parsing the script
510 if ($error = PMA_DBI_getError()) {
511 if ($is_gotofile) {
512 if (strpos($goto, 'db_') === 0 && strlen($table)) {
513 $table = '';
515 $active_page = $goto;
516 $message = PMA_Message::rawError($error);
518 if ($GLOBALS['is_ajax_request'] == true) {
519 PMA_ajaxResponse($message, false);
523 * Go to target path.
525 include './' . PMA_securePath($goto);
526 } else {
527 $full_err_url = (preg_match('@^(db|tbl)_@', $err_url))
528 ? $err_url . '&amp;show_query=1&amp;sql_query=' . urlencode($sql_query)
529 : $err_url;
530 PMA_mysqlDie($error, $full_sql_query, '', $full_err_url);
532 exit;
534 unset($error);
536 // Gets the number of rows affected/returned
537 // (This must be done immediately after the query because
538 // mysql_affected_rows() reports about the last query done)
540 if (! $is_affected) {
541 $num_rows = ($result) ? @PMA_DBI_num_rows($result) : 0;
542 } elseif (! isset($num_rows)) {
543 $num_rows = @PMA_DBI_affected_rows();
546 // Grabs the profiling results
547 if (isset($_SESSION['profiling']) && PMA_profilingSupported()) {
548 $profiling_results = PMA_DBI_fetch_result('SHOW PROFILE;');
551 // Checks if the current database has changed
552 // This could happen if the user sends a query like "USE `database`;"
554 * commented out auto-switching to active database - really required?
555 * bug #1814718 win: table list disappears (mixed case db names)
556 * https://sourceforge.net/support/tracker.php?aid=1814718
557 * @todo RELEASE test and comit or rollback before release
558 $current_db = PMA_DBI_fetch_value('SELECT DATABASE()');
559 if ($db !== $current_db) {
560 $db = $current_db;
561 $reload = 1;
563 unset($current_db);
566 // tmpfile remove after convert encoding appended by Y.Kawada
567 if (function_exists('PMA_kanji_file_conv')
568 && (isset($textfile) && file_exists($textfile))
570 unlink($textfile);
573 // Counts the total number of rows for the same 'SELECT' query without the
574 // 'LIMIT' clause that may have been programatically added
576 if (empty($sql_limit_to_append)) {
577 $unlim_num_rows = $num_rows;
578 // if we did not append a limit, set this to get a correct
579 // "Showing rows..." message
580 //$_SESSION['tmp_user_values']['max_rows'] = 'all';
581 } elseif ($is_select) {
583 // c o u n t q u e r y
585 // If we are "just browsing", there is only one table,
586 // and no WHERE clause (or just 'WHERE 1 '),
587 // we do a quick count (which uses MaxExactCount) because
588 // SQL_CALC_FOUND_ROWS is not quick on large InnoDB tables
590 // However, do not count again if we did it previously
591 // due to $find_real_end == true
593 if (! $is_group
594 && ! isset($analyzed_sql[0]['queryflags']['union'])
595 && ! isset($analyzed_sql[0]['table_ref'][1]['table_name'])
596 && (empty($analyzed_sql[0]['where_clause']) || $analyzed_sql[0]['where_clause'] == '1 ')
597 && ! isset($find_real_end)
600 // "j u s t b r o w s i n g"
601 $unlim_num_rows = PMA_Table::countRecords($db, $table);
603 } else { // n o t " j u s t b r o w s i n g "
605 // add select expression after the SQL_CALC_FOUND_ROWS
607 // for UNION, just adding SQL_CALC_FOUND_ROWS
608 // after the first SELECT works.
610 // take the left part, could be:
611 // SELECT
612 // (SELECT
613 $count_query = PMA_SQP_formatHtml($parsed_sql, 'query_only', 0, $analyzed_sql[0]['position_of_first_select'] + 1);
614 $count_query .= ' SQL_CALC_FOUND_ROWS ';
615 // add everything that was after the first SELECT
616 $count_query .= PMA_SQP_formatHtml($parsed_sql, 'query_only', $analyzed_sql[0]['position_of_first_select'] + 1);
617 // ensure there is no semicolon at the end of the
618 // count query because we'll probably add
619 // a LIMIT 1 clause after it
620 $count_query = rtrim($count_query);
621 $count_query = rtrim($count_query, ';');
623 // if using SQL_CALC_FOUND_ROWS, add a LIMIT to avoid
624 // long delays. Returned count will be complete anyway.
625 // (but a LIMIT would disrupt results in an UNION)
627 if (! isset($analyzed_sql[0]['queryflags']['union'])) {
628 $count_query .= ' LIMIT 1';
631 // run the count query
633 PMA_DBI_try_query($count_query);
634 // if (mysql_error()) {
635 // void.
636 // I tried the case
637 // (SELECT `User`, `Host`, `Db`, `Select_priv` FROM `db`)
638 // UNION (SELECT `User`, `Host`, "%" AS "Db",
639 // `Select_priv`
640 // FROM `user`) ORDER BY `User`, `Host`, `Db`;
641 // and although the generated count_query is wrong
642 // the SELECT FOUND_ROWS() work! (maybe it gets the
643 // count from the latest query that worked)
645 // another case where the count_query is wrong:
646 // SELECT COUNT(*), f1 from t1 group by f1
647 // and you click to sort on count(*)
648 // }
649 $unlim_num_rows = PMA_DBI_fetch_value('SELECT FOUND_ROWS()');
650 } // end else "just browsing"
652 } else { // not $is_select
653 $unlim_num_rows = 0;
654 } // end rows total count
656 // if a table or database gets dropped, check column comments.
657 if (isset($purge) && $purge == '1') {
659 * Cleanup relations.
661 include_once './libraries/relation_cleanup.lib.php';
663 if (strlen($table) && strlen($db)) {
664 PMA_relationsCleanupTable($db, $table);
665 } elseif (strlen($db)) {
666 PMA_relationsCleanupDatabase($db);
667 } else {
668 // VOID. No DB/Table gets deleted.
669 } // end if relation-stuff
670 } // end if ($purge)
672 // If a column gets dropped, do relation magic.
673 if (isset($dropped_column) && strlen($db) && strlen($table) && ! empty($dropped_column)) {
674 include_once './libraries/relation_cleanup.lib.php';
675 PMA_relationsCleanupColumn($db, $table, $dropped_column);
677 } // end if column was dropped
678 } // end else "didn't ask to see php code"
680 // No rows returned -> move back to the calling page
681 if ((0 == $num_rows && 0 == $unlim_num_rows) || $is_affected) {
682 if ($is_delete) {
683 $message = PMA_Message::deleted_rows($num_rows);
684 } elseif ($is_insert) {
685 if ($is_replace) {
686 /* For replace we get DELETED + INSERTED row count, so we have to call it affected */
687 $message = PMA_Message::affected_rows($num_rows);
688 } else {
689 $message = PMA_Message::inserted_rows($num_rows);
691 $insert_id = PMA_DBI_insert_id();
692 if ($insert_id != 0) {
693 // insert_id is id of FIRST record inserted in one insert, so if we inserted multiple rows, we had to increment this
694 $message->addMessage('[br]');
695 // need to use a temporary because the Message class
696 // currently supports adding parameters only to the first
697 // message
698 $_inserted = PMA_Message::notice(__('Inserted row id: %1$d'));
699 $_inserted->addParam($insert_id + $num_rows - 1);
700 $message->addMessage($_inserted);
702 } elseif ($is_affected) {
703 $message = PMA_Message::affected_rows($num_rows);
705 // Ok, here is an explanation for the !$is_select.
706 // The form generated by sql_query_form.lib.php
707 // and db_sql.php has many submit buttons
708 // on the same form, and some confusion arises from the
709 // fact that $message_to_show is sent for every case.
710 // The $message_to_show containing a success message and sent with
711 // the form should not have priority over errors
712 } elseif (! empty($message_to_show) && ! $is_select) {
713 $message = PMA_Message::rawSuccess(htmlspecialchars($message_to_show));
714 } elseif (! empty($GLOBALS['show_as_php'])) {
715 $message = PMA_Message::success(__('Showing as PHP code'));
716 } elseif (isset($GLOBALS['show_as_php'])) {
717 /* User disable showing as PHP, query is only displayed */
718 $message = PMA_Message::notice(__('Showing SQL query'));
719 } elseif (! empty($GLOBALS['validatequery'])) {
720 $message = PMA_Message::notice(__('Validated SQL'));
721 } else {
722 $message = PMA_Message::success(__('MySQL returned an empty result set (i.e. zero rows).'));
725 if (isset($GLOBALS['querytime'])) {
726 $_querytime = PMA_Message::notice(__('Query took %01.4f sec'));
727 $_querytime->addParam($GLOBALS['querytime']);
728 $message->addMessage('(');
729 $message->addMessage($_querytime);
730 $message->addMessage(')');
733 if ($GLOBALS['is_ajax_request'] == true) {
734 if ($cfg['ShowSQL']) {
735 $extra_data['sql_query'] = PMA_showMessage($message, $GLOBALS['sql_query'], 'success');
737 if (isset($GLOBALS['reload']) && $GLOBALS['reload'] == 1) {
738 $extra_data['reload'] = 1;
739 $extra_data['db'] = $GLOBALS['db'];
741 PMA_ajaxResponse($message, $message->isSuccess(), (isset($extra_data) ? $extra_data : ''));
744 if ($is_gotofile) {
745 $goto = PMA_securePath($goto);
746 // Checks for a valid target script
747 $is_db = $is_table = false;
748 if (isset($_REQUEST['purge']) && $_REQUEST['purge'] == '1') {
749 $table = '';
750 unset($url_params['table']);
752 include 'libraries/db_table_exists.lib.php';
754 if (strpos($goto, 'tbl_') === 0 && ! $is_table) {
755 if (strlen($table)) {
756 $table = '';
758 $goto = 'db_sql.php';
760 if (strpos($goto, 'db_') === 0 && ! $is_db) {
761 if (strlen($db)) {
762 $db = '';
764 $goto = 'main.php';
766 // Loads to target script
767 if ($goto != 'main.php') {
768 include_once './libraries/header.inc.php';
770 $active_page = $goto;
771 include './' . $goto;
772 } else {
773 // avoid a redirect loop when last record was deleted
774 if (0 == $num_rows && 'sql.php' == $cfg['DefaultTabTable']) {
775 $goto = str_replace('sql.php', 'tbl_structure.php', $goto);
777 PMA_sendHeaderLocation($cfg['PmaAbsoluteUri'] . str_replace('&amp;', '&', $goto) . '&message=' . urlencode($message));
778 } // end else
779 exit();
780 } // end no rows returned
782 // At least one row is returned -> displays a table with results
783 else {
784 //If we are retrieving the full value of a truncated field or the original
785 // value of a transformed field, show it here and exit
786 if ($GLOBALS['grid_edit'] == true && $GLOBALS['cfg']['AjaxEnable']) {
787 $row = PMA_DBI_fetch_row($result);
788 $extra_data = array();
789 $extra_data['value'] = $row[0];
790 PMA_ajaxResponse(null, true, $extra_data);
793 if (isset($_REQUEST['ajax_request']) && isset($_REQUEST['table_maintenance'])) {
794 $GLOBALS['js_include'][] = 'functions.js';
795 $GLOBALS['js_include'][] = 'makegrid.js';
796 $GLOBALS['js_include'][] = 'sql.js';
798 // Gets the list of fields properties
799 if (isset($result) && $result) {
800 $fields_meta = PMA_DBI_get_fields_meta($result);
801 $fields_cnt = count($fields_meta);
804 if (empty($disp_mode)) {
805 // see the "PMA_setDisplayMode()" function in
806 // libraries/display_tbl.lib.php
807 $disp_mode = 'urdr111101';
810 // hide edit and delete links for information_schema
811 if (PMA_is_system_schema($db)) {
812 $disp_mode = 'nnnn110111';
815 $message = PMA_Message::success($message);
816 echo PMA_showMessage($message, $GLOBALS['sql_query'], 'success');
817 PMA_displayTable($result, $disp_mode, $analyzed_sql);
818 exit();
821 // Displays the headers
822 if (isset($show_query)) {
823 unset($show_query);
825 if (isset($printview) && $printview == '1') {
826 include_once './libraries/header_printview.inc.php';
827 } else {
829 $GLOBALS['js_include'][] = 'functions.js';
830 $GLOBALS['js_include'][] = 'makegrid.js';
831 $GLOBALS['js_include'][] = 'sql.js';
833 unset($message);
835 if (! $GLOBALS['is_ajax_request'] || ! $GLOBALS['cfg']['AjaxEnable']) {
836 if (strlen($table)) {
837 include './libraries/tbl_common.php';
838 $url_query .= '&amp;goto=tbl_sql.php&amp;back=tbl_sql.php';
839 include './libraries/tbl_info.inc.php';
840 include './libraries/tbl_links.inc.php';
841 } elseif (strlen($db)) {
842 include './libraries/db_common.inc.php';
843 include './libraries/db_info.inc.php';
844 } else {
845 include './libraries/server_common.inc.php';
846 include './libraries/server_links.inc.php';
848 } else {
849 include_once './libraries/header.inc.php';
850 //we don't need to buffer the output in PMA_showMessage here.
851 //set a global variable and check against it in the function
852 $GLOBALS['buffer_message'] = false;
856 if (strlen($db)) {
857 $cfgRelation = PMA_getRelationsParam();
860 // Gets the list of fields properties
861 if (isset($result) && $result) {
862 $fields_meta = PMA_DBI_get_fields_meta($result);
863 $fields_cnt = count($fields_meta);
866 if (! $GLOBALS['is_ajax_request']) {
867 //begin the sqlqueryresults div here. container div
868 echo '<div id="sqlqueryresults"';
869 if ($GLOBALS['cfg']['AjaxEnable']) {
870 echo ' class="ajax"';
872 echo '>';
875 // Display previous update query (from tbl_replace)
876 if (isset($disp_query) && $cfg['ShowSQL'] == true) {
877 PMA_showMessage($disp_message, $disp_query, 'success');
880 if (isset($profiling_results)) {
881 // pma_token/url_query needed for chart export
883 <script type="text/javascript">
884 pma_token = '<?php echo $_SESSION[' PMA_token ']; ?>';
885 url_query = '<?php echo isset($url_query)?$url_query:PMA_generate_common_url($db);?>';
886 $(document).ready(makeProfilingChart);
887 </script>
888 <?php
889 echo '<fieldset><legend>' . __('Profiling') . '</legend>' . "\n";
890 echo '<div style="float: left;">';
891 echo '<table>' . "\n";
892 echo ' <tr>' . "\n";
893 echo ' <th>' . __('Status') . PMA_showMySQLDocu('general-thread-states', 'general-thread-states') . '</th>' . "\n";
894 echo ' <th>' . __('Time') . '</th>' . "\n";
895 echo ' </tr>' . "\n";
897 $chart_json = Array();
898 foreach ($profiling_results as $one_result) {
899 echo ' <tr>' . "\n";
900 echo '<td>' . ucwords($one_result['Status']) . '</td>' . "\n";
901 echo '<td align="right">' . (PMA_formatNumber($one_result['Duration'], 3, 1)) . 's</td>' . "\n";
902 $chart_json[ucwords($one_result['Status'])] = $one_result['Duration'];
905 echo '</table>' . "\n";
906 echo '</div>';
907 //require_once './libraries/chart.lib.php';
908 echo '<div id="profilingchart" style="display:none;">';
909 //PMA_chart_profiling($profiling_results);
910 echo json_encode($chart_json);
911 echo '</div>';
912 echo '</fieldset>' . "\n";
915 // Displays the results in a table
916 if (empty($disp_mode)) {
917 // see the "PMA_setDisplayMode()" function in
918 // libraries/display_tbl.lib.php
919 $disp_mode = 'urdr111101';
922 // hide edit and delete links for information_schema
923 if (PMA_is_system_schema($db)) {
924 $disp_mode = 'nnnn110111';
927 if (isset($label)) {
928 $message = PMA_message::success(__('Bookmark %s created'));
929 $message->addParam($label);
930 $message->display();
933 PMA_displayTable($result, $disp_mode, $analyzed_sql);
934 PMA_DBI_free_result($result);
936 // BEGIN INDEX CHECK See if indexes should be checked.
937 if (isset($query_type) && $query_type == 'check_tbl' && isset($selected) && is_array($selected)) {
938 foreach ($selected as $idx => $tbl_name) {
939 $check = PMA_Index::findDuplicates($tbl_name, $db);
940 if (! empty($check)) {
941 printf(__('Problems with indexes of table `%s`'), $tbl_name);
942 echo $check;
945 } // End INDEX CHECK
947 // Bookmark support if required
948 if ($disp_mode[7] == '1'
949 && (! empty($cfg['Bookmark']) && empty($id_bookmark))
950 && ! empty($sql_query)
952 echo "\n";
954 $goto = 'sql.php?'
955 . PMA_generate_common_url($db, $table)
956 . '&amp;sql_query=' . urlencode($sql_query)
957 . '&amp;id_bookmark=1';
960 <form action="sql.php" method="post" onsubmit="return emptyFormElements(this, 'fields[label]');">
961 <?php echo PMA_generate_common_hidden_inputs(); ?>
962 <input type="hidden" name="goto" value="<?php echo $goto; ?>" />
963 <input type="hidden" name="fields[dbase]" value="<?php echo htmlspecialchars($db); ?>" />
964 <input type="hidden" name="fields[user]" value="<?php echo $cfg['Bookmark']['user']; ?>" />
965 <input type="hidden" name="fields[query]" value="<?php echo urlencode(isset($complete_query) ? $complete_query : $sql_query); ?>" />
966 <fieldset>
967 <legend><?php
968 echo PMA_getIcon('b_bookmark.png', __('Bookmark this SQL query'), true);
970 </legend>
972 <div class="formelement">
973 <label for="fields_label_"><?php echo __('Label'); ?>:</label>
974 <input type="text" id="fields_label_" name="fields[label]" value="" />
975 </div>
977 <div class="formelement">
978 <input type="checkbox" name="bkm_all_users" id="bkm_all_users" value="true" />
979 <label for="bkm_all_users"><?php echo __('Let every user access this bookmark'); ?></label>
980 </div>
982 <div class="clearfloat"></div>
983 </fieldset>
984 <fieldset class="tblFooters">
985 <input type="submit" name="store_bkm" value="<?php echo __('Bookmark this SQL query'); ?>" />
986 </fieldset>
987 </form>
988 <?php
989 } // end bookmark support
991 // Do print the page if required
992 if (isset($printview) && $printview == '1') {
994 <script type="text/javascript">
995 //<![CDATA[
996 // Do print the page
997 window.onload = function()
999 if (typeof(window.print) != 'undefined') {
1000 window.print();
1003 //]]>
1004 </script>
1005 <?php
1006 } // end print case
1008 if ($GLOBALS['is_ajax_request'] != true) {
1009 echo '</div>'; // end sqlqueryresults div
1011 } // end rows returned
1014 * Displays the footer
1016 if (! isset($_REQUEST['table_maintenance'])) {
1017 include './libraries/footer.inc.php';