0

我试图对我的查询进行分页,但没有输出任何内容,任何人都可以看到我哪里出错了吗?我对 PHP/PDO 很陌生

else {
try
    {
    $per_page = '3';
    $result = $conn->prepare("SELECT * FROM directory WHERE user_active != ''");
    $rows = $result ->fetchAll();
    $total_records = count($rows);
    $pages = ceil($total_records / $per_page); 
    $page  = (isset ($_GET['page']))  ? (int) $_GET['page'] : 1 ;
    $start = ($page - 1) *  $per_page; 
    $query = $conn->prepare("SELECT * FROM directory WHERE user_active != ''");
    while($row = $query->fetch(PDO::FETCH_ASSOC)){
    echo '<br>' . $row['id'] . '<br>' . $row['First_Name'] . '<br>' . $row['Surname'] . '<br>';
    } ?>
    <br><br>
    <?php
    if ($pages >=  1 && $page <= $pages){
    //if ($page>1 && $page <= $pages){$previous=($page -1); echo '<a href="?page=' .$previous. '">Previous</a>';}
    for($x=1; $x<=$pages; $x++){ echo ($x == $page) ? ' <strong><a href="?page='.$x.'">'.$x.'</a></strong> ' : ' <a href="?page='.$x.'">'.$x.'</a> ';}
    //if ($page>1  && $page <= $pages){ $next=($page+1) ; echo '<a href="?page=' .$next. '">Next</a>';}
    }
    ####################### Close Database #######################
    $db = NULL;
    }
    catch(PDOException $e)
    {
    print 'Exception : '.$e->getMessage();
    } 
};
4

2 回答 2

2

您永远不会执行查询。

$result->execute();
$rows = $result ->fetchAll();

$query->execute();
while($row = $query->fetch(PDO::FETCH_ASSOC)){
于 2012-11-15T23:02:45.927 回答
1

此外,最好LIMIT在您的查询中使用。像这样的东西:

//to get need page
$per_page = 3;
$page  = (isset ($_GET['page']))  ? (int) $_GET['page'] : 1 ;
$result = $conn->prepare(
    "SELECT * FROM directory 
     WHERE user_active != '' 
     LIMIT ".(($page - 1) *  $per_page).", ".$per_page
);
$result->execute();
$rows = $result ->fetchAll();

//to get count of pages
$result = $conn->prepare(
    "SELECT COUNT(*) FROM directory 
     WHERE user_active != ''"
);
$result->execute();
$total-pages = reset($result->fetch(PDO::FETCH_NUM));
于 2012-11-15T23:22:06.700 回答