MYSQL / PHP分页显示9页,无论返回的结果是什么

时间:2016-10-11 01:27:53

标签: php mysql pagination

我正在使用以下代码进行事件页面mysql查询以显示当前日期的分页结果,但是它会在分页链接中显示9个页面,即使结果只有3页等等。有人可以帮我识别为什么会这样?

            $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 个答案:

答案 0 :(得分:1)

因为当你计算行数时,你总是在整个表中计算。

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

但是当你获得数据时,你在where子句中有一个关于StartDate的条件。

$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");

因此,您应该在count query中添加相同的StartDate条件。

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

实际上,count(*)将优于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/