[ Index ]
 

Code source de phpMyAdmin 2.10.3

Accédez au Source d'autres logiciels libres

Classes | Fonctions | Variables | Constantes | Tables

title

Body

[fermer]

/ -> sql.php (source)

   1  <?php
   2  /* $Id: sql.php 10365 2007-05-09 12:55:29Z lem9 $ */
   3  // vim: expandtab sw=4 ts=4 sts=4:
   4  /**
   5   * @todo    we must handle the case if sql.php is called directly with a query
   6   *          what returns 0 rows - to prevent cyclic redirects or includes
   7   */
   8  
   9  /**
  10   * Gets some core libraries
  11   */
  12  require_once  './libraries/common.lib.php';
  13  require_once  './libraries/Table.class.php';
  14  require_once  './libraries/tbl_indexes.lib.php';
  15  require_once  './libraries/check_user_privileges.lib.php';
  16  require_once  './libraries/bookmark.lib.php';
  17  
  18  /**
  19   * Could be coming from a subform ("T" column expander)
  20   */
  21  if (isset($_REQUEST['dontlimitchars'])) {
  22      $dontlimitchars = $_REQUEST['dontlimitchars'];
  23  }
  24  
  25  /**
  26   * Defines the url to return to in case of error in a sql statement
  27   */
  28  // Security checkings
  29  if (!empty($goto)) {
  30      $is_gotofile     = preg_replace('@^([^?]+).*$@s', '\\1', $goto);
  31      if (!@file_exists('./' . $is_gotofile)) {
  32          unset($goto);
  33      } else {
  34          $is_gotofile = ($is_gotofile == $goto);
  35      }
  36  } // end if (security checkings)
  37  
  38  if (empty($goto)) {
  39      $goto = (! isset($table) || ! strlen($table)) ? $cfg['DefaultTabDatabase'] : $cfg['DefaultTabTable'];
  40      $is_gotofile  = true;
  41  } // end if
  42  if (!isset($err_url)) {
  43      $err_url = (!empty($back) ? $back : $goto)
  44               . '?' . PMA_generate_common_url(isset($db) ? $db : '')
  45               . ((strpos(' ' . $goto, 'db_') != 1 && isset($table)) ? '&amp;table=' . urlencode($table) : '');
  46  } // end if
  47  
  48  // Coming from a bookmark dialog
  49  if (isset($fields['query'])) {
  50      $sql_query = $fields['query'];
  51  }
  52  
  53  // This one is just to fill $db
  54  if (isset($fields['dbase'])) {
  55      $db = $fields['dbase'];
  56  }
  57  
  58  // Default to browse if no query set an we have table
  59  // (needed for browsing from DefaultTabTable)
  60  if (! isset($sql_query) && isset($table) && isset($db)) {
  61      require_once  './libraries/bookmark.lib.php';
  62      $book_sql_query = PMA_queryBookmarks($db,
  63          $GLOBALS['cfg']['Bookmark'], '\'' . PMA_sqlAddslashes($table) . '\'',
  64          'label');
  65  
  66      if (! empty($book_sql_query)) {
  67          $sql_query = $book_sql_query;
  68      } else {
  69          $sql_query = 'SELECT * FROM ' . PMA_backquote($table);
  70      }
  71      unset($book_sql_query);
  72  
  73      // set $goto to what will be displayed if query returns 0 rows
  74      $goto = 'tbl_structure.php';
  75  } else {
  76      // Now we can check the parameters
  77      PMA_checkParameters(array('sql_query'));
  78  }
  79  
  80  // instead of doing the test twice
  81  $is_drop_database = preg_match('/DROP[[:space:]]+(DATABASE|SCHEMA)[[:space:]]+/i',
  82      $sql_query);
  83  
  84  /**
  85   * Check rights in case of DROP DATABASE
  86   *
  87   * This test may be bypassed if $is_js_confirmed = 1 (already checked with js)
  88   * but since a malicious user may pass this variable by url/form, we don't take
  89   * into account this case.
  90   */
  91  if (!defined('PMA_CHK_DROP')
  92      && !$cfg['AllowUserDropDatabase']
  93      && $is_drop_database
  94      && !$is_superuser) {
  95      require_once  './libraries/header.inc.php';
  96      PMA_mysqlDie($strNoDropDatabases, '', '', $err_url);
  97  } // end if
  98  
  99  
 100  /**
 101   * Need to find the real end of rows?
 102   */
 103  
 104  if (isset($find_real_end) && $find_real_end) {
 105      $unlim_num_rows = PMA_Table::countRecords($db, $table, true, true);
 106      $pos = @((ceil($unlim_num_rows / $session_max_rows) - 1) * $session_max_rows);
 107  }
 108  /**
 109   * Avoids undefined variables
 110   */
 111  elseif (!isset($pos)) {
 112      $pos = 0;
 113  } else {
 114      /* We need this to be a integer */
 115      $pos = (int)$pos;
 116  }
 117  
 118  /**
 119   * Bookmark add
 120   */
 121  if (isset($store_bkm)) {
 122      PMA_addBookmarks($fields, $cfg['Bookmark'], (isset($bkm_all_users) && $bkm_all_users == 'true' ? true : false));
 123      PMA_sendHeaderLocation($cfg['PmaAbsoluteUri'] . $goto);
 124  } // end if
 125  
 126  
 127  /**
 128   * Gets the true sql query
 129   */
 130  // $sql_query has been urlencoded in the confirmation form for drop/delete
 131  // queries or in the navigation bar for browsing among records
 132  if (isset($btnDrop) || isset($navig)) {
 133      $sql_query = urldecode($sql_query);
 134  }
 135  
 136  /**
 137   * Parse and analyze the query
 138   */
 139  require_once ('./libraries/parse_analyze.lib.php');
 140  
 141  /**
 142   * Sets or modifies the $goto variable if required
 143   */
 144  if ($goto == 'sql.php') {
 145      $is_gotofile = false;
 146      $goto = 'sql.php?'
 147            . PMA_generate_common_url($db, $table)
 148            . '&amp;pos=' . $pos
 149            . '&amp;sql_query=' . urlencode($sql_query);
 150  } // end if
 151  
 152  
 153  /**
 154   * Go back to further page if table should not be dropped
 155   */
 156  if (isset($btnDrop) && $btnDrop == $strNo) {
 157      if (!empty($back)) {
 158          $goto = $back;
 159      }
 160      if ($is_gotofile) {
 161          if (strpos(' ' . $goto, 'db_') == 1 && isset($table) && strlen($table)) {
 162              unset($table);
 163          }
 164          $active_page = $goto;
 165          require './' . PMA_securePath($goto);
 166      } else {
 167          PMA_sendHeaderLocation($cfg['PmaAbsoluteUri'] . str_replace('&amp;', '&', $goto));
 168      }
 169      exit();
 170  } // end if
 171  
 172  
 173  /**
 174   * Displays the confirm page if required
 175   *
 176   * This part of the script is bypassed if $is_js_confirmed = 1 (already checked
 177   * with js) because possible security issue is not so important here: at most,
 178   * the confirm message isn't displayed.
 179   *
 180   * Also bypassed if only showing php code.or validating a SQL query
 181   */
 182  if (!$cfg['Confirm']
 183      || (isset($is_js_confirmed) && $is_js_confirmed)
 184      || isset($btnDrop)
 185  
 186      // if we are coming from a "Create PHP code" or a "Without PHP Code"
 187      // dialog, we won't execute the query anyway, so don't confirm
 188      //|| !empty($GLOBALS['show_as_php'])
 189      || isset($GLOBALS['show_as_php'])
 190  
 191      || !empty($GLOBALS['validatequery'])) {
 192      $do_confirm = false;
 193  } else {
 194      $do_confirm = isset($analyzed_sql[0]['queryflags']['need_confirm']);
 195  }
 196  
 197  if ($do_confirm) {
 198      $stripped_sql_query = $sql_query;
 199      require_once  './libraries/header.inc.php';
 200      if ($is_drop_database) {
 201          echo '<h1 class="warning">' . $strDropDatabaseStrongWarning . '</h1>';
 202      }
 203      echo '<form action="sql.php" method="post">' . "\n"
 204          .PMA_generate_common_hidden_inputs($db, (isset($table)?$table:''));
 205      ?>
 206      <input type="hidden" name="sql_query" value="<?php echo urlencode($sql_query); ?>" />
 207      <input type="hidden" name="zero_rows" value="<?php echo isset($zero_rows) ? PMA_sanitize($zero_rows) : ''; ?>" />
 208      <input type="hidden" name="goto" value="<?php echo $goto; ?>" />
 209      <input type="hidden" name="back" value="<?php echo isset($back) ? PMA_sanitize($back) : ''; ?>" />
 210      <input type="hidden" name="reload" value="<?php echo isset($reload) ? PMA_sanitize($reload) : 0; ?>" />
 211      <input type="hidden" name="purge" value="<?php echo isset($purge) ? PMA_sanitize($purge) : ''; ?>" />
 212      <input type="hidden" name="cpurge" value="<?php echo isset($cpurge) ? PMA_sanitize($cpurge) : ''; ?>" />
 213      <input type="hidden" name="purgekey" value="<?php echo isset($purgekey) ? PMA_sanitize($purgekey) : ''; ?>" />
 214      <input type="hidden" name="show_query" value="<?php echo isset($show_query) ? PMA_sanitize($show_query) : ''; ?>" />
 215      <?php
 216      echo '<fieldset class="confirmation">' . "\n"
 217          .'    <legend>' . $strDoYouReally . '</legend>'
 218          .'    <tt>' . htmlspecialchars($stripped_sql_query) . '</tt>' . "\n"
 219          .'</fieldset>' . "\n"
 220          .'<fieldset class="tblFooters">' . "\n";
 221      ?>
 222      <input type="submit" name="btnDrop" value="<?php echo $strYes; ?>" id="buttonYes" />
 223      <input type="submit" name="btnDrop" value="<?php echo $strNo; ?>" id="buttonNo" />
 224      <?php
 225      echo '</fieldset>' . "\n"
 226         . '</form>' . "\n";
 227  
 228      /**
 229       * Displays the footer and exit
 230       */
 231      require_once  './libraries/footer.inc.php';
 232  } // end if $do_confirm
 233  
 234  
 235  /**
 236   * Executes the query and displays results
 237   */
 238  if (!isset($sql_query)) {
 239      $sql_query = '';
 240  }
 241  
 242  // Defines some variables
 243  // A table has to be created or renamed -> left frame should be reloaded
 244  /**
 245   * @todo use the parser/analyzer
 246   */
 247  
 248  if (empty($reload)
 249      && preg_match('/^(CREATE|ALTER|DROP)\s+(VIEW|TABLE|DATABASE|SCHEMA)\s+/i', $sql_query)) {
 250      $reload           = 1;
 251  }
 252  // Gets the number of rows per page
 253  if (empty($session_max_rows)) {
 254      $session_max_rows = $cfg['MaxRows'];
 255  } elseif ($session_max_rows != 'all') {
 256      $cfg['MaxRows']   = $session_max_rows;
 257  }
 258  // Defines the display mode (horizontal/vertical) and header "frequency"
 259  if (empty($disp_direction)) {
 260      $disp_direction   = $cfg['DefaultDisplay'];
 261  }
 262  if (empty($repeat_cells)) {
 263      $repeat_cells     = $cfg['RepeatCells'];
 264  }
 265  
 266  // SK -- Patch: $is_group added for use in calculation of total number of
 267  //              rows.
 268  //              $is_count is changed for more correct "LIMIT" clause
 269  //              appending in queries like
 270  //                "SELECT COUNT(...) FROM ... GROUP BY ..."
 271  
 272  /**
 273   * @todo detect all this with the parser, to avoid problems finding
 274   * those strings in comments or backquoted identifiers
 275   */
 276  
 277  $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;
 278  if ($is_select) { // see line 141
 279      $is_group = preg_match('@(GROUP[[:space:]]+BY|HAVING|SELECT[[:space:]]+DISTINCT)[[:space:]]+@i', $sql_query);
 280      $is_func =  !$is_group && (preg_match('@[[:space:]]+(SUM|AVG|STD|STDDEV|MIN|MAX|BIT_OR|BIT_AND)\s*\(@i', $sql_query));
 281      $is_count = !$is_group && (preg_match('@^SELECT[[:space:]]+COUNT\((.*\.+)?.*\)@i', $sql_query));
 282      $is_export   = (preg_match('@[[:space:]]+INTO[[:space:]]+OUTFILE[[:space:]]+@i', $sql_query));
 283      $is_analyse  = (preg_match('@[[:space:]]+PROCEDURE[[:space:]]+ANALYSE@i', $sql_query));
 284  } elseif (preg_match('@^EXPLAIN[[:space:]]+@i', $sql_query)) {
 285      $is_explain  = true;
 286  } elseif (preg_match('@^DELETE[[:space:]]+@i', $sql_query)) {
 287      $is_delete   = true;
 288      $is_affected = true;
 289  } elseif (preg_match('@^(INSERT|LOAD[[:space:]]+DATA|REPLACE)[[:space:]]+@i', $sql_query)) {
 290      $is_insert   = true;
 291      $is_affected = true;
 292      if (preg_match('@^(REPLACE)[[:space:]]+@i', $sql_query)) {
 293          $is_replace = true;
 294      }
 295  } elseif (preg_match('@^UPDATE[[:space:]]+@i', $sql_query)) {
 296      $is_affected = true;
 297  } elseif (preg_match('@^SHOW[[:space:]]+@i', $sql_query)) {
 298      $is_show     = true;
 299  } elseif (preg_match('@^(CHECK|ANALYZE|REPAIR|OPTIMIZE)[[:space:]]+TABLE[[:space:]]+@i', $sql_query)) {
 300      $is_maint    = true;
 301  }
 302  
 303  // Do append a "LIMIT" clause?
 304  if (isset($pos)
 305      && (!$cfg['ShowAll'] || $session_max_rows != 'all')
 306      && !($is_count || $is_export || $is_func || $is_analyse)
 307      && isset($analyzed_sql[0]['queryflags']['select_from'])
 308      && !isset($analyzed_sql[0]['queryflags']['offset'])
 309      && !preg_match('@[[:space:]]LIMIT[[:space:]0-9,-]+(;)?$@i', $sql_query)) {
 310      $sql_limit_to_append = " LIMIT $pos, ".$cfg['MaxRows'] . " ";
 311  
 312      $full_sql_query  = $analyzed_sql[0]['section_before_limit'] . "\n" . $sql_limit_to_append . $analyzed_sql[0]['section_after_limit'];
 313      /**
 314       * @todo pretty printing of this modified query
 315       */
 316      if (isset($display_query)) {
 317          // if the analysis of the original query revealed that we found
 318          // a section_after_limit, we now have to analyze $display_query
 319          // to display it correctly
 320  
 321          if (!empty($analyzed_sql[0]['section_after_limit']) && trim($analyzed_sql[0]['section_after_limit']) != ';') {
 322              $analyzed_display_query = PMA_SQP_analyze(PMA_SQP_parse($display_query));
 323              $display_query  = $analyzed_display_query[0]['section_before_limit'] . "\n" . $sql_limit_to_append . $analyzed_display_query[0]['section_after_limit'];
 324          }
 325      }
 326  
 327  } else {
 328      $full_sql_query      = $sql_query;
 329  } // end if...else
 330  
 331  if (isset($db)) {
 332      PMA_DBI_select_db($db);
 333  }
 334  
 335  // If the query is a DELETE query with no WHERE clause, get the number of
 336  // rows that will be deleted (mysql_affected_rows will always return 0 in
 337  // this case)
 338  // Note: testing shows that this no longer applies since MySQL 4.0.x
 339  
 340  if (PMA_MYSQL_INT_VERSION < 40000) {
 341      if ($is_delete
 342          && preg_match('@^DELETE([[:space:]].+)?(FROM[[:space:]](.+))$@i', $sql_query, $parts)
 343          && !preg_match('@[[:space:]]WHERE[[:space:]]@i', $parts[3])) {
 344          $cnt_all_result = @PMA_DBI_try_query('SELECT COUNT(*) as count ' .  $parts[2]);
 345          if ($cnt_all_result) {
 346              list($num_rows) = PMA_DBI_fetch_row($cnt_all_result);
 347              PMA_DBI_free_result($cnt_all_result);
 348          } else {
 349              $num_rows   = 0;
 350          }
 351      }
 352  }
 353  
 354  //  E x e c u t e    t h e    q u e r y
 355  
 356  // Only if we didn't ask to see the php code (mikebeck)
 357  if (isset($GLOBALS['show_as_php']) || !empty($GLOBALS['validatequery'])) {
 358      unset($result);
 359      $num_rows = 0;
 360  } else {
 361      // garvin: Measure query time.
 362      // TODO-Item http://sourceforge.net/tracker/index.php?func=detail&aid=571934&group_id=23067&atid=377411
 363      $querytime_before = array_sum(explode(' ', microtime()));
 364  
 365      $result   = @PMA_DBI_try_query($full_sql_query, null, PMA_DBI_QUERY_STORE);
 366  
 367      $querytime_after = array_sum(explode(' ', microtime()));
 368  
 369      $GLOBALS['querytime'] = $querytime_after - $querytime_before;
 370  
 371      // Displays an error message if required and stop parsing the script
 372      if ($error        = PMA_DBI_getError()) {
 373          require_once  './libraries/header.inc.php';
 374          $full_err_url = (preg_match('@^(db|tbl)_@', $err_url))
 375                        ? $err_url . '&amp;show_query=1&amp;sql_query=' . urlencode($sql_query)
 376                        : $err_url;
 377          PMA_mysqlDie($error, $full_sql_query, '', $full_err_url);
 378      }
 379      unset($error);
 380  
 381      // Gets the number of rows affected/returned
 382      // (This must be done immediately after the query because
 383      // mysql_affected_rows() reports about the last query done)
 384  
 385      if (!$is_affected) {
 386          $num_rows = ($result) ? @PMA_DBI_num_rows($result) : 0;
 387      } elseif (!isset($num_rows)) {
 388          $num_rows = @PMA_DBI_affected_rows();
 389      }
 390  
 391      // Checks if the current database has changed
 392      // This could happen if the user sends a query like "USE `database`;"
 393      $res = PMA_DBI_query('SELECT DATABASE() AS \'db\';');
 394      $row = PMA_DBI_fetch_row($res);
 395      if (isset($db) && is_array($row) && isset($row[0]) && (strcasecmp($db, $row[0]) != 0)) {
 396          $db     = $row[0];
 397          $reload = 1;
 398      }
 399      @PMA_DBI_free_result($res);
 400      unset($res, $row);
 401  
 402      // tmpfile remove after convert encoding appended by Y.Kawada
 403      if (function_exists('PMA_kanji_file_conv')
 404          && (isset($textfile) && file_exists($textfile))) {
 405          unlink($textfile);
 406      }
 407  
 408      // Counts the total number of rows for the same 'SELECT' query without the
 409      // 'LIMIT' clause that may have been programatically added
 410  
 411      if (empty($sql_limit_to_append)) {
 412          $unlim_num_rows         = $num_rows;
 413          // if we did not append a limit, set this to get a correct
 414          // "Showing rows..." message
 415          $GLOBALS['session_max_rows'] = 'all';
 416      } elseif ($is_select) {
 417  
 418              //    c o u n t    q u e r y
 419  
 420              // If we are "just browsing", there is only one table,
 421              // and no where clause (or just 'WHERE 1 '),
 422              // so we do a quick count (which uses MaxExactCount)
 423              // because SQL_CALC_FOUND_ROWS
 424              // is not quick on large InnoDB tables
 425  
 426              // but do not count again if we did it previously
 427              // due to $find_real_end == true
 428  
 429              if (!$is_group
 430               && !isset($analyzed_sql[0]['queryflags']['union'])
 431               && !isset($analyzed_sql[0]['table_ref'][1]['table_name'])
 432               && (empty($analyzed_sql[0]['where_clause'])
 433                 || $analyzed_sql[0]['where_clause'] == '1 ')
 434               && !isset($find_real_end)
 435               ) {
 436  
 437                  // "j u s t   b r o w s i n g"
 438                  $unlim_num_rows = PMA_Table::countRecords($db, $table, true);
 439  
 440              } else { // n o t   " j u s t   b r o w s i n g "
 441  
 442                  if (PMA_MYSQL_INT_VERSION < 40000) {
 443  
 444                      // detect this case:
 445                      // SELECT DISTINCT x AS foo, y AS bar FROM sometable
 446  
 447                      if (isset($analyzed_sql[0]['queryflags']['distinct'])) {
 448                          $count_what = 'DISTINCT ';
 449                          $first_expr = true;
 450                          foreach ($analyzed_sql[0]['select_expr'] as $part) {
 451                              $count_what .= (!$first_expr ? ', ' : '') . $part['expr'];
 452                              $first_expr = false;
 453                          }
 454                       } else {
 455                           $count_what = '*';
 456                       }
 457                      // this one does not apply to VIEWs
 458                      $count_query = 'SELECT COUNT(' . $count_what . ') AS count';
 459                  }
 460  
 461                  // add the remaining of select expression if there is
 462                  // a GROUP BY or HAVING clause
 463                  if (PMA_MYSQL_INT_VERSION < 40000
 464                   && $count_what =='*'
 465                   && (!empty($analyzed_sql[0]['group_by_clause'])
 466                      || !empty($analyzed_sql[0]['having_clause']))) {
 467                      $count_query .= ' ,' . $analyzed_sql[0]['select_expr_clause'];
 468                  }
 469  
 470                  if (PMA_MYSQL_INT_VERSION >= 40000) {
 471                       // add select expression after the SQL_CALC_FOUND_ROWS
 472  
 473                          // for UNION, just adding SQL_CALC_FOUND_ROWS
 474                          // after the first SELECT works.
 475  
 476                          // take the left part, could be:
 477                          // SELECT
 478                          // (SELECT
 479                          $count_query = PMA_SQP_formatHtml($parsed_sql, 'query_only', 0, $analyzed_sql[0]['position_of_first_select'] + 1);
 480                          $count_query .= ' SQL_CALC_FOUND_ROWS ';
 481                          // add everything that was after the first SELECT
 482                          $count_query .= PMA_SQP_formatHtml($parsed_sql, 'query_only', $analyzed_sql[0]['position_of_first_select']+1);
 483                          // ensure there is no semicolon at the end of the
 484                          // count query because we'll probably add
 485                          // a LIMIT 1 clause after it
 486                          $count_query = rtrim($count_query);
 487                          $count_query = rtrim($count_query, ';');
 488                  } else { // PMA_MYSQL_INT_VERSION < 40000
 489  
 490                      if (!empty($analyzed_sql[0]['from_clause'])) {
 491                          $count_query .= ' FROM ' . $analyzed_sql[0]['from_clause'];
 492                      }
 493                      if (!empty($analyzed_sql[0]['where_clause'])) {
 494                          $count_query .= ' WHERE ' . $analyzed_sql[0]['where_clause'];
 495                      }
 496                      if (!empty($analyzed_sql[0]['group_by_clause'])) {
 497                          $count_query .= ' GROUP BY ' . $analyzed_sql[0]['group_by_clause'];
 498                      }
 499                      if (!empty($analyzed_sql[0]['having_clause'])) {
 500                          $count_query .= ' HAVING ' . $analyzed_sql[0]['having_clause'];
 501                      }
 502                  } // end if
 503  
 504                  // if using SQL_CALC_FOUND_ROWS, add a LIMIT to avoid
 505                  // long delays. Returned count will be complete anyway.
 506                  // (but a LIMIT would disrupt results in an UNION)
 507  
 508                  if (PMA_MYSQL_INT_VERSION >= 40000
 509                  && !isset($analyzed_sql[0]['queryflags']['union'])) {
 510                      $count_query .= ' LIMIT 1';
 511                  }
 512  
 513                  // run the count query
 514  
 515                  if (PMA_MYSQL_INT_VERSION < 40000) {
 516                      if ($cnt_all_result = PMA_DBI_try_query($count_query)) {
 517                          if ($is_group && $count_what == '*') {
 518                              $unlim_num_rows = @PMA_DBI_num_rows($cnt_all_result);
 519                          } else {
 520                              $unlim_num_rows = PMA_DBI_fetch_assoc($cnt_all_result);
 521                              $unlim_num_rows = $unlim_num_rows['count'];
 522                          }
 523                          PMA_DBI_free_result($cnt_all_result);
 524                      } else {
 525                          if (PMA_DBI_getError()) {
 526  
 527                              // there are some cases where the generated
 528                              // count_query (for MySQL 3) is wrong,
 529                              // so we get here.
 530                              /**
 531                               * @todo use a big unlimited query to get the correct
 532                               * number of rows (depending on a config variable?)
 533                               */
 534                              $unlim_num_rows = 0;
 535                          }
 536                      }
 537                  } else {
 538                      PMA_DBI_try_query($count_query);
 539                      // if (mysql_error()) {
 540                      // void.
 541                      // I tried the case
 542                      // (SELECT `User`, `Host`, `Db`, `Select_priv` FROM `db`)
 543                      // UNION (SELECT `User`, `Host`, "%" AS "Db",
 544                      // `Select_priv`
 545                      // FROM `user`) ORDER BY `User`, `Host`, `Db`;
 546                      // and although the generated count_query is wrong
 547                      // the SELECT FOUND_ROWS() work! (maybe it gets the
 548                      // count from the latest query that worked)
 549                      //
 550                      // another case where the count_query is wrong:
 551                      // SELECT COUNT(*), f1 from t1 group by f1
 552                      // and you click to sort on count(*)
 553                      // }
 554                      $cnt_all_result       = PMA_DBI_query('SELECT FOUND_ROWS() as count;');
 555                      list($unlim_num_rows) = PMA_DBI_fetch_row($cnt_all_result);
 556                      @PMA_DBI_free_result($cnt_all_result);
 557                  }
 558          } // end else "just browsing"
 559  
 560      } else { // not $is_select
 561           $unlim_num_rows         = 0;
 562      } // end rows total count
 563  
 564      // garvin: if a table or database gets dropped, check column comments.
 565      if (isset($purge) && $purge == '1') {
 566          require_once  './libraries/relation_cleanup.lib.php';
 567  
 568          if (isset($table) && isset($db) && strlen($table) && strlen($db)) {
 569              PMA_relationsCleanupTable($db, $table);
 570          } elseif (isset($db) && strlen($db)) {
 571              PMA_relationsCleanupDatabase($db);
 572          } else {
 573              // garvin: VOID. No DB/Table gets deleted.
 574          } // end if relation-stuff
 575       } // end if ($purge)
 576  
 577      // garvin: If a column gets dropped, do relation magic.
 578      if (isset($cpurge) && $cpurge == '1' && isset($purgekey)
 579        && isset($db) && isset($table)
 580        && strlen($db) && strlen($table) && !empty($purgekey)) {
 581          require_once  './libraries/relation_cleanup.lib.php';
 582          PMA_relationsCleanupColumn($db, $table, $purgekey);
 583  
 584      } // end if column PMA_* purge
 585  } // end else "didn't ask to see php code"
 586  
 587  // No rows returned -> move back to the calling page
 588  if ($num_rows < 1 || $is_affected) {
 589      if ($is_delete) {
 590          $message = $strDeletedRows . '&nbsp;' . $num_rows;
 591      } elseif ($is_insert) {
 592          if ($is_replace) {
 593              /* For replace we get DELETED + INSERTED row count, so we have to call it affected */
 594              $message = $strAffectedRows . '&nbsp;' . $num_rows;
 595          } else {
 596              $message = $strInsertedRows . '&nbsp;' . $num_rows;
 597          }
 598          $insert_id = PMA_DBI_insert_id();
 599          if ($insert_id != 0) {
 600              // insert_id is id of FIRST record inserted in one insert, so if we inserted multiple rows, we had to increment this
 601              $message .= '[br]'.$strInsertedRowId . '&nbsp;' . ($insert_id + $num_rows - 1);
 602          }
 603      } elseif ($is_affected) {
 604          $message = $strAffectedRows . '&nbsp;' . $num_rows;
 605  
 606          // Ok, here is an explanation for the !$is_select.
 607          // The form generated by sql_query_form.lib.php
 608          // and db_sql.php has many submit buttons
 609          // on the same form, and some confusion arises from the
 610          // fact that $zero_rows is sent for every case.
 611          // The $zero_rows containing $strSuccess and sent with
 612          // the form should not have priority over
 613          // errors like $strEmptyResultSet
 614      } elseif (!empty($zero_rows) && !$is_select) {
 615          $message = $zero_rows;
 616      } elseif (!empty($GLOBALS['show_as_php'])) {
 617          $message = $strShowingPhp;
 618      } elseif (isset($GLOBALS['show_as_php'])) {
 619          /* User disable showing as PHP, query is only displayed */
 620          $message = $strShowingSQL;
 621      } elseif (!empty($GLOBALS['validatequery'])) {
 622          $message = $strValidateSQL;
 623      } else {
 624          $message = $strEmptyResultSet;
 625      }
 626  
 627      $message .= ' ' . (isset($GLOBALS['querytime']) ? '(' . sprintf($strQueryTime, $GLOBALS['querytime']) . ')' : '');
 628  
 629      if ($is_gotofile) {
 630          $goto = PMA_securePath($goto);
 631          // Checks for a valid target script
 632          $is_db = $is_table = false;
 633          include  'libraries/db_table_exists.lib.php';
 634          if (strpos($goto, 'tbl_') === 0 && ! $is_table) {
 635              if (isset($table)) {
 636                  unset($table);
 637              }
 638              $goto = 'db_sql.php';
 639          }
 640          if (strpos($goto, 'db_') === 0 && ! $is_db) {
 641              if (isset($db)) {
 642                  unset($db);
 643              }
 644              $goto = 'main.php';
 645          }
 646          // Loads to target script
 647          if (strpos($goto, 'db_') === 0
 648           || strpos($goto, 'tbl_') === 0) {
 649              $js_to_run = 'functions.js';
 650          }
 651          if ($goto != 'main.php') {
 652              require_once  './libraries/header.inc.php';
 653          }
 654          $active_page = $goto;
 655          require './' . $goto;
 656      } else {
 657          // avoid a redirect loop when last record was deleted
 658          if ('sql.php' == $cfg['DefaultTabTable']) {
 659              $goto = str_replace('sql.php','tbl_structure.php',$goto);
 660          }
 661          PMA_sendHeaderLocation($cfg['PmaAbsoluteUri'] . str_replace('&amp;', '&', $goto) . '&message=' . urlencode($message));
 662      } // end else
 663      exit();
 664  } // end no rows returned
 665  
 666  // At least one row is returned -> displays a table with results
 667  else {
 668      // Displays the headers
 669      if (isset($show_query)) {
 670          unset($show_query);
 671      }
 672      if (isset($printview) && $printview == '1') {
 673          require_once  './libraries/header_printview.inc.php';
 674      } else {
 675          $js_to_run = 'functions.js';
 676          unset($message);
 677          if (isset($table) && strlen($table)) {
 678              require  './libraries/tbl_common.php';
 679              $url_query .= '&amp;goto=tbl_sql.php&amp;back=tbl_sql.php';
 680              require  './libraries/tbl_info.inc.php';
 681              require  './libraries/tbl_links.inc.php';
 682          } elseif (isset($db) && strlen($db)) {
 683              require  './libraries/db_common.inc.php';
 684              require  './libraries/db_info.inc.php';
 685          } else {
 686              require  './libraries/server_common.inc.php';
 687              require  './libraries/server_links.inc.php';
 688          }
 689      }
 690  
 691      if (isset($db) && strlen($db)) {
 692          require_once  './libraries/relation.lib.php';
 693          $cfgRelation = PMA_getRelationsParam();
 694      }
 695  
 696      // Gets the list of fields properties
 697      if (isset($result) && $result) {
 698          $fields_meta = PMA_DBI_get_fields_meta($result);
 699          $fields_cnt  = count($fields_meta);
 700      }
 701  
 702      // Display previous update query (from tbl_replace)
 703      if (isset($disp_query) && $cfg['ShowSQL'] == true) {
 704          $tmp_sql_query = $GLOBALS['sql_query'];
 705          $GLOBALS['sql_query'] = $disp_query;
 706          PMA_showMessage($disp_message);
 707          $GLOBALS['sql_query'] = $tmp_sql_query;
 708      }
 709  
 710      // Displays the results in a table
 711      require_once  './libraries/display_tbl.lib.php';
 712      if (empty($disp_mode)) {
 713          // see the "PMA_setDisplayMode()" function in
 714          // libraries/display_tbl.lib.php
 715          $disp_mode = 'urdr111101';
 716      }
 717      if (!isset($dontlimitchars)) {
 718          $dontlimitchars = 0;
 719      }
 720  
 721      // hide edit and delete links for information_schema
 722      if (PMA_MYSQL_INT_VERSION >= 50002 && isset($db) && $db == 'information_schema') {
 723          $disp_mode = 'nnnn110111';
 724      }
 725  
 726      PMA_displayTable($result, $disp_mode, $analyzed_sql);
 727      PMA_DBI_free_result($result);
 728  
 729      // BEGIN INDEX CHECK See if indexes should be checked.
 730      if (isset($query_type) && $query_type == 'check_tbl' && isset($selected) && is_array($selected)) {
 731          foreach ($selected AS $idx => $tbl_name) {
 732              $indexes        = $indexes_info = $indexes_data = array();
 733              $tbl_ret_keys   = PMA_get_indexes(urldecode($tbl_name), $err_url_0);
 734  
 735              PMA_extract_indexes($tbl_ret_keys, $indexes, $indexes_info, $indexes_data);
 736  
 737              $idx_collection = PMA_show_indexes(urldecode($tbl_name), $indexes, $indexes_info, $indexes_data, false);
 738              $check          = PMA_check_indexes($idx_collection);
 739              if (!empty($check)) {
 740                  ?>
 741  <table border="0" cellpadding="2" cellspacing="0">
 742      <tr>
 743          <td class="tblHeaders" colspan="7"><?php printf($strIndexWarningTable, urldecode($tbl_name)); ?></td>
 744      </tr>
 745      <?php echo $check; ?>
 746  </table>
 747                  <?php
 748              }
 749          }
 750      } // End INDEX CHECK
 751  
 752      // Bookmark support if required
 753      if ($disp_mode[7] == '1'
 754          && (isset($cfg['Bookmark']) && ! empty($cfg['Bookmark']['db']) && ! empty($cfg['Bookmark']['table']) && empty($id_bookmark))
 755          && !empty($sql_query)) {
 756          echo "\n";
 757  
 758          $goto = 'sql.php?'
 759                . PMA_generate_common_url($db, $table)
 760                . '&amp;pos=' . $pos
 761                . '&amp;session_max_rows=' . $session_max_rows
 762                . '&amp;disp_direction=' . $disp_direction
 763                . '&amp;repeat_cells=' . $repeat_cells
 764                . '&amp;dontlimitchars=' . $dontlimitchars
 765                . '&amp;sql_query=' . urlencode($sql_query)
 766                . '&amp;id_bookmark=1';
 767  
 768          ?>
 769  <form action="sql.php" method="post" onsubmit="return emptyFormElements(this, 'fields[label]');">
 770  <?php echo PMA_generate_common_hidden_inputs(); ?>
 771  <input type="hidden" name="goto" value="<?php echo $goto; ?>" />
 772  <input type="hidden" name="fields[dbase]" value="<?php echo htmlspecialchars($db); ?>" />
 773  <input type="hidden" name="fields[user]" value="<?php echo $cfg['Bookmark']['user']; ?>" />
 774  <input type="hidden" name="fields[query]" value="<?php echo urlencode(isset($complete_query) ? $complete_query : $sql_query); ?>" />
 775  <fieldset>
 776      <legend><?php
 777       echo ($cfg['PropertiesIconic'] ? '<img class="icon" src="' . $pmaThemeImage . 'b_bookmark.png" width="16" height="16" alt="' . $strBookmarkThis . '" />' : '')
 778          . $strBookmarkThis;
 779  ?>
 780      </legend>
 781  
 782      <div class="formelement">
 783          <label for="fields_label_"><?php echo $strBookmarkLabel; ?>:</label>
 784          <input type="text" id="fields_label_" name="fields[label]" value="" />
 785      </div>
 786  
 787      <div class="formelement">
 788          <input type="checkbox" name="bkm_all_users" id="bkm_all_users" value="true" />
 789          <label for="bkm_all_users"><?php echo $strBookmarkAllUsers; ?></label>
 790      </div>
 791  
 792      <div class="clearfloat"></div>
 793  </fieldset>
 794  <fieldset class="tblFooters">
 795      <input type="submit" name="store_bkm" value="<?php echo $strBookmarkThis; ?>" />
 796  </fieldset>
 797  </form>
 798          <?php
 799      } // end bookmark support
 800  
 801      // Do print the page if required
 802      if (isset($printview) && $printview == '1') {
 803          ?>
 804  <script type="text/javascript" language="javascript">
 805  //<![CDATA[
 806  // Do print the page
 807  window.onload = function()
 808  {
 809      if (typeof(window.print) != 'undefined') {
 810          window.print();
 811      }
 812  }
 813  //]]>
 814  </script>
 815          <?php
 816      } // end print case
 817  } // end rows returned
 818  
 819  /**
 820   * Displays the footer
 821   */
 822  require_once  './libraries/footer.inc.php';
 823  ?>


Généré le : Mon Nov 26 15:18:20 2007 par Balluche grâce à PHPXref 0.7
  Clicky Web Analytics