php分页

<?php
header('Content-Type: text/html; charset=utf-8');

//每页显示多少个项目
$pagesize = 6; 

//从地址栏获取?page = 多少来确定哪一页
if (isset($_GET['page']))
{
    $page = $_GET['page'] + 0; //用intval (int)  + 0 的方式来过滤非法的字符
}
else
{
    $page = 1;
}

$startpage = ($page - 1) * $pagesize; // limit X,pagesize 的算法 X是0开始的。



$res = mysql_connect('localhost','root','123456');

if(!$res)
{
    echo 'fail connect!','<br/>';
    echo(mysql_errno().':'.mysql_error());
    exit;
}
//else
//{
//    echo 'connect ok!','<br/>';
//}

mysql_query('set names utf-8',$res);
mysql_query('use test',$res);

//读取到底有多少个项目。用来决定有多少页
$res2 = mysql_query('select count(id) from msg',$res);
if ($res2)
{
    $tcount = mysql_fetch_row($res2);
    $totalcount = $tcount[0];
}
else
{
    $totalcount = 0;
}


//首页
$firstpage = 1;

//末页
if ($totalcount > 0)
{
    $finalpage = ceil($totalcount/$pagesize);
}
else
{
    $finalpage = 1; 
}

//上一页
if ($page > 1)
{
    $prevpage = $page - 1;
}
else
{
    $prevpage = 1;
}

//下一页
if ($page < $finalpage)
{
    $nextpage  = $page + 1;
}
else
{
    $nextpage  = $finalpage;
}

$sql = "select * from msg limit $startpage,$pagesize"; 


$res1 = mysql_query($sql,$res);

$list = array();
if($res1)
{
    while ($tiezi = mysql_fetch_assoc($res1))
    {
        $list[] = $tiezi;
        //print_r($tiezi);
        //echo PHP_EOL;
    }
    
}

mysql_close();
?>
<!DOCTYPE html>
<html lang="zh-CN" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title>New Document</title>
    <meta name="generator" content="" />
    <meta name="author"    content="" />
    <meta name="keywords" content="" />
    <meta name="description" content=""    />
</head>
<body>
    <table>
            <?php foreach( $list as $k => $v )
            { 
            ?>
            <tr>
            <td><?php echo $v['id'] ?></td>
            <td><?php echo $v['content'] ?></td>
            <td><?php echo $v['isread'] ?></td>
            </tr>
            <?php } ?>
    </table>
<div>
    <a href="?page=<?php echo $firstpage ?>">首页</a>
    <a href="?page=<?php echo $prevpage  ?>">前一页</a>
    <a href="?page=<?php echo $nextpage  ?>">下一页</a>
    <a href="?page=<?php echo $finalpage ?>">末页</a><?php echo $totalcount ?>条记录,
    每页<?php echo $pagesize ?>条记录,
    共<?php echo $finalpage ?>页,
    当时第<?php echo $page ?></div>
</body>
</html>
原文地址:https://www.cnblogs.com/zy2012/p/3478536.html