Translated using Weblate (Slovenian)
[phpmyadmin.git] / libraries / sql.lib.php
blobcb45ad02dc938e5b92dc7572ecf603a6558304e8
1 <?php
2 /* vim: set expandtab sw=4 ts=4 sts=4: */
3 /**
4 * set of functions for the sql executor
6 * @package PhpMyAdmin
7 */
8 use PMA\libraries\DisplayResults;
9 use PMA\libraries\Message;
10 use PMA\libraries\Table;
11 use PMA\libraries\Response;
12 use PMA\libraries\URL;
13 use PMA\libraries\Bookmark;
15 /**
16 * Parses and analyzes the given SQL query.
18 * @param string $sql_query SQL query
19 * @param string $db DB name
21 * @return mixed
23 function PMA_parseAndAnalyze($sql_query, $db = null)
25 if (($db === null) && (!empty($GLOBALS['db']))) {
26 $db = $GLOBALS['db'];
29 include_once 'libraries/parse_analyze.lib.php';
30 list($analyzed_sql_results,,) = PMA_parseAnalyze($sql_query, $db);
32 return $analyzed_sql_results;
35 /**
36 * Handle remembered sorting order, only for single table query
38 * @param string $db database name
39 * @param string $table table name
40 * @param array &$analyzed_sql_results the analyzed query results
41 * @param string &$full_sql_query SQL query
43 * @return void
45 function PMA_handleSortOrder(
46 $db, $table, &$analyzed_sql_results, &$full_sql_query
47 ) {
48 $pmatable = new Table($table, $db);
50 if (empty($analyzed_sql_results['order'])) {
52 // Retrieving the name of the column we should sort after.
53 $sortCol = $pmatable->getUiProp(Table::PROP_SORTED_COLUMN);
54 if (empty($sortCol)) {
55 return;
58 // Remove the name of the table from the retrieved field name.
59 $sortCol = str_replace(
60 PMA\libraries\Util::backquote($table) . '.',
61 '',
62 $sortCol
65 // Create the new query.
66 $full_sql_query = PhpMyAdmin\SqlParser\Utils\Query::replaceClause(
67 $analyzed_sql_results['statement'],
68 $analyzed_sql_results['parser']->list,
69 'ORDER BY ' . $sortCol
72 // TODO: Avoid reparsing the query.
73 $analyzed_sql_results = PhpMyAdmin\SqlParser\Utils\Query::getAll($full_sql_query);
74 } else {
75 // Store the remembered table into session.
76 $pmatable->setUiProp(
77 Table::PROP_SORTED_COLUMN,
78 PhpMyAdmin\SqlParser\Utils\Query::getClause(
79 $analyzed_sql_results['statement'],
80 $analyzed_sql_results['parser']->list,
81 'ORDER BY'
87 /**
88 * Append limit clause to SQL query
90 * @param array &$analyzed_sql_results the analyzed query results
92 * @return string limit clause appended SQL query
94 function PMA_getSqlWithLimitClause(&$analyzed_sql_results)
96 return PhpMyAdmin\SqlParser\Utils\Query::replaceClause(
97 $analyzed_sql_results['statement'],
98 $analyzed_sql_results['parser']->list,
99 'LIMIT ' . $_SESSION['tmpval']['pos'] . ', '
100 . $_SESSION['tmpval']['max_rows']
105 * Verify whether the result set has columns from just one table
107 * @param array $fields_meta meta fields
109 * @return boolean whether the result set has columns from just one table
111 function PMA_resultSetHasJustOneTable($fields_meta)
113 $just_one_table = true;
114 $prev_table = '';
115 foreach ($fields_meta as $one_field_meta) {
116 if ($one_field_meta->table != ''
117 && $prev_table != ''
118 && $one_field_meta->table != $prev_table
120 $just_one_table = false;
122 if ($one_field_meta->table != '') {
123 $prev_table = $one_field_meta->table;
126 return $just_one_table && $prev_table != '';
130 * Verify whether the result set contains all the columns
131 * of at least one unique key
133 * @param string $db database name
134 * @param string $table table name
135 * @param array $fields_meta meta fields
137 * @return boolean whether the result set contains a unique key
139 function PMA_resultSetContainsUniqueKey($db, $table, $fields_meta)
141 $resultSetColumnNames = array();
142 foreach ($fields_meta as $oneMeta) {
143 $resultSetColumnNames[] = $oneMeta->name;
145 foreach (PMA\libraries\Index::getFromTable($table, $db) as $index) {
146 if ($index->isUnique()) {
147 $indexColumns = $index->getColumns();
148 $numberFound = 0;
149 foreach ($indexColumns as $indexColumnName => $dummy) {
150 if (in_array($indexColumnName, $resultSetColumnNames)) {
151 $numberFound++;
154 if ($numberFound == count($indexColumns)) {
155 return true;
159 return false;
163 * Get the HTML for relational column dropdown
164 * During grid edit, if we have a relational field, returns the html for the
165 * dropdown
167 * @param string $db current database
168 * @param string $table current table
169 * @param string $column current column
170 * @param string $curr_value current selected value
172 * @return string $dropdown html for the dropdown
174 function PMA_getHtmlForRelationalColumnDropdown($db, $table, $column, $curr_value)
176 $foreigners = PMA_getForeigners($db, $table, $column);
178 $foreignData = PMA_getForeignData($foreigners, $column, false, '', '');
180 if ($foreignData['disp_row'] == null) {
181 //Handle the case when number of values
182 //is more than $cfg['ForeignKeyMaxLimit']
183 $_url_params = array(
184 'db' => $db,
185 'table' => $table,
186 'field' => $column
189 $dropdown = '<span class="curr_value">'
190 . htmlspecialchars($_REQUEST['curr_value'])
191 . '</span>'
192 . '<a href="browse_foreigners.php'
193 . URL::getCommon($_url_params) . '"'
194 . 'class="ajax browse_foreign" ' . '>'
195 . __('Browse foreign values')
196 . '</a>';
197 } else {
198 $dropdown = PMA_foreignDropdown(
199 $foreignData['disp_row'],
200 $foreignData['foreign_field'],
201 $foreignData['foreign_display'],
202 $curr_value,
203 $GLOBALS['cfg']['ForeignKeyMaxLimit']
205 $dropdown = '<select>' . $dropdown . '</select>';
208 return $dropdown;
212 * Get the HTML for the profiling table and accompanying chart if profiling is set.
213 * Otherwise returns null
215 * @param string $url_query url query
216 * @param string $db current database
217 * @param array $profiling_results array containing the profiling info
219 * @return string $profiling_table html for the profiling table and chart
221 function PMA_getHtmlForProfilingChart($url_query, $db, $profiling_results)
223 if (! empty($profiling_results)) {
224 $pma_token = $_SESSION[' PMA_token '];
225 $url_query = isset($url_query)
226 ? $url_query
227 : URL::getCommon(array('db' => $db));
229 $profiling_table = '';
230 $profiling_table .= '<fieldset><legend>' . __('Profiling')
231 . '</legend>' . "\n";
232 $profiling_table .= '<div class="floatleft">';
233 $profiling_table .= '<h3>' . __('Detailed profile') . '</h3>';
234 $profiling_table .= '<table id="profiletable"><thead>' . "\n";
235 $profiling_table .= ' <tr>' . "\n";
236 $profiling_table .= ' <th>' . __('Order')
237 . '<div class="sorticon"></div></th>' . "\n";
238 $profiling_table .= ' <th>' . __('State')
239 . PMA\libraries\Util::showMySQLDocu('general-thread-states')
240 . '<div class="sorticon"></div></th>' . "\n";
241 $profiling_table .= ' <th>' . __('Time')
242 . '<div class="sorticon"></div></th>' . "\n";
243 $profiling_table .= ' </tr></thead><tbody>' . "\n";
244 list($detailed_table, $chart_json, $profiling_stats)
245 = PMA_analyzeAndGetTableHtmlForProfilingResults($profiling_results);
246 $profiling_table .= $detailed_table;
247 $profiling_table .= '</tbody></table>' . "\n";
248 $profiling_table .= '</div>';
250 $profiling_table .= '<div class="floatleft">';
251 $profiling_table .= '<h3>' . __('Summary by state') . '</h3>';
252 $profiling_table .= '<table id="profilesummarytable"><thead>' . "\n";
253 $profiling_table .= ' <tr>' . "\n";
254 $profiling_table .= ' <th>' . __('State')
255 . PMA\libraries\Util::showMySQLDocu('general-thread-states')
256 . '<div class="sorticon"></div></th>' . "\n";
257 $profiling_table .= ' <th>' . __('Total Time')
258 . '<div class="sorticon"></div></th>' . "\n";
259 $profiling_table .= ' <th>' . __('% Time')
260 . '<div class="sorticon"></div></th>' . "\n";
261 $profiling_table .= ' <th>' . __('Calls')
262 . '<div class="sorticon"></div></th>' . "\n";
263 $profiling_table .= ' <th>' . __('ø Time')
264 . '<div class="sorticon"></div></th>' . "\n";
265 $profiling_table .= ' </tr></thead><tbody>' . "\n";
266 $profiling_table .= PMA_getTableHtmlForProfilingSummaryByState(
267 $profiling_stats
269 $profiling_table .= '</tbody></table>' . "\n";
271 $profiling_table .= <<<EOT
272 <script type="text/javascript">
273 pma_token = '$pma_token';
274 url_query = '$url_query';
275 </script>
276 EOT;
277 $profiling_table .= "</div>";
278 $profiling_table .= "<div class='clearfloat'></div>";
280 //require_once 'libraries/chart.lib.php';
281 $profiling_table .= '<div id="profilingChartData" style="display:none;">';
282 $profiling_table .= json_encode($chart_json);
283 $profiling_table .= '</div>';
284 $profiling_table .= '<div id="profilingchart" style="display:none;">';
285 $profiling_table .= '</div>';
286 $profiling_table .= '<script type="text/javascript">';
287 $profiling_table .= "AJAX.registerOnload('sql.js', function () {";
288 $profiling_table .= 'makeProfilingChart();';
289 $profiling_table .= 'initProfilingTables();';
290 $profiling_table .= '});';
291 $profiling_table .= '</script>';
292 $profiling_table .= '</fieldset>' . "\n";
293 } else {
294 $profiling_table = null;
296 return $profiling_table;
300 * Function to get HTML for detailed profiling results table, profiling stats, and
301 * $chart_json for displaying the chart.
303 * @param array $profiling_results profiling results
305 * @return mixed
307 function PMA_analyzeAndGetTableHtmlForProfilingResults(
308 $profiling_results
310 $profiling_stats = array(
311 'total_time' => 0,
312 'states' => array(),
314 $chart_json = Array();
315 $i = 1;
316 $table = '';
317 foreach ($profiling_results as $one_result) {
318 if (isset($profiling_stats['states'][ucwords($one_result['Status'])])) {
319 $states = $profiling_stats['states'];
320 $states[ucwords($one_result['Status'])]['total_time']
321 += $one_result['Duration'];
322 $states[ucwords($one_result['Status'])]['calls']++;
323 } else {
324 $profiling_stats['states'][ucwords($one_result['Status'])] = array(
325 'total_time' => $one_result['Duration'],
326 'calls' => 1,
329 $profiling_stats['total_time'] += $one_result['Duration'];
331 $table .= ' <tr>' . "\n";
332 $table .= '<td>' . $i++ . '</td>' . "\n";
333 $table .= '<td>' . ucwords($one_result['Status'])
334 . '</td>' . "\n";
335 $table .= '<td class="right">'
336 . (PMA\libraries\Util::formatNumber($one_result['Duration'], 3, 1))
337 . 's<span style="display:none;" class="rawvalue">'
338 . $one_result['Duration'] . '</span></td>' . "\n";
339 if (isset($chart_json[ucwords($one_result['Status'])])) {
340 $chart_json[ucwords($one_result['Status'])]
341 += $one_result['Duration'];
342 } else {
343 $chart_json[ucwords($one_result['Status'])]
344 = $one_result['Duration'];
347 return array($table, $chart_json, $profiling_stats);
351 * Function to get HTML for summary by state table
353 * @param array $profiling_stats profiling stats
355 * @return string $table html for the table
357 function PMA_getTableHtmlForProfilingSummaryByState($profiling_stats)
359 $table = '';
360 foreach ($profiling_stats['states'] as $name => $stats) {
361 $table .= ' <tr>' . "\n";
362 $table .= '<td>' . $name . '</td>' . "\n";
363 $table .= '<td align="right">'
364 . PMA\libraries\Util::formatNumber($stats['total_time'], 3, 1)
365 . 's<span style="display:none;" class="rawvalue">'
366 . $stats['total_time'] . '</span></td>' . "\n";
367 $table .= '<td align="right">'
368 . PMA\libraries\Util::formatNumber(
369 100 * ($stats['total_time'] / $profiling_stats['total_time']),
370 0, 2
372 . '%</td>' . "\n";
373 $table .= '<td align="right">' . $stats['calls'] . '</td>'
374 . "\n";
375 $table .= '<td align="right">'
376 . PMA\libraries\Util::formatNumber(
377 $stats['total_time'] / $stats['calls'], 3, 1
379 . 's<span style="display:none;" class="rawvalue">'
380 . number_format($stats['total_time'] / $stats['calls'], 8, '.', '')
381 . '</span></td>' . "\n";
382 $table .= ' </tr>' . "\n";
384 return $table;
388 * Get the HTML for the enum column dropdown
389 * During grid edit, if we have a enum field, returns the html for the
390 * dropdown
392 * @param string $db current database
393 * @param string $table current table
394 * @param string $column current column
395 * @param string $curr_value currently selected value
397 * @return string $dropdown html for the dropdown
399 function PMA_getHtmlForEnumColumnDropdown($db, $table, $column, $curr_value)
401 $values = PMA_getValuesForColumn($db, $table, $column);
402 $dropdown = '<option value="">&nbsp;</option>';
403 $dropdown .= PMA_getHtmlForOptionsList($values, array($curr_value));
404 $dropdown = '<select>' . $dropdown . '</select>';
405 return $dropdown;
409 * Get value of a column for a specific row (marked by $where_clause)
411 * @param string $db current database
412 * @param string $table current table
413 * @param string $column current column
414 * @param string $where_clause where clause to select a particular row
416 * @return string with value
418 function PMA_getFullValuesForSetColumn($db, $table, $column, $where_clause)
420 $result = $GLOBALS['dbi']->fetchSingleRow(
421 "SELECT `$column` FROM `$db`.`$table` WHERE $where_clause"
424 return $result[$column];
428 * Get the HTML for the set column dropdown
429 * During grid edit, if we have a set field, returns the html for the
430 * dropdown
432 * @param string $db current database
433 * @param string $table current table
434 * @param string $column current column
435 * @param string $curr_value currently selected value
437 * @return string $dropdown html for the set column
439 function PMA_getHtmlForSetColumn($db, $table, $column, $curr_value)
441 $values = PMA_getValuesForColumn($db, $table, $column);
442 $dropdown = '';
443 $full_values =
444 isset($_REQUEST['get_full_values']) ? $_REQUEST['get_full_values'] : false;
445 $where_clause =
446 isset($_REQUEST['where_clause']) ? $_REQUEST['where_clause'] : null;
448 // If the $curr_value was truncated, we should
449 // fetch the correct full values from the table
450 if ($full_values && ! empty($where_clause)) {
451 $curr_value = PMA_getFullValuesForSetColumn(
452 $db, $table, $column, $where_clause
456 //converts characters of $curr_value to HTML entities
457 $converted_curr_value = htmlentities(
458 $curr_value, ENT_COMPAT, "UTF-8"
461 $selected_values = explode(',', $converted_curr_value);
463 $dropdown .= PMA_getHtmlForOptionsList($values, $selected_values);
465 $select_size = (sizeof($values) > 10) ? 10 : sizeof($values);
466 $dropdown = '<select multiple="multiple" size="' . $select_size . '">'
467 . $dropdown . '</select>';
469 return $dropdown;
473 * Get all the values for a enum column or set column in a table
475 * @param string $db current database
476 * @param string $table current table
477 * @param string $column current column
479 * @return array $values array containing the value list for the column
481 function PMA_getValuesForColumn($db, $table, $column)
483 $field_info_query = $GLOBALS['dbi']->getColumnsSql($db, $table, $column);
485 $field_info_result = $GLOBALS['dbi']->fetchResult(
486 $field_info_query,
487 null,
488 null,
489 null,
490 PMA\libraries\DatabaseInterface::QUERY_STORE
493 $values = PMA\libraries\Util::parseEnumSetValues($field_info_result[0]['Type']);
495 return $values;
499 * Get HTML for options list
501 * @param array $values set of values
502 * @param array $selected_values currently selected values
504 * @return string $options HTML for options list
506 function PMA_getHtmlForOptionsList($values, $selected_values)
508 $options = '';
509 foreach ($values as $value) {
510 $options .= '<option value="' . $value . '"';
511 if (in_array($value, $selected_values, true)) {
512 $options .= ' selected="selected" ';
514 $options .= '>' . $value . '</option>';
516 return $options;
520 * Function to get html for bookmark support if bookmarks are enabled. Else will
521 * return null
523 * @param array $displayParts the parts to display
524 * @param array $cfgBookmark configuration setting for bookmarking
525 * @param string $sql_query sql query
526 * @param string $db current database
527 * @param string $table current table
528 * @param string $complete_query complete query
529 * @param string $bkm_user bookmarking user
531 * @return string $html
533 function PMA_getHtmlForBookmark($displayParts, $cfgBookmark, $sql_query, $db,
534 $table, $complete_query, $bkm_user
536 if ($displayParts['bkm_form'] == '1'
537 && (! empty($cfgBookmark) && empty($_GET['id_bookmark']))
538 && ! empty($sql_query)
540 $goto = 'sql.php'
541 . URL::getCommon(
542 array(
543 'db' => $db,
544 'table' => $table,
545 'sql_query' => $sql_query,
546 'id_bookmark'=> 1,
549 $bkm_sql_query = isset($complete_query) ? $complete_query : $sql_query;
550 $html = '<form action="sql.php" method="post"'
551 . ' onsubmit="return ! emptyCheckTheField(this,'
552 . '\'bkm_fields[bkm_label]\');"'
553 . ' class="bookmarkQueryForm print_ignore">';
554 $html .= URL::getHiddenInputs();
555 $html .= '<input type="hidden" name="db"'
556 . ' value="' . htmlspecialchars($db) . '" />';
557 $html .= '<input type="hidden" name="goto" value="' . $goto . '" />';
558 $html .= '<input type="hidden" name="bkm_fields[bkm_database]"'
559 . ' value="' . htmlspecialchars($db) . '" />';
560 $html .= '<input type="hidden" name="bkm_fields[bkm_user]"'
561 . ' value="' . $bkm_user . '" />';
562 $html .= '<input type="hidden" name="bkm_fields[bkm_sql_query]"'
563 . ' value="'
564 . htmlspecialchars($bkm_sql_query)
565 . '" />';
566 $html .= '<fieldset>';
567 $html .= '<legend>';
568 $html .= PMA\libraries\Util::getIcon(
569 'b_bookmark.png', __('Bookmark this SQL query'), true
571 $html .= '</legend>';
572 $html .= '<div class="formelement">';
573 $html .= '<label>' . __('Label:');
574 $html .= '<input type="text" name="bkm_fields[bkm_label]" value="" />' .
575 '</label>';
576 $html .= '</div>';
577 $html .= '<div class="formelement">';
578 $html .= '<label>' .
579 '<input type="checkbox" name="bkm_all_users" value="true" />';
580 $html .= __('Let every user access this bookmark') . '</label>';
581 $html .= '</div>';
582 $html .= '<div class="clearfloat"></div>';
583 $html .= '</fieldset>';
584 $html .= '<fieldset class="tblFooters">';
585 $html .= '<input type="hidden" name="store_bkm" value="1" />';
586 $html .= '<input type="submit"'
587 . ' value="' . __('Bookmark this SQL query') . '" />';
588 $html .= '</fieldset>';
589 $html .= '</form>';
591 } else {
592 $html = null;
595 return $html;
599 * Function to check whether to remember the sorting order or not
601 * @param array $analyzed_sql_results the analyzed query and other variables set
602 * after analyzing the query
604 * @return boolean
606 function PMA_isRememberSortingOrder($analyzed_sql_results)
608 return $GLOBALS['cfg']['RememberSorting']
609 && ! ($analyzed_sql_results['is_count']
610 || $analyzed_sql_results['is_export']
611 || $analyzed_sql_results['is_func']
612 || $analyzed_sql_results['is_analyse'])
613 && $analyzed_sql_results['select_from']
614 && ((empty($analyzed_sql_results['select_expr']))
615 || (count($analyzed_sql_results['select_expr'] == 1)
616 && ($analyzed_sql_results['select_expr'][0] == '*')))
617 && count($analyzed_sql_results['select_tables']) == 1;
621 * Function to check whether the LIMIT clause should be appended or not
623 * @param array $analyzed_sql_results the analyzed query and other variables set
624 * after analyzing the query
626 * @return boolean
628 function PMA_isAppendLimitClause($analyzed_sql_results)
630 // Assigning LIMIT clause to an syntactically-wrong query
631 // is not needed. Also we would want to show the true query
632 // and the true error message to the query executor
634 return (isset($analyzed_sql_results['parser'])
635 && count($analyzed_sql_results['parser']->errors) === 0)
636 && ($_SESSION['tmpval']['max_rows'] != 'all')
637 && ! ($analyzed_sql_results['is_export']
638 || $analyzed_sql_results['is_analyse'])
639 && ($analyzed_sql_results['select_from']
640 || $analyzed_sql_results['is_subquery'])
641 && empty($analyzed_sql_results['limit']);
645 * Function to check whether this query is for just browsing
647 * @param array $analyzed_sql_results the analyzed query and other variables set
648 * after analyzing the query
649 * @param boolean $find_real_end whether the real end should be found
651 * @return boolean
653 function PMA_isJustBrowsing($analyzed_sql_results, $find_real_end)
655 return ! $analyzed_sql_results['is_group']
656 && ! $analyzed_sql_results['is_func']
657 && empty($analyzed_sql_results['union'])
658 && empty($analyzed_sql_results['distinct'])
659 && $analyzed_sql_results['select_from']
660 && (count($analyzed_sql_results['select_tables']) === 1)
661 && (empty($analyzed_sql_results['statement']->where)
662 || (count($analyzed_sql_results['statement']->where) == 1
663 && $analyzed_sql_results['statement']->where[0]->expr ==='1'))
664 && empty($analyzed_sql_results['group'])
665 && ! isset($find_real_end)
666 && ! $analyzed_sql_results['is_subquery']
667 && ! $analyzed_sql_results['join']
668 && empty($analyzed_sql_results['having']);
672 * Function to check whether the related transformation information should be deleted
674 * @param array $analyzed_sql_results the analyzed query and other variables set
675 * after analyzing the query
677 * @return boolean
679 function PMA_isDeleteTransformationInfo($analyzed_sql_results)
681 return !empty($analyzed_sql_results['querytype'])
682 && (($analyzed_sql_results['querytype'] == 'ALTER')
683 || ($analyzed_sql_results['querytype'] == 'DROP'));
687 * Function to check whether the user has rights to drop the database
689 * @param array $analyzed_sql_results the analyzed query and other variables set
690 * after analyzing the query
691 * @param boolean $allowUserDropDatabase whether the user is allowed to drop db
692 * @param boolean $is_superuser whether this user is a superuser
694 * @return boolean
696 function PMA_hasNoRightsToDropDatabase($analyzed_sql_results,
697 $allowUserDropDatabase, $is_superuser
699 return ! $allowUserDropDatabase
700 && isset($analyzed_sql_results['drop_database'])
701 && $analyzed_sql_results['drop_database']
702 && ! $is_superuser;
706 * Function to set a column property
708 * @param Table $pmatable Table instance
709 * @param string $request_index col_order|col_visib
711 * @return boolean $retval
713 function PMA_setColumnProperty($pmatable, $request_index)
715 $property_value = explode(',', $_REQUEST[$request_index]);
716 switch($request_index) {
717 case 'col_order':
718 $property_to_set = Table::PROP_COLUMN_ORDER;
719 break;
720 case 'col_visib':
721 $property_to_set = Table::PROP_COLUMN_VISIB;
722 break;
723 default:
724 $property_to_set = '';
726 $retval = $pmatable->setUiProp(
727 $property_to_set,
728 $property_value,
729 $_REQUEST['table_create_time']
731 if (gettype($retval) != 'boolean') {
732 $response = Response::getInstance();
733 $response->setRequestStatus(false);
734 $response->addJSON('message', $retval->getString());
735 exit;
738 return $retval;
742 * Function to check the request for setting the column order or visibility
744 * @param String $table the current table
745 * @param String $db the current database
747 * @return void
749 function PMA_setColumnOrderOrVisibility($table, $db)
751 $pmatable = new Table($table, $db);
752 $retval = false;
754 // set column order
755 if (isset($_REQUEST['col_order'])) {
756 $retval = PMA_setColumnProperty($pmatable, 'col_order');
759 // set column visibility
760 if ($retval === true && isset($_REQUEST['col_visib'])) {
761 $retval = PMA_setColumnProperty($pmatable, 'col_visib');
764 $response = Response::getInstance();
765 $response->setRequestStatus($retval == true);
766 exit;
770 * Function to add a bookmark
772 * @param String $goto goto page URL
774 * @return void
776 function PMA_addBookmark($goto)
778 $bookmark = Bookmark::createBookmark(
779 $_POST['bkm_fields'],
780 (isset($_POST['bkm_all_users'])
781 && $_POST['bkm_all_users'] == 'true' ? true : false
784 $result = $bookmark->save();
785 $response = Response::getInstance();
786 if ($response->isAjax()) {
787 if ($result) {
788 $msg = Message::success(__('Bookmark %s has been created.'));
789 $msg->addParam($_POST['bkm_fields']['bkm_label']);
790 $response->addJSON('message', $msg);
791 } else {
792 $msg = PMA\libraries\message::error(__('Bookmark not created!'));
793 $response->setRequestStatus(false);
794 $response->addJSON('message', $msg);
796 exit;
797 } else {
798 // go back to sql.php to redisplay query; do not use &amp; in this case:
800 * @todo In which scenario does this happen?
802 PMA_sendHeaderLocation(
803 './' . $goto
804 . '&label=' . $_POST['bkm_fields']['bkm_label']
810 * Function to find the real end of rows
812 * @param String $db the current database
813 * @param String $table the current table
815 * @return mixed the number of rows if "retain" param is true, otherwise true
817 function PMA_findRealEndOfRows($db, $table)
819 $unlim_num_rows = $GLOBALS['dbi']->getTable($db, $table)->countRecords(true);
820 $_SESSION['tmpval']['pos'] = PMA_getStartPosToDisplayRow($unlim_num_rows);
822 return $unlim_num_rows;
826 * Function to get values for the relational columns
828 * @param String $db the current database
829 * @param String $table the current table
831 * @return void
833 function PMA_getRelationalValues($db, $table)
835 $column = $_REQUEST['column'];
836 if ($_SESSION['tmpval']['relational_display'] == 'D'
837 && isset($_REQUEST['relation_key_or_display_column'])
838 && $_REQUEST['relation_key_or_display_column']
840 $curr_value = $_REQUEST['relation_key_or_display_column'];
841 } else {
842 $curr_value = $_REQUEST['curr_value'];
844 $dropdown = PMA_getHtmlForRelationalColumnDropdown(
845 $db, $table, $column, $curr_value
847 $response = Response::getInstance();
848 $response->addJSON('dropdown', $dropdown);
849 exit;
853 * Function to get values for Enum or Set Columns
855 * @param String $db the current database
856 * @param String $table the current table
857 * @param String $columnType whether enum or set
859 * @return void
861 function PMA_getEnumOrSetValues($db, $table, $columnType)
863 $column = $_REQUEST['column'];
864 $curr_value = $_REQUEST['curr_value'];
865 $response = Response::getInstance();
866 if ($columnType == "enum") {
867 $dropdown = PMA_getHtmlForEnumColumnDropdown(
868 $db, $table, $column, $curr_value
870 $response->addJSON('dropdown', $dropdown);
871 } else {
872 $select = PMA_getHtmlForSetColumn(
873 $db, $table, $column, $curr_value
875 $response->addJSON('select', $select);
877 exit;
881 * Function to get the default sql query for browsing page
883 * @param String $db the current database
884 * @param String $table the current table
886 * @return String $sql_query the default $sql_query for browse page
888 function PMA_getDefaultSqlQueryForBrowse($db, $table)
890 $bookmark = Bookmark::get(
891 $db,
892 $table,
893 'label',
894 false,
895 true
898 if (! empty($bookmark) && ! empty($bookmark->getQuery())) {
899 $GLOBALS['using_bookmark_message'] = Message::notice(
900 __('Using bookmark "%s" as default browse query.')
902 $GLOBALS['using_bookmark_message']->addParam($table);
903 $GLOBALS['using_bookmark_message']->addHtml(
904 PMA\libraries\Util::showDocu('faq', 'faq6-22')
906 $sql_query = $bookmark->getQuery();
907 } else {
909 $defaultOrderByClause = '';
911 if (isset($GLOBALS['cfg']['TablePrimaryKeyOrder'])
912 && ($GLOBALS['cfg']['TablePrimaryKeyOrder'] !== 'NONE')
915 $primaryKey = null;
916 $primary = PMA\libraries\Index::getPrimary($table, $db);
918 if ($primary !== false) {
920 $primarycols = $primary->getColumns();
922 foreach ($primarycols as $col) {
923 $primaryKey = $col->getName();
924 break;
927 if ($primaryKey != null) {
928 $defaultOrderByClause = ' ORDER BY '
929 . PMA\libraries\Util::backquote($table) . '.'
930 . PMA\libraries\Util::backquote($primaryKey) . ' '
931 . $GLOBALS['cfg']['TablePrimaryKeyOrder'];
938 $sql_query = 'SELECT * FROM ' . PMA\libraries\Util::backquote($table)
939 . $defaultOrderByClause;
943 return $sql_query;
947 * Responds an error when an error happens when executing the query
949 * @param boolean $is_gotofile whether goto file or not
950 * @param String $error error after executing the query
951 * @param String $full_sql_query full sql query
953 * @return void
955 function PMA_handleQueryExecuteError($is_gotofile, $error, $full_sql_query)
957 if ($is_gotofile) {
958 $message = PMA\libraries\Message::rawError($error);
959 $response = Response::getInstance();
960 $response->setRequestStatus(false);
961 $response->addJSON('message', $message);
962 } else {
963 PMA\libraries\Util::mysqlDie($error, $full_sql_query, '', '');
965 exit;
969 * Function to store the query as a bookmark
971 * @param String $db the current database
972 * @param String $bkm_user the bookmarking user
973 * @param String $sql_query_for_bookmark the query to be stored in bookmark
974 * @param String $bkm_label bookmark label
975 * @param boolean $bkm_replace whether to replace existing bookmarks
977 * @return void
979 function PMA_storeTheQueryAsBookmark($db, $bkm_user, $sql_query_for_bookmark,
980 $bkm_label, $bkm_replace
982 $bfields = array(
983 'bkm_database' => $db,
984 'bkm_user' => $bkm_user,
985 'bkm_sql_query' => $sql_query_for_bookmark,
986 'bkm_label' => $bkm_label
989 // Should we replace bookmark?
990 if (isset($bkm_replace)) {
991 $bookmarks = Bookmark::getList($db);
992 foreach ($bookmarks as $bookmark) {
993 if ($bookmark->getLabel() == $bkm_label) {
994 $bookmark->delete();
999 $bookmark = Bookmark::createBookmark($bfields, isset($_POST['bkm_all_users']));
1000 $bookmark->save();
1004 * Executes the SQL query and measures its execution time
1006 * @param String $full_sql_query the full sql query
1008 * @return array ($result, $querytime)
1010 function PMA_executeQueryAndMeasureTime($full_sql_query)
1012 // close session in case the query takes too long
1013 session_write_close();
1015 // Measure query time.
1016 $querytime_before = array_sum(explode(' ', microtime()));
1018 $result = @$GLOBALS['dbi']->tryQuery(
1019 $full_sql_query, null, PMA\libraries\DatabaseInterface::QUERY_STORE
1021 $querytime_after = array_sum(explode(' ', microtime()));
1023 // reopen session
1024 session_start();
1026 return array($result, $querytime_after - $querytime_before);
1030 * Function to get the affected or changed number of rows after executing a query
1032 * @param boolean $is_affected whether the query affected a table
1033 * @param mixed $result results of executing the query
1035 * @return int $num_rows number of rows affected or changed
1037 function PMA_getNumberOfRowsAffectedOrChanged($is_affected, $result)
1039 if (! $is_affected) {
1040 $num_rows = ($result) ? @$GLOBALS['dbi']->numRows($result) : 0;
1041 } else {
1042 $num_rows = @$GLOBALS['dbi']->affectedRows();
1045 return $num_rows;
1049 * Checks if the current database has changed
1050 * This could happen if the user sends a query like "USE `database`;"
1052 * @param String $db the database in the query
1054 * @return int $reload whether to reload the navigation(1) or not(0)
1056 function PMA_hasCurrentDbChanged($db)
1058 if (strlen($db) > 0) {
1059 $current_db = $GLOBALS['dbi']->fetchValue('SELECT DATABASE()');
1060 // $current_db is false, except when a USE statement was sent
1061 return ($current_db != false) && ($db !== $current_db);
1064 return false;
1068 * If a table, database or column gets dropped, clean comments.
1070 * @param String $db current database
1071 * @param String $table current table
1072 * @param String $column current column
1073 * @param bool $purge whether purge set or not
1075 * @return array $extra_data
1077 function PMA_cleanupRelations($db, $table, $column, $purge)
1079 include_once 'libraries/relation_cleanup.lib.php';
1081 if (! empty($purge) && strlen($db) > 0) {
1082 if (strlen($table) > 0) {
1083 if (isset($column) && strlen($column) > 0) {
1084 PMA_relationsCleanupColumn($db, $table, $column);
1085 } else {
1086 PMA_relationsCleanupTable($db, $table);
1088 } else {
1089 PMA_relationsCleanupDatabase($db);
1095 * Function to count the total number of rows for the same 'SELECT' query without
1096 * the 'LIMIT' clause that may have been programatically added
1098 * @param int $num_rows number of rows affected/changed by the query
1099 * @param bool $justBrowsing whether just browsing or not
1100 * @param string $db the current database
1101 * @param string $table the current table
1102 * @param array $analyzed_sql_results the analyzed query and other variables set
1103 * after analyzing the query
1105 * @return int $unlim_num_rows unlimited number of rows
1107 function PMA_countQueryResults(
1108 $num_rows, $justBrowsing, $db, $table, $analyzed_sql_results
1111 /* Shortcut for not analyzed/empty query */
1112 if (empty($analyzed_sql_results)) {
1113 return 0;
1116 if (!PMA_isAppendLimitClause($analyzed_sql_results)) {
1117 // if we did not append a limit, set this to get a correct
1118 // "Showing rows..." message
1119 // $_SESSION['tmpval']['max_rows'] = 'all';
1120 $unlim_num_rows = $num_rows;
1121 } elseif ($analyzed_sql_results['querytype'] == 'SELECT'
1122 || $analyzed_sql_results['is_subquery']
1124 // c o u n t q u e r y
1126 // If we are "just browsing", there is only one table (and no join),
1127 // and no WHERE clause (or just 'WHERE 1 '),
1128 // we do a quick count (which uses MaxExactCount) because
1129 // SQL_CALC_FOUND_ROWS is not quick on large InnoDB tables
1131 // However, do not count again if we did it previously
1132 // due to $find_real_end == true
1133 if ($justBrowsing) {
1134 // Get row count (is approximate for InnoDB)
1135 $unlim_num_rows = $GLOBALS['dbi']->getTable($db, $table)->countRecords();
1137 * @todo Can we know at this point that this is InnoDB,
1138 * (in this case there would be no need for getting
1139 * an exact count)?
1141 if ($unlim_num_rows < $GLOBALS['cfg']['MaxExactCount']) {
1142 // Get the exact count if approximate count
1143 // is less than MaxExactCount
1145 * @todo In countRecords(), MaxExactCount is also verified,
1146 * so can we avoid checking it twice?
1148 $unlim_num_rows = $GLOBALS['dbi']->getTable($db, $table)
1149 ->countRecords(true);
1152 } else {
1154 // The SQL_CALC_FOUND_ROWS option of the SELECT statement is used.
1156 // For UNION statements, only a SQL_CALC_FOUND_ROWS is required
1157 // after the first SELECT.
1159 $count_query = PhpMyAdmin\SqlParser\Utils\Query::replaceClause(
1160 $analyzed_sql_results['statement'],
1161 $analyzed_sql_results['parser']->list,
1162 'SELECT SQL_CALC_FOUND_ROWS',
1163 null,
1164 true
1167 // Another LIMIT clause is added to avoid long delays.
1168 // A complete result will be returned anyway, but the LIMIT would
1169 // stop the query as soon as the result that is required has been
1170 // computed.
1172 if (empty($analyzed_sql_results['union'])) {
1173 $count_query .= ' LIMIT 1';
1176 // Running the count query.
1177 $GLOBALS['dbi']->tryQuery($count_query);
1179 $unlim_num_rows = $GLOBALS['dbi']->fetchValue('SELECT FOUND_ROWS()');
1180 } // end else "just browsing"
1181 } else {// not $is_select
1182 $unlim_num_rows = 0;
1185 return $unlim_num_rows;
1189 * Function to handle all aspects relating to executing the query
1191 * @param array $analyzed_sql_results analyzed sql results
1192 * @param String $full_sql_query full sql query
1193 * @param boolean $is_gotofile whether to go to a file
1194 * @param String $db current database
1195 * @param String $table current table
1196 * @param boolean $find_real_end whether to find the real end
1197 * @param String $sql_query_for_bookmark sql query to be stored as bookmark
1198 * @param array $extra_data extra data
1200 * @return mixed
1202 function PMA_executeTheQuery($analyzed_sql_results, $full_sql_query, $is_gotofile,
1203 $db, $table, $find_real_end, $sql_query_for_bookmark, $extra_data
1205 $response = Response::getInstance();
1206 $response->getHeader()->getMenu()->setTable($table);
1208 // Only if we ask to see the php code
1209 if (isset($GLOBALS['show_as_php'])) {
1210 $result = null;
1211 $num_rows = 0;
1212 $unlim_num_rows = 0;
1213 } else { // If we don't ask to see the php code
1214 if (isset($_SESSION['profiling'])
1215 && PMA\libraries\Util::profilingSupported()
1217 $GLOBALS['dbi']->query('SET PROFILING=1;');
1220 list(
1221 $result,
1222 $GLOBALS['querytime']
1223 ) = PMA_executeQueryAndMeasureTime($full_sql_query);
1225 // Displays an error message if required and stop parsing the script
1226 $error = $GLOBALS['dbi']->getError();
1227 if ($error && $GLOBALS['cfg']['IgnoreMultiSubmitErrors']) {
1228 $extra_data['error'] = $error;
1229 } elseif ($error) {
1230 PMA_handleQueryExecuteError($is_gotofile, $error, $full_sql_query);
1233 // If there are no errors and bookmarklabel was given,
1234 // store the query as a bookmark
1235 if (! empty($_POST['bkm_label']) && ! empty($sql_query_for_bookmark)) {
1236 $cfgBookmark = Bookmark::getParams();
1237 PMA_storeTheQueryAsBookmark(
1238 $db, $cfgBookmark['user'],
1239 $sql_query_for_bookmark, $_POST['bkm_label'],
1240 isset($_POST['bkm_replace']) ? $_POST['bkm_replace'] : null
1242 } // end store bookmarks
1244 // Gets the number of rows affected/returned
1245 // (This must be done immediately after the query because
1246 // mysql_affected_rows() reports about the last query done)
1247 $num_rows = PMA_getNumberOfRowsAffectedOrChanged(
1248 $analyzed_sql_results['is_affected'], $result
1251 // Grabs the profiling results
1252 if (isset($_SESSION['profiling'])
1253 && PMA\libraries\Util::profilingSupported()
1255 $profiling_results = $GLOBALS['dbi']->fetchResult('SHOW PROFILE;');
1258 $justBrowsing = PMA_isJustBrowsing(
1259 $analyzed_sql_results, isset($find_real_end) ? $find_real_end : null
1262 $unlim_num_rows = PMA_countQueryResults(
1263 $num_rows, $justBrowsing, $db, $table, $analyzed_sql_results
1266 PMA_cleanupRelations(
1267 isset($db) ? $db : '',
1268 isset($table) ? $table : '',
1269 isset($_REQUEST['dropped_column']) ? $_REQUEST['dropped_column'] : null,
1270 isset($_REQUEST['purge']) ? $_REQUEST['purge'] : null
1273 if (isset($_REQUEST['dropped_column'])
1274 && strlen($db) > 0
1275 && strlen($table) > 0
1277 // to refresh the list of indexes (Ajax mode)
1278 $extra_data['indexes_list'] = PMA\libraries\Index::getHtmlForIndexes(
1279 $table,
1285 return array($result, $num_rows, $unlim_num_rows,
1286 isset($profiling_results) ? $profiling_results : null, $extra_data
1290 * Delete related tranformation information
1292 * @param String $db current database
1293 * @param String $table current table
1294 * @param array $analyzed_sql_results analyzed sql results
1296 * @return void
1298 function PMA_deleteTransformationInfo($db, $table, $analyzed_sql_results)
1300 include_once 'libraries/transformations.lib.php';
1301 $statement = $analyzed_sql_results['statement'];
1302 if ($statement instanceof PhpMyAdmin\SqlParser\Statements\AlterStatement) {
1303 if (!empty($statement->altered[0])
1304 && $statement->altered[0]->options->has('DROP')
1306 if (!empty($statement->altered[0]->field->column)) {
1307 PMA_clearTransformations(
1308 $db,
1309 $table,
1310 $statement->altered[0]->field->column
1314 } elseif ($statement instanceof PhpMyAdmin\SqlParser\Statements\DropStatement) {
1315 PMA_clearTransformations($db, $table);
1320 * Function to get the message for the no rows returned case
1322 * @param string $message_to_show message to show
1323 * @param array $analyzed_sql_results analyzed sql results
1324 * @param int $num_rows number of rows
1326 * @return string $message
1328 function PMA_getMessageForNoRowsReturned($message_to_show,
1329 $analyzed_sql_results, $num_rows
1331 if ($analyzed_sql_results['querytype'] == 'DELETE"') {
1332 $message = Message::getMessageForDeletedRows($num_rows);
1333 } elseif ($analyzed_sql_results['is_insert']) {
1334 if ($analyzed_sql_results['querytype'] == 'REPLACE') {
1335 // For REPLACE we get DELETED + INSERTED row count,
1336 // so we have to call it affected
1337 $message = Message::getMessageForAffectedRows($num_rows);
1338 } else {
1339 $message = Message::getMessageForInsertedRows($num_rows);
1341 $insert_id = $GLOBALS['dbi']->insertId();
1342 if ($insert_id != 0) {
1343 // insert_id is id of FIRST record inserted in one insert,
1344 // so if we inserted multiple rows, we had to increment this
1345 $message->addText('[br]');
1346 // need to use a temporary because the Message class
1347 // currently supports adding parameters only to the first
1348 // message
1349 $_inserted = Message::notice(__('Inserted row id: %1$d'));
1350 $_inserted->addParam($insert_id + $num_rows - 1);
1351 $message->addMessage($_inserted);
1353 } elseif ($analyzed_sql_results['is_affected']) {
1354 $message = Message::getMessageForAffectedRows($num_rows);
1356 // Ok, here is an explanation for the !$is_select.
1357 // The form generated by sql_query_form.lib.php
1358 // and db_sql.php has many submit buttons
1359 // on the same form, and some confusion arises from the
1360 // fact that $message_to_show is sent for every case.
1361 // The $message_to_show containing a success message and sent with
1362 // the form should not have priority over errors
1363 } elseif (! empty($message_to_show)
1364 && $analyzed_sql_results['querytype'] != 'SELECT'
1366 $message = Message::rawSuccess(htmlspecialchars($message_to_show));
1367 } elseif (! empty($GLOBALS['show_as_php'])) {
1368 $message = Message::success(__('Showing as PHP code'));
1369 } elseif (isset($GLOBALS['show_as_php'])) {
1370 /* User disable showing as PHP, query is only displayed */
1371 $message = Message::notice(__('Showing SQL query'));
1372 } else {
1373 $message = Message::success(
1374 __('MySQL returned an empty result set (i.e. zero rows).')
1378 if (isset($GLOBALS['querytime'])) {
1379 $_querytime = Message::notice(
1380 '(' . __('Query took %01.4f seconds.') . ')'
1382 $_querytime->addParam($GLOBALS['querytime']);
1383 $message->addMessage($_querytime);
1386 // In case of ROLLBACK, notify the user.
1387 if (isset($_REQUEST['rollback_query'])) {
1388 $message->addText(__('[ROLLBACK occurred.]'));
1391 return $message;
1395 * Function to respond back when the query returns zero rows
1396 * This method is called
1397 * 1-> When browsing an empty table
1398 * 2-> When executing a query on a non empty table which returns zero results
1399 * 3-> When executing a query on an empty table
1400 * 4-> When executing an INSERT, UPDATE, DELETE query from the SQL tab
1401 * 5-> When deleting a row from BROWSE tab
1402 * 6-> When searching using the SEARCH tab which returns zero results
1403 * 7-> When changing the structure of the table except change operation
1405 * @param array $analyzed_sql_results analyzed sql results
1406 * @param string $db current database
1407 * @param string $table current table
1408 * @param string $message_to_show message to show
1409 * @param int $num_rows number of rows
1410 * @param DisplayResults $displayResultsObject DisplayResult instance
1411 * @param array $extra_data extra data
1412 * @param string $pmaThemeImage uri of the theme image
1413 * @param object $result executed query results
1414 * @param string $sql_query sql query
1415 * @param string $complete_query complete sql query
1417 * @return string html
1419 function PMA_getQueryResponseForNoResultsReturned($analyzed_sql_results, $db,
1420 $table, $message_to_show, $num_rows, $displayResultsObject, $extra_data,
1421 $pmaThemeImage, $result, $sql_query, $complete_query
1423 if (PMA_isDeleteTransformationInfo($analyzed_sql_results)) {
1424 PMA_deleteTransformationInfo($db, $table, $analyzed_sql_results);
1427 if (isset($extra_data['error'])) {
1428 $message = PMA\libraries\Message::rawError($extra_data['error']);
1429 } else {
1430 $message = PMA_getMessageForNoRowsReturned(
1431 isset($message_to_show) ? $message_to_show : null,
1432 $analyzed_sql_results, $num_rows
1436 $html_output = '';
1437 $html_message = PMA\libraries\Util::getMessage(
1438 $message, $GLOBALS['sql_query'], 'success'
1440 $html_output .= $html_message;
1441 if (!isset($GLOBALS['show_as_php'])) {
1443 if (! empty($GLOBALS['reload'])) {
1444 $extra_data['reload'] = 1;
1445 $extra_data['db'] = $GLOBALS['db'];
1448 // For ajax requests add message and sql_query as JSON
1449 if (empty($_REQUEST['ajax_page_request'])) {
1450 $extra_data['message'] = $message;
1451 if ($GLOBALS['cfg']['ShowSQL']) {
1452 $extra_data['sql_query'] = $html_message;
1456 $response = Response::getInstance();
1457 $response->addJSON(isset($extra_data) ? $extra_data : array());
1459 if (!empty($analyzed_sql_results['is_select']) &&
1460 !isset($extra_data['error'])) {
1461 $url_query = isset($url_query) ? $url_query : null;
1463 $displayParts = array(
1464 'edit_lnk' => null,
1465 'del_lnk' => null,
1466 'sort_lnk' => '1',
1467 'nav_bar' => '0',
1468 'bkm_form' => '1',
1469 'text_btn' => '1',
1470 'pview_lnk' => '1'
1473 $html_output .= PMA_getHtmlForSqlQueryResultsTable(
1474 $displayResultsObject,
1475 $pmaThemeImage, $url_query, $displayParts,
1476 false, 0, $num_rows, true, $result,
1477 $analyzed_sql_results, true
1480 $html_output .= $displayResultsObject->getCreateViewQueryResultOp(
1481 $analyzed_sql_results
1484 $cfgBookmark = Bookmark::getParams();
1485 if ($cfgBookmark) {
1486 $html_output .= PMA_getHtmlForBookmark(
1487 $displayParts,
1488 $cfgBookmark,
1489 $sql_query, $db, $table,
1490 isset($complete_query) ? $complete_query : $sql_query,
1491 $cfgBookmark['user']
1497 return $html_output;
1501 * Function to send response for ajax grid edit
1503 * @param object $result result of the executed query
1505 * @return void
1507 function PMA_sendResponseForGridEdit($result)
1509 $row = $GLOBALS['dbi']->fetchRow($result);
1510 $field_flags = $GLOBALS['dbi']->fieldFlags($result, 0);
1511 if (stristr($field_flags, PMA\libraries\DisplayResults::BINARY_FIELD)) {
1512 $row[0] = bin2hex($row[0]);
1514 $response = Response::getInstance();
1515 $response->addJSON('value', $row[0]);
1516 exit;
1520 * Function to get html for the sql query results div
1522 * @param string $previous_update_query_html html for the previously executed query
1523 * @param string $profiling_chart_html html for profiling
1524 * @param Message $missing_unique_column_msg message for the missing unique column
1525 * @param Message $bookmark_created_msg message for bookmark creation
1526 * @param string $table_html html for the table for displaying sql
1527 * results
1528 * @param string $indexes_problems_html html for displaying errors in indexes
1529 * @param string $bookmark_support_html html for displaying bookmark form
1531 * @return string $html_output
1533 function PMA_getHtmlForSqlQueryResults($previous_update_query_html,
1534 $profiling_chart_html, $missing_unique_column_msg, $bookmark_created_msg,
1535 $table_html, $indexes_problems_html, $bookmark_support_html
1537 //begin the sqlqueryresults div here. container div
1538 $html_output = '<div class="sqlqueryresults ajax">';
1539 $html_output .= isset($previous_update_query_html)
1540 ? $previous_update_query_html : '';
1541 $html_output .= isset($profiling_chart_html) ? $profiling_chart_html : '';
1542 $html_output .= isset($missing_unique_column_msg)
1543 ? $missing_unique_column_msg->getDisplay() : '';
1544 $html_output .= isset($bookmark_created_msg)
1545 ? $bookmark_created_msg->getDisplay() : '';
1546 $html_output .= $table_html;
1547 $html_output .= isset($indexes_problems_html) ? $indexes_problems_html : '';
1548 $html_output .= isset($bookmark_support_html) ? $bookmark_support_html : '';
1549 $html_output .= '</div>'; // end sqlqueryresults div
1551 return $html_output;
1555 * Returns a message for successful creation of a bookmark or null if a bookmark
1556 * was not created
1558 * @return Message $bookmark_created_msg
1560 function PMA_getBookmarkCreatedMessage()
1562 if (isset($_GET['label'])) {
1563 $bookmark_created_msg = Message::success(
1564 __('Bookmark %s has been created.')
1566 $bookmark_created_msg->addParam($_GET['label']);
1567 } else {
1568 $bookmark_created_msg = null;
1571 return $bookmark_created_msg;
1575 * Function to get html for the sql query results table
1577 * @param DisplayResults $displayResultsObject instance of DisplayResult
1578 * @param string $pmaThemeImage theme image uri
1579 * @param string $url_query url query
1580 * @param array $displayParts the parts to display
1581 * @param bool $editable whether the result table is
1582 * editable or not
1583 * @param int $unlim_num_rows unlimited number of rows
1584 * @param int $num_rows number of rows
1585 * @param bool $showtable whether to show table or not
1586 * @param object $result result of the executed query
1587 * @param array $analyzed_sql_results analyzed sql results
1588 * @param bool $is_limited_display Show only limited operations or not
1590 * @return String
1592 function PMA_getHtmlForSqlQueryResultsTable($displayResultsObject,
1593 $pmaThemeImage, $url_query, $displayParts,
1594 $editable, $unlim_num_rows, $num_rows, $showtable, $result,
1595 $analyzed_sql_results, $is_limited_display = false
1597 $printview = isset($_REQUEST['printview']) && $_REQUEST['printview'] == '1' ? '1' : null;
1598 $table_html = '';
1599 $browse_dist = ! empty($_REQUEST['is_browse_distinct']);
1601 if ($analyzed_sql_results['is_procedure']) {
1603 do {
1604 if (! isset($result)) {
1605 $result = $GLOBALS['dbi']->storeResult();
1607 $num_rows = $GLOBALS['dbi']->numRows($result);
1609 if ($result !== false && $num_rows > 0) {
1611 $fields_meta = $GLOBALS['dbi']->getFieldsMeta($result);
1612 $fields_cnt = count($fields_meta);
1614 $displayResultsObject->setProperties(
1615 $num_rows,
1616 $fields_meta,
1617 $analyzed_sql_results['is_count'],
1618 $analyzed_sql_results['is_export'],
1619 $analyzed_sql_results['is_func'],
1620 $analyzed_sql_results['is_analyse'],
1621 $num_rows,
1622 $fields_cnt,
1623 $GLOBALS['querytime'],
1624 $pmaThemeImage,
1625 $GLOBALS['text_dir'],
1626 $analyzed_sql_results['is_maint'],
1627 $analyzed_sql_results['is_explain'],
1628 $analyzed_sql_results['is_show'],
1629 $showtable,
1630 $printview,
1631 $url_query,
1632 $editable,
1633 $browse_dist
1636 $displayParts = array(
1637 'edit_lnk' => $displayResultsObject::NO_EDIT_OR_DELETE,
1638 'del_lnk' => $displayResultsObject::NO_EDIT_OR_DELETE,
1639 'sort_lnk' => '1',
1640 'nav_bar' => '1',
1641 'bkm_form' => '1',
1642 'text_btn' => '1',
1643 'pview_lnk' => '1'
1646 $table_html .= $displayResultsObject->getTable(
1647 $result,
1648 $displayParts,
1649 $analyzed_sql_results,
1650 $is_limited_display
1654 $GLOBALS['dbi']->freeResult($result);
1655 unset($result);
1657 } while ($GLOBALS['dbi']->moreResults() && $GLOBALS['dbi']->nextResult());
1659 } else {
1660 if (isset($result) && $result) {
1661 $fields_meta = $GLOBALS['dbi']->getFieldsMeta($result);
1662 $fields_cnt = count($fields_meta);
1664 $_SESSION['is_multi_query'] = false;
1665 $displayResultsObject->setProperties(
1666 $unlim_num_rows,
1667 $fields_meta,
1668 $analyzed_sql_results['is_count'],
1669 $analyzed_sql_results['is_export'],
1670 $analyzed_sql_results['is_func'],
1671 $analyzed_sql_results['is_analyse'],
1672 $num_rows,
1673 $fields_cnt, $GLOBALS['querytime'],
1674 $pmaThemeImage, $GLOBALS['text_dir'],
1675 $analyzed_sql_results['is_maint'],
1676 $analyzed_sql_results['is_explain'],
1677 $analyzed_sql_results['is_show'],
1678 $showtable,
1679 $printview,
1680 $url_query,
1681 $editable,
1682 $browse_dist
1685 $table_html .= $displayResultsObject->getTable(
1686 $result,
1687 $displayParts,
1688 $analyzed_sql_results,
1689 $is_limited_display
1691 $GLOBALS['dbi']->freeResult($result);
1694 return $table_html;
1698 * Function to get html for the previous query if there is such. If not will return
1699 * null
1701 * @param string $disp_query display query
1702 * @param bool $showSql whether to show sql
1703 * @param array $sql_data sql data
1704 * @param string $disp_message display message
1706 * @return string $previous_update_query_html
1708 function PMA_getHtmlForPreviousUpdateQuery($disp_query, $showSql, $sql_data,
1709 $disp_message
1711 // previous update query (from tbl_replace)
1712 if (isset($disp_query) && ($showSql == true) && empty($sql_data)) {
1713 $previous_update_query_html = PMA\libraries\Util::getMessage(
1714 $disp_message, $disp_query, 'success'
1716 } else {
1717 $previous_update_query_html = null;
1720 return $previous_update_query_html;
1724 * To get the message if a column index is missing. If not will return null
1726 * @param string $table current table
1727 * @param string $db current database
1728 * @param boolean $editable whether the results table can be editable or not
1729 * @param boolean $has_unique whether there is a unique key
1731 * @return Message $message
1733 function PMA_getMessageIfMissingColumnIndex($table, $db, $editable, $has_unique)
1735 if (!empty($table) && ($GLOBALS['dbi']->isSystemSchema($db) || !$editable)) {
1736 $missing_unique_column_msg = Message::notice(
1737 sprintf(
1739 'Current selection does not contain a unique column.'
1740 . ' Grid edit, checkbox, Edit, Copy and Delete features'
1741 . ' are not available. %s'
1743 PMA\libraries\Util::showDocu(
1744 'config',
1745 'cfg_RowActionLinksWithoutUnique'
1749 } elseif (! empty($table) && ! $has_unique) {
1750 $missing_unique_column_msg = Message::notice(
1751 sprintf(
1753 'Current selection does not contain a unique column.'
1754 . ' Grid edit, Edit, Copy and Delete features may result in'
1755 . ' undesired behavior. %s'
1757 PMA\libraries\Util::showDocu(
1758 'config',
1759 'cfg_RowActionLinksWithoutUnique'
1763 } else {
1764 $missing_unique_column_msg = null;
1767 return $missing_unique_column_msg;
1771 * Function to get html to display problems in indexes
1773 * @param string $query_type query type
1774 * @param array|null $selectedTables array of table names selected from the
1775 * database structure page, for an action
1776 * like check table, optimize table,
1777 * analyze table or repair table
1778 * @param string $db current database
1780 * @return string
1782 function PMA_getHtmlForIndexesProblems($query_type, $selectedTables, $db)
1784 // BEGIN INDEX CHECK See if indexes should be checked.
1785 if (isset($query_type)
1786 && $query_type == 'check_tbl'
1787 && isset($selectedTables)
1788 && is_array($selectedTables)
1790 $indexes_problems_html = '';
1791 foreach ($selectedTables as $tbl_name) {
1792 $check = PMA\libraries\Index::findDuplicates($tbl_name, $db);
1793 if (! empty($check)) {
1794 $indexes_problems_html .= sprintf(
1795 __('Problems with indexes of table `%s`'), $tbl_name
1797 $indexes_problems_html .= $check;
1800 } else {
1801 $indexes_problems_html = null;
1804 return $indexes_problems_html;
1808 * Function to display results when the executed query returns non empty results
1810 * @param object $result executed query results
1811 * @param array $analyzed_sql_results analysed sql results
1812 * @param string $db current database
1813 * @param string $table current table
1814 * @param string $message message to show
1815 * @param array $sql_data sql data
1816 * @param DisplayResults $displayResultsObject Instance of DisplayResults
1817 * @param string $pmaThemeImage uri of the theme image
1818 * @param int $unlim_num_rows unlimited number of rows
1819 * @param int $num_rows number of rows
1820 * @param string $disp_query display query
1821 * @param string $disp_message display message
1822 * @param array $profiling_results profiling results
1823 * @param string $query_type query type
1824 * @param array|null $selectedTables array of table names selected
1825 * from the database structure page, for
1826 * an action like check table,
1827 * optimize table, analyze table or
1828 * repair table
1829 * @param string $sql_query sql query
1830 * @param string $complete_query complete sql query
1832 * @return string html
1834 function PMA_getQueryResponseForResultsReturned($result, $analyzed_sql_results,
1835 $db, $table, $message, $sql_data, $displayResultsObject, $pmaThemeImage,
1836 $unlim_num_rows, $num_rows, $disp_query, $disp_message, $profiling_results,
1837 $query_type, $selectedTables, $sql_query, $complete_query
1839 // If we are retrieving the full value of a truncated field or the original
1840 // value of a transformed field, show it here
1841 if (isset($_REQUEST['grid_edit']) && $_REQUEST['grid_edit'] == true) {
1842 PMA_sendResponseForGridEdit($result);
1843 // script has exited at this point
1846 // Gets the list of fields properties
1847 if (isset($result) && $result) {
1848 $fields_meta = $GLOBALS['dbi']->getFieldsMeta($result);
1851 // Should be initialized these parameters before parsing
1852 $showtable = isset($showtable) ? $showtable : null;
1853 $url_query = isset($url_query) ? $url_query : null;
1855 $response = Response::getInstance();
1856 $header = $response->getHeader();
1857 $scripts = $header->getScripts();
1859 $just_one_table = PMA_resultSetHasJustOneTable($fields_meta);
1861 // hide edit and delete links:
1862 // - for information_schema
1863 // - if the result set does not contain all the columns of a unique key
1864 // (unless this is an updatable view)
1865 // - if the SELECT query contains a join or a subquery
1867 $updatableView = false;
1869 $statement = $analyzed_sql_results['statement'];
1870 if ($statement instanceof PhpMyAdmin\SqlParser\Statements\SelectStatement) {
1871 if (!empty($statement->expr)) {
1872 if ($statement->expr[0]->expr === '*') {
1873 $_table = new Table($table, $db);
1874 $updatableView = $_table->isUpdatableView();
1878 if ($analyzed_sql_results['join']
1879 || $analyzed_sql_results['is_subquery']
1880 || count($analyzed_sql_results['select_tables']) !== 1
1882 $just_one_table = false;
1886 $has_unique = PMA_resultSetContainsUniqueKey(
1887 $db, $table, $fields_meta
1890 $editable = ($has_unique
1891 || $GLOBALS['cfg']['RowActionLinksWithoutUnique']
1892 || $updatableView)
1893 && $just_one_table;
1895 $displayParts = array(
1896 'edit_lnk' => $displayResultsObject::UPDATE_ROW,
1897 'del_lnk' => $displayResultsObject::DELETE_ROW,
1898 'sort_lnk' => '1',
1899 'nav_bar' => '1',
1900 'bkm_form' => '1',
1901 'text_btn' => '0',
1902 'pview_lnk' => '1'
1905 if ($GLOBALS['dbi']->isSystemSchema($db) || !$editable) {
1906 $displayParts = array(
1907 'edit_lnk' => $displayResultsObject::NO_EDIT_OR_DELETE,
1908 'del_lnk' => $displayResultsObject::NO_EDIT_OR_DELETE,
1909 'sort_lnk' => '1',
1910 'nav_bar' => '1',
1911 'bkm_form' => '1',
1912 'text_btn' => '1',
1913 'pview_lnk' => '1'
1917 if (isset($_REQUEST['printview']) && $_REQUEST['printview'] == '1') {
1918 $displayParts = array(
1919 'edit_lnk' => $displayResultsObject::NO_EDIT_OR_DELETE,
1920 'del_lnk' => $displayResultsObject::NO_EDIT_OR_DELETE,
1921 'sort_lnk' => '0',
1922 'nav_bar' => '0',
1923 'bkm_form' => '0',
1924 'text_btn' => '0',
1925 'pview_lnk' => '0'
1929 if (isset($_REQUEST['table_maintenance'])) {
1930 $scripts->addFile('makegrid.js');
1931 $scripts->addFile('sql.js');
1932 $table_maintenance_html = '';
1933 if (isset($message)) {
1934 $message = Message::success($message);
1935 $table_maintenance_html = PMA\libraries\Util::getMessage(
1936 $message, $GLOBALS['sql_query'], 'success'
1939 $table_maintenance_html .= PMA_getHtmlForSqlQueryResultsTable(
1940 $displayResultsObject,
1941 $pmaThemeImage, $url_query, $displayParts,
1942 false, $unlim_num_rows, $num_rows, $showtable, $result,
1943 $analyzed_sql_results
1945 if (empty($sql_data) || ($sql_data['valid_queries'] = 1)) {
1946 $response->addHTML($table_maintenance_html);
1947 exit();
1951 if (!isset($_REQUEST['printview']) || $_REQUEST['printview'] != '1') {
1952 $scripts->addFile('makegrid.js');
1953 $scripts->addFile('sql.js');
1954 unset($GLOBALS['message']);
1955 //we don't need to buffer the output in getMessage here.
1956 //set a global variable and check against it in the function
1957 $GLOBALS['buffer_message'] = false;
1960 $previous_update_query_html = PMA_getHtmlForPreviousUpdateQuery(
1961 isset($disp_query) ? $disp_query : null,
1962 $GLOBALS['cfg']['ShowSQL'], isset($sql_data) ? $sql_data : null,
1963 isset($disp_message) ? $disp_message : null
1966 $profiling_chart_html = PMA_getHtmlForProfilingChart(
1967 $url_query, $db, isset($profiling_results) ? $profiling_results :array()
1970 $missing_unique_column_msg = PMA_getMessageIfMissingColumnIndex(
1971 $table, $db, $editable, $has_unique
1974 $bookmark_created_msg = PMA_getBookmarkCreatedMessage();
1976 $table_html = PMA_getHtmlForSqlQueryResultsTable(
1977 $displayResultsObject,
1978 $pmaThemeImage, $url_query, $displayParts,
1979 $editable, $unlim_num_rows, $num_rows, $showtable, $result,
1980 $analyzed_sql_results
1983 $indexes_problems_html = PMA_getHtmlForIndexesProblems(
1984 isset($query_type) ? $query_type : null,
1985 isset($selectedTables) ? $selectedTables : null, $db
1988 $cfgBookmark = Bookmark::getParams();
1989 if ($cfgBookmark) {
1990 $bookmark_support_html = PMA_getHtmlForBookmark(
1991 $displayParts,
1992 $cfgBookmark,
1993 $sql_query, $db, $table,
1994 isset($complete_query) ? $complete_query : $sql_query,
1995 $cfgBookmark['user']
1997 } else {
1998 $bookmark_support_html = '';
2001 $html_output = isset($table_maintenance_html) ? $table_maintenance_html : '';
2003 $html_output .= PMA_getHtmlForSqlQueryResults(
2004 $previous_update_query_html, $profiling_chart_html,
2005 $missing_unique_column_msg, $bookmark_created_msg,
2006 $table_html, $indexes_problems_html, $bookmark_support_html
2009 return $html_output;
2013 * Function to execute the query and send the response
2015 * @param array $analyzed_sql_results analysed sql results
2016 * @param bool $is_gotofile whether goto file or not
2017 * @param string $db current database
2018 * @param string $table current table
2019 * @param bool|null $find_real_end whether to find real end or not
2020 * @param string $sql_query_for_bookmark the sql query to be stored as bookmark
2021 * @param array|null $extra_data extra data
2022 * @param string $message_to_show message to show
2023 * @param string $message message
2024 * @param array|null $sql_data sql data
2025 * @param string $goto goto page url
2026 * @param string $pmaThemeImage uri of the PMA theme image
2027 * @param string $disp_query display query
2028 * @param string $disp_message display message
2029 * @param string $query_type query type
2030 * @param string $sql_query sql query
2031 * @param array|null $selectedTables array of table names selected from the
2032 * database structure page, for an action
2033 * like check table, optimize table,
2034 * analyze table or repair table
2035 * @param string $complete_query complete query
2037 * @return void
2039 function PMA_executeQueryAndSendQueryResponse($analyzed_sql_results,
2040 $is_gotofile, $db, $table, $find_real_end, $sql_query_for_bookmark,
2041 $extra_data, $message_to_show, $message, $sql_data, $goto, $pmaThemeImage,
2042 $disp_query, $disp_message, $query_type, $sql_query, $selectedTables,
2043 $complete_query
2045 if ($analyzed_sql_results == null) {
2046 // Parse and analyze the query
2047 include_once 'libraries/parse_analyze.lib.php';
2048 list(
2049 $analyzed_sql_results,
2050 $db,
2051 $table_from_sql
2052 ) = PMA_parseAnalyze($sql_query, $db);
2053 // @todo: possibly refactor
2054 extract($analyzed_sql_results);
2056 if ($table != $table_from_sql && !empty($table_from_sql)) {
2057 $table = $table_from_sql;
2061 $html_output = PMA_executeQueryAndGetQueryResponse(
2062 $analyzed_sql_results, // analyzed_sql_results
2063 $is_gotofile, // is_gotofile
2064 $db, // db
2065 $table, // table
2066 $find_real_end, // find_real_end
2067 $sql_query_for_bookmark, // sql_query_for_bookmark
2068 $extra_data, // extra_data
2069 $message_to_show, // message_to_show
2070 $message, // message
2071 $sql_data, // sql_data
2072 $goto, // goto
2073 $pmaThemeImage, // pmaThemeImage
2074 $disp_query, // disp_query
2075 $disp_message, // disp_message
2076 $query_type, // query_type
2077 $sql_query, // sql_query
2078 $selectedTables, // selectedTables
2079 $complete_query // complete_query
2082 $response = Response::getInstance();
2083 $response->addHTML($html_output);
2087 * Function to execute the query and send the response
2089 * @param array $analyzed_sql_results analysed sql results
2090 * @param bool $is_gotofile whether goto file or not
2091 * @param string $db current database
2092 * @param string $table current table
2093 * @param bool|null $find_real_end whether to find real end or not
2094 * @param string $sql_query_for_bookmark the sql query to be stored as bookmark
2095 * @param array|null $extra_data extra data
2096 * @param string $message_to_show message to show
2097 * @param string $message message
2098 * @param array|null $sql_data sql data
2099 * @param string $goto goto page url
2100 * @param string $pmaThemeImage uri of the PMA theme image
2101 * @param string $disp_query display query
2102 * @param string $disp_message display message
2103 * @param string $query_type query type
2104 * @param string $sql_query sql query
2105 * @param array|null $selectedTables array of table names selected from the
2106 * database structure page, for an action
2107 * like check table, optimize table,
2108 * analyze table or repair table
2109 * @param string $complete_query complete query
2111 * @return string html
2113 function PMA_executeQueryAndGetQueryResponse($analyzed_sql_results,
2114 $is_gotofile, $db, $table, $find_real_end, $sql_query_for_bookmark,
2115 $extra_data, $message_to_show, $message, $sql_data, $goto, $pmaThemeImage,
2116 $disp_query, $disp_message, $query_type, $sql_query, $selectedTables,
2117 $complete_query
2119 // Handle disable/enable foreign key checks
2120 $default_fk_check = PMA\libraries\Util::handleDisableFKCheckInit();
2122 // Handle remembered sorting order, only for single table query.
2123 // Handling is not required when it's a union query
2124 // (the parser never sets the 'union' key to 0).
2125 // Handling is also not required if we came from the "Sort by key"
2126 // drop-down.
2127 if (! empty($analyzed_sql_results)
2128 && PMA_isRememberSortingOrder($analyzed_sql_results)
2129 && empty($analyzed_sql_results['union'])
2130 && ! isset($_REQUEST['sort_by_key'])
2132 if (! isset($_SESSION['sql_from_query_box'])) {
2133 PMA_handleSortOrder($db, $table, $analyzed_sql_results, $sql_query);
2134 } else {
2135 unset($_SESSION['sql_from_query_box']);
2140 $displayResultsObject = new PMA\libraries\DisplayResults(
2141 $GLOBALS['db'], $GLOBALS['table'], $goto, $sql_query
2143 $displayResultsObject->setConfigParamsForDisplayTable();
2145 // assign default full_sql_query
2146 $full_sql_query = $sql_query;
2148 // Do append a "LIMIT" clause?
2149 if (PMA_isAppendLimitClause($analyzed_sql_results)) {
2150 $full_sql_query = PMA_getSqlWithLimitClause($analyzed_sql_results);
2153 $GLOBALS['reload'] = PMA_hasCurrentDbChanged($db);
2154 $GLOBALS['dbi']->selectDb($db);
2156 // Execute the query
2157 list($result, $num_rows, $unlim_num_rows, $profiling_results, $extra_data)
2158 = PMA_executeTheQuery(
2159 $analyzed_sql_results,
2160 $full_sql_query,
2161 $is_gotofile,
2162 $db,
2163 $table,
2164 isset($find_real_end) ? $find_real_end : null,
2165 isset($sql_query_for_bookmark) ? $sql_query_for_bookmark : null,
2166 isset($extra_data) ? $extra_data : null
2169 // No rows returned -> move back to the calling page
2170 if ((0 == $num_rows && 0 == $unlim_num_rows)
2171 || $analyzed_sql_results['is_affected']
2173 $html_output = PMA_getQueryResponseForNoResultsReturned(
2174 $analyzed_sql_results, $db, $table,
2175 isset($message_to_show) ? $message_to_show : null,
2176 $num_rows, $displayResultsObject, $extra_data,
2177 $pmaThemeImage, isset($result) ? $result : null,
2178 $sql_query, isset($complete_query) ? $complete_query : null
2180 } else {
2181 // At least one row is returned -> displays a table with results
2182 $html_output = PMA_getQueryResponseForResultsReturned(
2183 isset($result) ? $result : null,
2184 $analyzed_sql_results,
2185 $db,
2186 $table,
2187 isset($message) ? $message : null,
2188 isset($sql_data) ? $sql_data : null,
2189 $displayResultsObject,
2190 $pmaThemeImage,
2191 $unlim_num_rows,
2192 $num_rows,
2193 isset($disp_query) ? $disp_query : null,
2194 isset($disp_message) ? $disp_message : null,
2195 $profiling_results,
2196 isset($query_type) ? $query_type : null,
2197 isset($selectedTables) ? $selectedTables : null,
2198 $sql_query,
2199 isset($complete_query) ? $complete_query : null
2203 // Handle disable/enable foreign key checks
2204 PMA\libraries\Util::handleDisableFKCheckCleanup($default_fk_check);
2206 return $html_output;
2210 * Function to define pos to display a row
2212 * @param Int $number_of_line Number of the line to display
2213 * @param Int $max_rows Number of rows by page
2215 * @return Int Start position to display the line
2217 function PMA_getStartPosToDisplayRow($number_of_line, $max_rows = null)
2219 if (null === $max_rows) {
2220 $max_rows = $_SESSION['tmpval']['max_rows'];
2223 return @((ceil($number_of_line / $max_rows) - 1) * $max_rows);
2227 * Function to calculate new pos if pos is higher than number of rows
2228 * of displayed table
2230 * @param String $db Database name
2231 * @param String $table Table name
2232 * @param Int|null $pos Initial position
2234 * @return Int Number of pos to display last page
2236 function PMA_calculatePosForLastPage($db, $table, $pos)
2238 if (null === $pos) {
2239 $pos = $_SESSION['tmpval']['pos'];
2242 $_table = new Table($table, $db);
2243 $unlim_num_rows = $_table->countRecords(true);
2244 //If position is higher than number of rows
2245 if ($unlim_num_rows <= $pos && 0 != $pos) {
2246 $pos = PMA_getStartPosToDisplayRow($unlim_num_rows);
2249 return $pos;