简体   繁体   中英

Limiting number of database entries shown per page

How would we select just, lets say 12 database entries per page, and then push 12 more onto the next page and so on and so forth?

This would be implementing pagination from boostrap, so:

<ul class="pagination">
  <li><a href="#">1</a></li>
  <li><a href="#">2</a></li>
  <li><a href="#">3</a></li>
  <li><a href="#">4</a></li>
  <li><a href="#">5</a></li>
</ul>

and if it helps here is some php, this is just the basic form that I used to grab and display the entires, but they all appear on one page right now.

$id = (empty($_GET['id'])) ? : $_GET['id'] ;

$query = "SELECT title,whole FROM stories ";
$stmt = $db->prepare($query);

$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
//delete this-> $info = mysql_fetch_array($query1);   ?
while($row = $stmt->fetch(PDO::FETCH_ASSOC))
{

    ?>
    <div class="left">
       <a href="">
          <span class="text-content"><span><?php echo htmlentities($row["whole"]); ?></span></span>
       </a>
    </div>
    <?php
}

?>

Based on your code examples, you could easily use LIMIT and OFFSET in your query to enable pagination.

SELECT title, whole FROM stories LIMIT 12 OFFSET 0

The above query would show the 12 results.

<?php
$per_page = 12;
$id = (empty($_GET['id'])) ? 0 : $_GET['id'] ;
$offset = $per_page * $id;
$query = "SELECT title, whole FROM stories LIMIT :limit OFFSET :offset";
$stmt = $db->prepare($query);
$stmt->bindParam(":limit", $per_page, PDO::PARAM_INT);
$stmt->bindParam(":offset", $offset, PDO::PARAM_INT);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
//delete this-> $info = mysql_fetch_array($query1);   ?
while($row = $stmt->fetch(PDO::FETCH_ASSOC))
{

    ?>
    <div class="left">
       <a href="">
          <span class="text-content"><span><?php echo htmlentities($row["whole"]); ?></span></span>
       </a>
    </div>
    <?php
}

This isn't tested , but it should point you in the right direction.

Here is a link to a more in-depth explanation .

To get the total number of posts you can use query like SELECT COUNT(*) AS num_rows FROM stories , divide the total number of posts with posts per page to build the pagination links.

To retrieve the posts for the current page build your query by using LIMIT clause [LIMIT {[offset,] row_count | row_count OFFSET offset}] [LIMIT {[offset,] row_count | row_count OFFSET offset}] , for example:

$post_per_page = 12;
$page = $_GET['page'];

$sql = sprintf( "SELECT title, whole FROM stories LIMIT %d, %d", $post_per_page*$page, $post_per_page );

MySql SELECT Syntax

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM