2013-01-20 131 views
2

我正在做一個簡單的從數據庫和顯示選擇應用程序,並正在建設分頁去。問題與分頁

這裏是我的代碼:

<?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 › »

回答

2

您正在嘗試使用rowCount()函數來計算查詢返回的行,該函數用於從INSERT,UPDATE,DELETE查詢中返回受影響的行。你需要創建一個計數查詢。

試試這個例子來代替:

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