如果数据库中没有记录,则分页错误

时间:2016-08-05 11:32:12

标签: php mysql pdo

所以如果我的偏移为0,我会得到一个负面结果,如

var_dump($offset);
var_dump($per_page);
var_dump($uid);

float(-10) 
int(10) 
int(4)

我的代码是

$query = "SELECT COUNT(*) FROM applied WHERE memberID = :memberID";
        $stmt = $db->prepare($query);
        $stmt->bindParam(':memberID', $uid, PDO::PARAM_INT);
        $stmt->execute();
        $total = $stmt->fetchColumn();    

$pages = ceil($total / $per_page);

$page = min($pages, filter_input(INPUT_GET, 'page', FILTER_VALIDATE_INT, array(
'options' => array(
'default'   => 1,
'min_range' => 1,
),
)));

$offset = ($page - 1)  * $per_page; 

$query = "SELECT * FROM applied WHERE memberID = :memberID ORDER BY id DESC LIMIT :per_page OFFSET :offset";

         $stmt = $db->prepare($query);
         $stmt->bindParam(':per_page', $per_page, PDO::PARAM_INT);
         $stmt->bindParam(':offset', $offset, PDO::PARAM_INT);
         $stmt->bindParam(':memberID', $uid, PDO::PARAM_INT);
         $stmt->execute();

$result = $stmt->fetchAll();

这是一个解决方案

$offset = ($page - 1)  * $per_page; 
if($offset < 0){
$offset = 10;
}

或者这里有人可以告诉我更好的方法来处理这个问题

感谢您的帮助

2 个答案:

答案 0 :(得分:1)

使用PHP的abs函数始终确保您的偏移是正数。

$offset = abs(($page - 1)  * $per_page);

答案 1 :(得分:0)

将您的代码修改为:

$query = "SELECT COUNT(*) FROM applied WHERE memberID = :memberID";
        $stmt = $db->prepare($query);
        $stmt->bindParam(':memberID', $uid, PDO::PARAM_INT);
        $stmt->execute();
        $total = $stmt->fetchColumn();    

$pages = ceil($total / $per_page);

$page = min($pages, filter_input(INPUT_GET, 'page', FILTER_VALIDATE_INT, array(
'options' => array(
'default'   => 1,
'min_range' => 1,
),
)));

$offset = ($page - 1)  * $per_page; 

$query = "SELECT * FROM applied WHERE memberID = :memberID ORDER BY id DESC LIMIT :per_page".($offset>0?" OFFSET :offset":"");

$stmt = $db->prepare($query);
$stmt->bindParam(':per_page', $per_page, PDO::PARAM_INT);
if ($offset > 0) {
    $stmt->bindParam(':offset', $offset, PDO::PARAM_INT);
}
$stmt->bindParam(':memberID', $uid, PDO::PARAM_INT);
$stmt->execute();

$result = $stmt->fetchAll();