PHP分页fetchAll()和LIMIT

时间:2012-11-25 23:25:55

标签: php mysql pagination limit fetchall

此代码在第一页上运行良好,但似乎LIMIT不会影响FetchAll()。 所以我的问题是: fetchAll()有一些限制行数的可选参数吗? 或者建议我更好地解决这个问题。

<html>
<body>
<?php
require_once('connection.php');
$rowsCount = $connection->query('SELECT COUNT(*) FROM test')->fetchColumn();
$page = 1;
$perPage = 10;
if ( isset( $_GET["page"] ) and $_GET["page"] >= 1 and $_GET["page"] <= 10 ) {
    $page = (int) $_GET["page"];
  }
$beginning = ($page-1) * $perPage;
$end = $page * $perPage;
$sql = "SELECT * FROM test LIMIT $beginning, $end";

?>
<table border = '2'>
<tr>
    <th width="30%">ID</th>
    <th width="70%">TEXT</th>
</tr>
<?php
// echo '<pre>';
// print_r($connection->query($sql)->fetch());
// echo $sql;
// echo '<pre>';
foreach ($connection->query($sql) as $value) {
    echo '<tr height ="50px"><td>' . $value['id'] . '</td><td>' .   $value['text'] . '</td></tr>';
}
?>
</table>
    <p>
    <?php if($page > 1){ ?>
        <a href="pagination.php?page=<?php echo $page-1;?>" >Previous</a>
    <?php } ?>
        <a href="pagination.php?page=<?php if($page < ceil($rowsCount/$perPage)){ echo $page+1;} else {echo 1;}?>" >Next</a>
    </p>
  </body>
</html>

2 个答案:

答案 0 :(得分:0)

语法不是LIMIT beginning, end,而是LIMIT beginning, maxrows

答案 1 :(得分:0)

更正此行:

$end = $page * $perPage;

使用:

$end = $perPage;

或者将您的sql字符串更改为:

$sql = "SELECT * FROM test LIMIT $beginning, $perPage";