为什么分页不显示数据?

时间:2016-07-25 07:51:15

标签: php mysql pdo

以下是我的代码计算好的结果,当我回应但是试图打印出刚刚赢得的数据时的总计数。

我的代码是:

$query = "SELECT COUNT(*) FROM recent WHERE memberID = '".$uid."'";
$stmt = $db->query($query);
$stmt->execute();

global $per_page;

$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 recent WHERE memberID = '".$uid."' ORDER BY id DESC LIMIT :per_page OFFSET :offset";
$stmt->bindParam(':per_page', $per_page, PDO::PARAM_INT);
$stmt->bindParam(':offset', $offset, PDO::PARAM_INT);
$stmt->execute();

$result = $stmt->fetchAll();

1 个答案:

答案 0 :(得分:0)

使用

配置数据库连接
<?php
$db = new PDO('mysql:host=127.0.0.1;dbname=yourdatabasename;','username','password');
?>

然后使用准备

$query = "SELECT COUNT(*) FROM users WHERE id = ?";
$stmt = $db->prepare($query);
$stmt->execute( array($uid) );

global $per_page;

$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 users WHERE id = '".$uid."' 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->execute();

$result = $stmt->fetchAll();