2012-08-03 124 views
0

我下面的代碼基本上從數據庫中獲得一堆電影,並將數年設置爲數組鍵,然後每年回放每部電影。儘管我的結果越來越長,需要分頁,這一切都很酷。我無法找到任何有助於我的情況的例子,因爲php中的大多數分頁是用於while循環的 - 感謝任何幫助或反饋。我不介意它的jQuery或PHP或兩者的組合。分頁在PHP foreach循環

<?php 
require_once('Connections/timeline.php'); 
mysql_select_db($database_timeline, $timeline); 
// select all the events from the database ordered by date: 
$res = mysql_query("SELECT * FROM film2 ORDER BY `year` ASC"); 
$filmArray = null; 
while($row_res = mysql_fetch_assoc($res)) { 
      $year = $row_res['year']; 
      $filmArray[$year][] = $row_res; 
} 
//for each year in the film array echo out each film within that year 
foreach($filmArray as $year => $films) { 
      echo $year; 
      echo '<br />'; 
      foreach($films as $film) { 
          echo $film['event']; 
          echo '<br />'; 
          echo $film['name']; 
          echo '<br />'; 
         } 
} 

?> 
+0

採取護理:當你介紹分頁,並通過多年的不斷分組薄膜的上述邏輯,則分頁或者不產生相同長度的頁面或在幾個頁面,從一個單一的一年傳播電影。 – arkascha 2012-08-03 08:57:53

+0

我建議只使用一個循環:在第一個while循環期間回顯內容。一年頭部的注射可以用一個簡單的條件來完成,該條件評估當前和最後一部電影的年份是否已經改變。這樣可以避免複製整個數組並使代碼更易於理解。 – arkascha 2012-08-03 09:00:24

回答

0

您需要有GET參數,例如頁面。 網址:本地主機/ film.php頁= 1

然後

if (isset($_GET['page'])) 
    $page = $_GET['page']; 
else 
    $page = 1; 

$entriesPerPage = 20; 
$limitFrom = $page - 1; 
$limitTill = $limitFrom + $entriesPerPage; 

然後你的SQL查詢:

$res = mysql_query("SELECT * FROM film2 ORDER BY `year` ASC LIMIT $limitFrom, $limitTill"); 

而在最後,創建HTML鏈接。

<a href="film.php?page=<?=$page-1?>">Previous</a> 
<a href="film.php?page=<?=$page+1?>">Next</a> 
+0

欣賞這一點 - 只需要看它分解。一直在看複雜的分頁tuts沒有幫助。 – Jeff 2012-08-03 09:14:00

+0

'LIMIT offset,max_row_to_show' not limitFrom and limitTill – Yang 2012-08-03 09:21:14

+0

有什麼區別? – dpitkevics 2012-08-03 09:26:43