sql - 确定第一组记录

时间:2014-08-05 04:48:08

标签: php mysql pdo pagination

我想进行分页:

< page >

其中<表示前10个帖子,>表示接下来的10个帖子。

我知道我们可以使用:

对于前10条记录:

SELECT some_column FROM Table WHERE some_column ORDER BY some_column LIMIT 10 

接下来的10条记录:

SELECT some_column FROM Table WHERE some_column ORDER BY some_column LIMIT 10 OFFSET 10

最近10条记录:

SELECT some_column FROM Table WHERE some_column ORDER BY some_column DESC LIMIT 10

问题是:说我正在查看11到20条记录,然后我点击预览1到10条记录。

我希望<在我查看1 - 10 records时消失,这样用户就不会滥用<来停止向数据库发送查询。

P.S。我正在使用托管的mysql服务器。

2 个答案:

答案 0 :(得分:2)

基本上这个想法是:

  • 如果当前页面是第一页(page 1),请隐藏<
  • 如果当前页面是最后一页,请隐藏>

您可以使用$_GET['page']并将其用作当前页面的标记:

http://youdomain.php?page=300

首先,您可以初始化它:

$page = isset($_GET['page']) ? $_GET['page'] : 1;

然后确定最后一页:ceil(total number of rows / how many rows per page)

示例:PDO

$check = $db->query('SELECT COUNT(id) as total FROM TABLE_NAME'); // get total rows
$total_items = $check->fetch(PDO::FETCH_ASSOC)['total']; // 5.4 above (dereference)
$total_pages = ceil($total_items / $limit); // calculate how many pages
// of course this is the last page

现在,只需在两种条件下使用它:

<div class="paging">
    <!-- previous -->
    <?php if($page != 1): ?>
        <a href="?page=<?php echo $page-1; ?>" title="Previous Page">&laquo;</a>
    <?php endif; ?>

    <span><?php echo $page; ?></span> <!-- current page -->

    <!-- next -->
    <?php if($page != $total_pages): ?>
        <a href="?page=<?php echo $page+1; ?>" title="Next Page">&raquo;</a>
    <?php endif; ?>
</div>

示例逻辑:

$db = new PDO('mysql:host=localhost;dbname=DATABASE_NAME;charset=utf8', 'USERNAME', 'PASSWORD');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

// paginate using url get `?page=x` where x is a number
$page = isset($_GET['page']) ? $_GET['page'] : 1;
$limit = 10; // default entries

$check = $db->query('SELECT COUNT(id) as total FROM TABLE_NAME'); // get total rows
$total_items = $check->fetch(PDO::FETCH_ASSOC)['total']; // 5.4 above
$total_pages = ceil($total_items / $limit); // calculate how many pages
$offset = ($page - 1) * $limit; // offset

// using limit offset
$query = $db->query("SELECT * FROM TABLE_NAME LIMIT $offset, $limit");
$results = $query->fetchAll(PDO::FETCH_ASSOC);


?>

<table border="1" cellpadding="10">
    <?php foreach($results as $row): ?>
        <tr>
            <!-- just add other info -->
            <td><?php echo $row['id']; ?></td>
        </tr>
    <?php endforeach; ?>
</table>
<div class="paging">
    <?php if($page != 1): ?>
        <a href="?page=<?php echo $page-1; ?>" title="Previous Page">&laquo;</a>
    <?php endif; ?>
    <span><?php echo $page; ?></span>
    <?php if($page != $total_pages): ?>
        <a href="?page=<?php echo $page+1; ?>" title="Next Page">&raquo;</a>
    <?php endif; ?>
</div>

答案 1 :(得分:0)

 SELECT * FROM tbl LIMIT offset, count