SQL无效的分页

时间:2017-01-05 10:25:53

标签: php sql

我使用PHP和SQL完成了这个分页。第2页模块中缺少Id 11和12。我无法找出我的错误所在。 这是我的源代码:

<?php
$per_page = 5;
$rec_count = $row['id'];
$total_pages = ceil($rec_count / $per_page);         

if (isset($_GET['page'])) {
    $show_page = $_GET['page']; //current page
    if ($show_page > 0 && $show_page <= $total_pages) {
        $start = ($show_page - 1) * $per_page;
        $end = $start + $per_page;
    } else {
        $start = 0;
        $end = $per_page;
    }
} else {
    $start = 0;
    $end = $per_page;
}

$page = intval($_GET['page']);
$tpages=$total_pages;
if ($page <= 0)
    $page = 1;

$sql = "SELECT COUNT(Id) AS id FROM [Register].[dbo].[RegisData] WHERE DeleteStatus = 1";
$result = sqlsrv_query($conn,$sql); 
$row = sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC);
$rec_count = $row['id'];
$total_pages = ceil($rec_count / $per_page);

$sql1 = "SELECT [Id],[FirstName],[LastName],[ProfilePic],[Gender]
         ,[Email],[MobileNo],[Company],[Designation],[Country],[State],[Address],[City]
         ,[Pincode],[Hobbies],[DietaryHabits],[DeleteStatus] 
        FROM (SELECT *, ROW_NUMBER() OVER (ORDER BY RegId) as row 
        FROM [Register].[dbo].[RegisData]) 
        a WHERE row between $start and $end 
        AND DeleteStatus = 1 
        ORDER BY RegId";

$result = sqlsrv_query($conn,$sql1);
$z = 1;
for ($x=1; $x<=$total_pages; $x++) {
    echo $x;
}  
?> 

1 个答案:

答案 0 :(得分:0)

DeleteStatus = 1结合使用的分页方式总是会创建损坏和不完整的页面(如果您将1到5之间的所有行和{4}的第4行都行,则只会获得4行)

您应该使用SQL的DeleteStatus = 0功能,该功能允许您选择要开始的结果行号以及在LIMIT子句后显示的行数 所以试试

WHERE

有关SQL中$page = intval($_GET['page']); if($page == 0) $page = 1; $per_page = 5; $offset = ($page -1) * $per_page; $sql1 = "SELECT [Id],[FirstName],[LastName],[ProfilePic],[Gender] ,[Email],[MobileNo],[Company],[Designation],[Country],[State],[Address],[City] ,[Pincode],[Hobbies],[DietaryHabits],[DeleteStatus] FROM (SELECT *, ROW_NUMBER() OVER (ORDER BY RegId) as row FROM [Register].[dbo].[RegisData]) a WHERE DeleteStatus = 1 ORDER BY RegId LIMIT {$per_page} OFFSET {$offset}"; 的更多信息,请查看以下简短说明:https://www.techonthenet.com/sql/select_limit.php它真的是您正在寻找的

--- ---- EDIT

由于您不想使用我建议的解决方案(原因不明),您可以尝试对代码进行此更改:

LIMIT

我所做的是将$sql1 = "SELECT [Id],[FirstName],[LastName],[ProfilePic],[Gender] ,[Email],[MobileNo],[Company],[Designation],[Country],[State],[Address],[City] ,[Pincode],[Hobbies],[DietaryHabits],[DeleteStatus] FROM (SELECT *, ROW_NUMBER() OVER (ORDER BY RegId) as row FROM [Register].[dbo].[RegisData] WHERE DeleteStatus = 1) a WHERE row between $start and $end AND DeleteStatus = 1 ORDER BY RegId"; 条件添加到对行进行编号的内部查询中,这样您的过滤器应该按预期工作 - 尽管您应该使用WHERE DeleteStatus = 1

为了防止重复(第1页和第2页都出现重复),您应该在以下情况下进行更改:

LIMIT

到此:

 if ($show_page > 0 && $show_page <= $total_pages) {
    $start = ($show_page - 1) * $per_page;
    $end = $start + $per_page;
}

再次,如果您使用 if ($show_page > 1 && $show_page <= $total_pages) { $start = ($show_page - 1) * $per_page + 1; $end = $start + $per_page; } 这将不是问题