如何在PHP中对Mysql表进行分页

时间:2011-07-13 10:37:07

标签: php mysql html-table

我在mysql中有一个表。 因为它有很多行,我想在页面中放置每10行,然后单击链接向我显示10行。 有什么解决方案吗?

2 个答案:

答案 0 :(得分:12)

真的很棒http://www.phpsimplicity.com/tips.php?id=1

这很简单!无需与大班一起工作!我很高兴:D

 <html>

<head>
<title>Paginate</title>
</head>
<body>
<form method='get'>
<?PHP
$connection=Mysql_connect('server','user','pass');
        if(!$connection)
        {
            echo 'connection is invalid';
        }
        else
        {
            Mysql_select_db('DB',$connection);

        }
//check if the starting row variable was passed in the URL or not
if (!isset($_GET['startrow']) or !is_numeric($_GET['startrow'])) {
  //we give the value of the starting row to 0 because nothing was found in URL
  $startrow = 0;
//otherwise we take the value from the URL
} else {
  $startrow = (int)$_GET['startrow'];
}
//this part goes after the checking of the $_GET var
$fetch = mysql_query("SELECT * FROM sample LIMIT $startrow, 10")or
die(mysql_error());
   $num=Mysql_num_rows($fetch);
        if($num>0)
        {
        echo "<table border=2>";
        echo "<tr><td>ID</td><td>Drug</td><td>quantity</td></tr>";
        for($i=0;$i<$num;$i++)
        {
        $row=mysql_fetch_row($fetch);
        echo "<tr>";
        echo"<td>$row[0]</td>";
        echo"<td>$row[1]</td>";
        echo"<td>$row[2]</td>";
        echo"</tr>";
        }//for
        echo"</table>";
        }
//now this is the link..
echo '<a href="'.$_SERVER['PHP_SELF'].'?startrow='.($startrow+10).'">Next</a>';

$prev = $startrow - 10;

//only print a "Previous" link if a "Next" was clicked
if ($prev >= 0)
    echo '<a href="'.$_SERVER['PHP_SELF'].'?startrow='.$prev.'">Previous</a>';
?>
</form>
</body>
</html>

顺便说一下rickyduck的链接也很好

答案 1 :(得分:1)

我建议查看此链接:http://php.about.com/od/phpwithmysql/ss/php_pagination.htm以获取基本分页。此外,如果你有javascript的知识,你可以使用jQuery。