实验12-参考:分页操作 Pagination

MySQL 飞快学 305浏览
<?php
require_once 'db_config.php';

$conn = mysqli_connect($host, $user, $pass, $db);
if (!$conn) 
    die("Connection failed: " . mysqli_connect_error());

$itemsPerPage = 10;

$sql = "SELECT COUNT(*) as `total` FROM `country`";
$rs = mysqli_query($conn, $sql);
$row = mysqli_fetch_array($rs);
$total = $row[0];

$totalPages = ceil($total / $itemsPerPage);

$page = (isset($_GET['page']))?$_GET['page']:1;
$start = ($page-1) * $itemsPerPage;
$sql = "select * from country LIMIT $start , $itemsPerPage";
$result= mysqli_query($conn, $sql);
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf8">
<title>所有国家列表</title>
</head>
<body>
<table>
  <tr>
    <td>序号</td>
    <td>国家名称</td>
  </tr>
<?php while($row = mysqli_fetch_array($result)) : ?>  
  <tr> 
    <td><?php echo $row["country_id"];?></td>
    <td><?php echo $row["country"];?></td>
  </tr>  
<?php endwhile; ?>   
</table> 
<p>
    <?php foreach(range(1, $totalPages) as $tp): ?>
        <?php if ($tp==$page) : ?>
            <a href=?page=<?= $tp ?>><font color="red"><?= $tp ?></font></a>
        <?php else : ?>
            <a href=?page=<?= $tp ?>><?= $tp ?></a>      
        <?php endif ?>
    <?php endforeach; ?>
</p>

</body>
</html>