2016-10-11 86 views
1

我對事件頁面使用以下代碼mysql查詢顯示當前日期的分頁結果,但它將在分頁鏈接中顯示9頁,即使結果只有總共3頁等有人可以幫助我確定這是爲什麼發生?MYSQL/PHP分頁顯示9頁,無論結果是否返回

  $per_page = 25; 
      $pages_query = mysql_query("SELECT COUNT('CompName') FROM my_db"); 
      $pages = ceil(mysql_result($pages_query, 0)/$per_page); 
      $page = (isset($_GET['page'])) ? (int)$_GET['page'] : 1; 
      $start = ($page - 1) * $per_page; 
      $query = mysql_query("SELECT *, DATE_FORMAT(StartDate, '%d/%m/%Y') StartDate, CompName, HostState, Location, competitiontypedesc FROM my_db WHERE StartDate >= CURDATE() LIMIT $start, $per_page"); 

      while($query_row = mysql_fetch_assoc($query)) { 
      echo" 
      <li class='kleo-masonry-item event-item'> 
      <div class='member-inner-list animated animate-when-almost-visible bottom-to-top start-animation grey-border'> 
      <div class='event-cell event-date-cell'> 
      <p class='no-margin'>" . $query_row["StartDate"] . "</p> 
      </div> 
      <div class='event-cell name'> 
      <p class='no-margin'>" . $query_row["CompName"] ." " .$query_row["LastName"]. "</p></div> 
      <div class='event-cell'> 
      <p class='no-margin'>" . $query_row["Location"] . "</p> 
      </div> 
      <div class='event-cell'> 
      <p class='no-margin'>" . $query_row["HostState"] . "</p> 
      </div> 
      </li>" 
      ; 
      } 

      $prev = $page - 1; 
      $next = $page + 1; 

      if(!($page <= 1)){ 
      echo "<a href='?page=$prev'><</a> ";} 

      if($pages >= 1){ 
      for($x=1; $x<=$pages; $x++){ 
      echo ($x == $page) ? '<b><a href="?page='.$x.'">'.$x.'</a></b> ' : '<a href="?page='.$x.'">'.$x.'</a>';} 
      } 

      if(!($page >= $pages)){ 
      echo "<a href='?page=$next'>></a> ";} 
      } 
      } 
+1

請閱讀這個問題:http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php。 – Michas

+0

'echo $ pages'是什麼,'顯示你? –

+0

感謝Michas,實現其折舊並將更新,代碼來自舊教程 – Dexx

回答

1

因爲當你計算行數時,你總是算在整個表中。

$pages_query = mysql_query("SELECT COUNT(`CompName`) FROM my_db"); 

但是,當您獲取數據時,您在StartDate的Where子句中有條件。

$query = mysql_query("SELECT *, DATE_FORMAT(StartDate, '%d/%m/%Y') StartDate, CompName, HostState, Location, competitiontypedesc FROM my_db WHERE StartDate >= CURDATE() LIMIT $start, $per_page"); 

因此,您應該在計數查詢中添加相同的StartDate條件。

$pages_query = mysql_query("SELECT COUNT(`CompName`) FROM my_db WHERE StartDate >= CURDATE()"); 

其實,COUNT(*)將好於計數(CompName)。

$pages_query = mysql_query("SELECT COUNT(*) FROM my_db WHERE StartDate >= CURDATE()"); 

https://www.percona.com/blog/2007/04/10/count-vs-countcol/

+0

如果使用MyISAM表,count(*)將會有更好的性能。 (「SELECT COUNT(*)FROM my_db WHERE StartDate> = CURDATE()」); https://www.percona.com/blog/2007/04/10/count-vs-countcol/ 如果您使用Innodb,count(*)和count('ComName')具有相同的性能。 –

+0

感謝Tung的工作,它現在顯示正確數量的頁面。 – Dexx