选择第n页而不是第n页

时间:2011-01-10 00:19:12

标签: php mysql

我有一个网页,用于分析我的MySQL数据库的结果。以下代码用于创建下拉菜单以导航结果。目前它被设置为选择页面 n ;这假设当我请求第30页(例如)时,相关记录存储在结果集的第30行,但是从某些测试来看,情况并非如此。我应该如何更改它以便它返回 n 页面呢?我知道这是需要调整的while语句,但我无法弄明白。

    //…previous code…

    $rowsPerPage = 1;

    // by default we show first page
    $pageNum = 1;

    // if $_GET['page'] defined, use it as page number
    if(isset($_GET['page']))
    {
        $pageNum = $_GET['page'];
    }

    $offset = ($pageNum - 1) * $rowsPerPage;

    $query3 = 'SELECT t1.s_name AS t1_sname, t1.uh_heading AS t1_unit, t1.ut_latin AS t1_latin, t1.ut_english AS t1_english, t1.uh_id, t1.chapter_sequence AS t1_chapters, t1.unit_sequence AS t1_units, 
                      t2.s_name AS t2_sname, t2.ut_latin AS t2_latin, t2.ut_english AS t2_english, t2.chapter_sequence AS t2_chapters, t2.unit_sequence AS t2_units
               FROM vw_source_text_and_translation AS t1
               LEFT JOIN vw_source_text_and_translation AS t2
               ON (t2.uh_id = t1.uh_id AND t2.s_id = " ' . $_SESSION['source2'] . ' " )
               WHERE t1.s_id =  " ' . $_SESSION['source1'] . ' "
               ORDER BY t1.chapter_sequence, t1.unit_sequence' .
               " LIMIT $offset, $rowsPerPage";

//...more code...

    $query4   = 'SELECT uh_id, chapter_sequence, unit_sequence, uh_heading 
             FROM vw_source_text_and_translation 
             WHERE s_id = "' . $_SESSION['source1'] . '"';

//...more code...

    $rows= $result4;
    $numrows = 0;
    $nav  = '';
    while ($row = mysql_fetch_assoc($rows)) 
    {
      $nav .= ' <option value="'. $row['uh_id'] .'"> '. 
              $row['chapter_sequence'] .'.'.$row['unit_sequence'] .
              ' - '. $row['uh_heading'] .'</option>';
      $numrows ++;
    }

    /*…more code… */

好的,所以在一些帮助下,这部分是固定的; while语句现在读作:

while ($row = mysql_fetch_assoc($rows)) 
 {
  $numrows ++;
  $nav .= ' <option value=" ' . $numrows . '"> '. $row['chapter_sequence'] .'.'.
             $row['unit_sequence'] .' - '. $row['uh_heading'] .'</option>';
 }

这修复了分页,虽然我仍然遇到一些问题,即某些记录没有显示,即使我在MySQL Toolkit中使用$ _SESSION ['source1']和$ _SESSION ['source2']的设置值运行$ query3它工作正常。似乎如果t2.ut_latin或t2.ut_english有一个NULL值,那么即使它识别出已经分页的记录,也不会显示任何数据。但是,我想这超出了这个问题的主题,所以我可能不得不在一个新问题中重新发布。

1 个答案:

答案 0 :(得分:1)

您应该使用带偏移量的LIMIT子句。

SELECT col1, col2, col3
FROM yourtable
ORDER BY something
LIMIT 40, 10

计算偏移量乘以页码(从0开始)乘以每页的行数。