2013-01-12 51 views
0

我一直在嘗試解決分頁問題,​​但我不明白以下代碼。使用PHP和SQL進行分頁

   $lstart = ($page * 6) -6; 
       $lend = ($page * 6)-1; 
       $limit = $lstart.','.$lend; 

我得到的結果是混合的。我應該每頁獲得六篇文章,但不一致。代碼被合併到我從其他人繼承的腳本中,我正在嘗試修復它。有人可以向我解釋這段代碼嗎?在查詢中,LIMIT = $ limit。

+1

如果這是'LIMIT start,number',它不是'start/stop'上下文。它以* 35開頭,給我下一個'30' *。所以從這一點來看它並不正確。 –

回答

2

它應該是...

$lstart = ($page * 6) -6; // quite frankly, it's clearer to write... 
     // ($page - 1) * 6 
$limit = $lstart.',6'; 

在極限的第二條聲明有多少項目。沒有達到某一點。


從MySQL文檔:(複製/粘貼)

SELECT * FROM tbl LIMIT 5,10; # Retrieve rows 6-15 

所以,1,10將行2-11 因此,要獲得第1行,你需要設置的偏移量爲零:0,10這會給你第1-10行。

您還可以檢查出進一步的教程上限制這兒的: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 
+0

與喬納森的迴應非常相似。唯一的區別是他的代碼中的+1。我也嘗試過你,並得到了相同的結果。所有的文章在一個頁面上。 – Learner

+0

@Learner在Johanathan的'$ lstart =($ page - 1)* 6 + 1;'中回答'+ 1'實際上是錯誤的,除非你想從第二條記錄開始。偏移值從零開始。你可以通過mysql文檔來確認:http://dev.mysql.com/doc/refman/5.5/en/select.html以及測試。如果您獲得所有結果,則意味着您在其他地方有錯誤,而不是在特定的「0,6」字符串中。編輯:我已經編輯了我的答案,從mysql文檔摘錄顯示偏移如何工作。 – Grumpy

+0

我改變了我的查詢來讀取限制5,10,我用上面的代碼Slstart =($ page-1)* 6和Slimit = $ lstart。 ,6' ;我有5條記錄,seond頁面出現sql語法錯誤。 Johnathan的確給我發了一個他的代碼的更正,但它沒有幫助。 – Learner