我有一个网页可以从我的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,则即使它识别出已分页的记录,也不会显示任何数据。但是,我认为这超出了这个问题的主题,因此我可能不得不在一个新问题中重新发布。
最佳答案
您应该使用带有偏移量的LIMIT子句。
SELECT col1, col2, col3
FROM yourtable
ORDER BY something
LIMIT 40, 10
要计算偏移量,请将页码(从0开始)乘以每页的行数。