PHP每页显示n个帖子

时间:2017-12-21 01:25:33

标签: php mysql mysqli

我看过其他类似于我正在尝试做的帖子,但我似乎无法弄清楚我做错了什么。我需要显示5 / n结果,其中n =来自我的SQL查询的总数。我尝试过做其他人的建议,但由于某种原因,我得到了非常奇怪的结果,我似乎无法解决问题。

$sqlPosts = "SELECT
                count(post_owner)
                FROM post_table";

  $stmt = $db -> prepare($sqlPosts);
  $stmt->execute();
  $stmt->store_result();
  $stmt->bind_result($totalPosts);
  $stmt->fetch();

  $sql = "SELECT
              body_of_post,
              date_time,
              post_owner,
              title,
              id
          FROM
              post_table
          ORDER BY
              date_time
          DESC LIMIT
              ?,?";
  $sqlFive = 5;
  $sqlTotal = $totalPosts/$sqlFive;
  $page = ($page - 1) * $limit;
  $stmt = $db -> prepare($sql);
  $stmt->bind_param('dd',$sqlFive, $sqlTotal);
  $stmt->execute();
  $stmt->store_result();
  $stmt->bind_result($body_of_post, $date_time, $post_owner, $title, $id);

  echo "<p> Number of results found: ".(($stmt->num_rows)/2)."/".$stmt->num_rows."</p>";
  echo '<a href=\"index.php?page='.$page.'\">Next '.$page.'</a>';

这是我得到的结果:

找到的结果数量:1/2

下一步0

它应该是这样的:

找到的结果数量:5/10

接下来5

有人请向我解释我做错了什么以及如何解决这个问题?在查询中使用OFFSET会更容易吗?

1 个答案:

答案 0 :(得分:2)

您使用错误的变量来获取和显示信息:

//I'm assuming that $page exists somewhere before the code you posted
....
$rowsPerPage = 5; //renamed for clarity
$totalPages  = ceil($totalPosts/$rowsPerPage); //we need to round this value up
$offset      = ($page - 1) * $rowsPerPage; //e.g. on $page=2 we need an offset of five rows. Renamed for clarity
$stmt        = $db->prepare($sql);  
$stmt->bind_param('dd', $offset, $rowsPerPage); //OFFSET comes first when using comma notation
$stmt->execute();

$totalPostsOnThisPage = $stmt->num_rows; //to make things clear
//You could also show ($offset + 1) . '-' . ($offset + $totalPostsOnThisPage) . ' of ' . $totalPosts --- output: 6-10 of 10
echo "<p> Number of results found: ". $totalRowsOnThisPage . "/" . $totalPosts ."</p>";
//display next only if has more posts
if ($page < $totalPages) {

    echo '<a href=\"index.php?page='.$page.'\">Next '. $rowsPerPage .'</a>';
}