我一直在尝试解决分页问题,但我不理解以下代码。
$lstart = ($page * 6) -6;
$lend = ($page * 6)-1;
$limit = $lstart.','.$lend;
我得到的结果好坏参半。我应该每页得到六篇文章,但它不一致。代码包含在我从其他人继承的脚本中,我正在尝试修复它。有人可以向我解释这段代码吗?在查询中,LIMIT = $ limit。
答案 0 :(得分:2)
应该是......
$lstart = ($page * 6) -6; // quite frankly, it's clearer to write...
// ($page - 1) * 6
$limit = $lstart.',6';
限制中的第二个子句声明了多少项。没达到某一点。
来自mysql docs :(复制/粘贴)
SELECT * FROM tbl LIMIT 5,10; # Retrieve rows 6-15
因此,1,10将是2-11行 因此,要获得第1行,您需要将偏移量设置为零:0,10,这将为您提供1-10行。
您还可以在此处查看有关LIMIT的更多教程:http://php.about.com/od/mysqlcommands/g/Limit_sql.htm
代码说明。
$rows_per_page = 6; // you're trying to get 6 rows for every "page".
// On page 1, you'd want rows 0-5 (6 rows inclusively)
// On page 2, you'd want rows 6-111 (again, 6 rows inclusively)
// and so forth.
// So when $page == 1, you want to start at 0, on page 2, start at 6....
// To express this pattern mathematically, we write:
$start = ($page - 1) * 6
// mysql takes offset and number as it's two variables in the LIMIT clause,
// in that order, when two are provided.
// So we write:
$query = "SELECT * FROM table WHERE 1 LIMIT $start, $rows_per_page;";
// So, at page 1, you get
$query = "SELECT * FROM table WHERE 1 LIMIT 0, 6;"; // if we were to substitute the variables.
$query = "SELECT * FROM table WHERE 1 LIMIT 6, 6;"; // at page 2
$query = "SELECT * FROM table WHERE 1 LIMIT 12, 6;"; // at page 3