PHP分页 - 只有1页有效

时间:2014-10-11 12:50:53

标签: php html mysql sql pagination

我一直在搞乱,并一直在尝试使这个脚本工作(以后在我自己的项目中实现它)。它工作正常,除了我点击新页面时,结果不会改变..

这是脚本:

<?php 
if (isset($_GET["page"])) { $page  = $_GET["page"]; } else { $page=1; }; 
$start_from = ($page-1) * 5; 
$sql = "SELECT * FROM employee ORDER BY emp_id ASC LIMIT $start_from, 20"; 
$rs_result = mysql_query ($sql); 
?> 
<table>
<tr><td>Name</td><td>Phone</td><td>Salary</td></tr>
<?php 
while ($row = mysql_fetch_assoc($rs_result)) { 
?> 
            <tr>
            <td><?php echo $row['emp_id']; ?></td>
            <td><?php echo $row['emp_name']; ?></td>
            <td><?php echo $row['emp_salary']; ?></td>
            </tr>
<?php 
}; 
?> 
</table>
<?php 
$sql = "SELECT COUNT(emp_name) FROM employee"; 
$rs_result = mysql_query($sql); 
$row = mysql_fetch_row($rs_result); 
$total_records = $row[0]; 
$total_pages = ceil($total_records / 5); 

for ($i=1; $i<=$total_pages; $i++) { 
            echo "<a href='pagination?page=".$i."'>".$i."</a> "; 
}; 
?>

1 个答案:

答案 0 :(得分:1)

实际上似乎没有根本错误。您是否尝试在浏览器中重新加载?

在页面未显示的头部使用此功能来解决一些缓存问题:

<html>
        <head>
            <META HTTP-EQUIV="Pragma" CONTENT="no-cache">
            <META HTTP-EQUIV="Expires" CONTENT="-1">
            <meta http-equiv="cache-control" content="no-cache">
        </head>
...
</html>

无论如何我改变了一些事情:

  • $ perpage包含一页中每页的条目数
  • 从不在sql中使用unsanitized值,所以我(int)编辑了$ _GET

---需要这一行代码才能显示---

<?php 
$perpage = 5;

if (isset($_GET["page"])) { $page  = abs ((int)$_GET["page"]); } else { $page=1; }; 
$start_from = ($page-1) * $perpage; 
$sql = "SELECT * FROM employee ORDER BY emp_id ASC LIMIT $start_from, $perpage"; 
$rs_result = mysql_query ($sql); 
?> 
<table>
<tr><td>Name</td><td>Phone</td><td>Salary</td></tr>
<? php 
while ($row = mysql_fetch_assoc($rs_result)) { 
?> 
            <tr>
            <td><?php echo $row['emp_id']; ?></td>
            <td><?php echo $row['emp_name']; ?></td>
            <td><?php echo $row['emp_salary']; ?></td>
            </tr>
<?php 
}; 
?> 
</table>
<?php 
$sql = "SELECT COUNT(emp_name) FROM employee"; 
$rs_result = mysql_query($sql); 
$row = mysql_fetch_row($rs_result); 
$total_records = $row[0]; 
$total_pages = ceil($total_records / 5); 

for ($i=1; $i<=$total_pages; $i++) { 
            echo "<a href='pagination?page=".$i."'>".$i."</a> "; 
}; 
?>