分页问题

时间:2013-01-20 00:00:06

标签: php mysql pdo pagination

我正在制作一个简单的从数据库中选择和显示的应用程序,并正在建立分页以便与它并行。

这是我的代码:

<?php   
   $sqlcount = "SELECT * FROM user where user_id= ?";
   $qcount = $db->prepare($sqlcount);
   $qcount->execute(array($id));
   $qcount->setFetchMode(PDO::FETCH_BOTH);
   $total = $qcount->rowCount();

   // How many items to list per page
   $limit = 10;

   // How many pages will there be
   $pages = ceil($total / $limit);

   // What page are we currently on?
   $page = min($pages, filter_input(INPUT_GET, 'page', FILTER_VALIDATE_INT, array(
                            'options' => array(
                                'default'   => 1,
                                'min_range' => 1,
                            ),
   )));

   // Calculate the offset for the query
   $offset = ($page - 1)  * $limit;

   // Some information to display to the user
   $start = $offset + 1;
   $end = min(($offset + $limit), $total);

   // The "back" link
   $prevlink = ($page > 1) ? '<a href="?page=1" title="First page">&laquo;</a> <a href="?page=' . ($page - 1) . '" title="Previous page">&lsaquo;</a>' : '<span class="disabled">&laquo;</span> <span class="disabled">&lsaquo;</span>';

   // The "forward" link
   $nextlink = ($page < $pages) ? '<a href="?page=' . ($page + 1) . '" title="Next page">&rsaquo;</a> <a href="?page=' . $pages . '" title="Last page">&raquo;</a>' : '<span class="disabled">&rsaquo;</span> <span class="disabled">&raquo;</span>';

   // Display the paging information
   echo '<div id="paging"><p>', $prevlink, ' Page ', $page, ' of ', $pages, ' pages, displaying ', $start, '-', $end, ' of ', $total, ' results ', $nextlink, ' </p></div>';

   $stmt = $db->prepare("SELECT * FROM recipes WHERE user_id = :userid ORDER BY name LIMIT :limit OFFSET :offset");
   $stmt->bindParam(':userid', $id, PDO:: PARAM_INT);
   $stmt->bindParam(':limit', $limit, PDO:: PARAM_INT);
   $stmt->bindParam(':offset', $offset, PDO:: PARAM_INT);
   $stmt->execute();
   $rowcount = $stmt->rowCount();

   echo "<ul id='container'>";
   if(empty($rowcount)){echo"No recipes";}
   while($row = $stmt->fetch()){
    $recipeid = $row['id'];
    $public = $row['public'];

    //here i left out some stuff unimportant to the problem
   }
?>

在我加入分页之前,我的结果已经显示出来了。现在,错误报告没有错误,但显示“No Recipes”和« ‹ Page 0 of 0 pages, displaying -9-0 of 0 results › »

1 个答案:

答案 0 :(得分:2)

您正在尝试使用rowCount()函数计算从查询返回的行,并使用该函数从INSERT,UPDATE,DELETE查询返回受影响的行。您需要创建一个计数查询。

请尝试使用此示例:

$sqlcount = "SELECT COUNT(*) FROM user where user_id= ?";
$qcount = $db->prepare($sqlcount);
$qcount->execute(array($id));
$total = $qcount->fetchColumn();