Abidas
Abidas

Reputation: 1

PHP Pagination - only 1 page works

I have been messing around, and been trying to make this script work (for later implenting it in my own projects). It works fine, beside that I when I click on a new page, the results doesnt' change..

here is the script:

<?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> "; 
}; 
?>

Upvotes: 0

Views: 373

Answers (1)

snitch182
snitch182

Reputation: 723

Actually there seems nothing fundamentally wrong. Did you try a hard reload in your browser ?

Use this in the unshown head part of your page to get rid of some caching issues:

<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>

I changed some things anyway:

  • $perpage contains the number of entries per page nice in one place
  • never use unsanitized values in sql so I (int)ed the $_GET

--- need this line for the code to show ---

<?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> "; 
}; 
?> 

Upvotes: 1

Related Questions