<?php
require('db_info.php');
$recordsPerPage = 5;
if (isset($_GET['page']))
$curPage = $_GET['page'];
else
$curPage = 1;
$startIndex = ($curPage-1) * $recordsPerPage;
try {
$pdoObject = new PDO("mysql:host=$dbhost; dbname=$dbname;", $dbuser, $dbpass);
$sql = "SELECT count(id) FROM usercom";
$statement = $pdoObject->query($sql);
$record = $statement->fetch(PDO::FETCH_ASSOC);
$pages = ceil($record['count(id)']/$recordsPerPage);
$record=null;
$sql = "SELECT * FROM usercom LIMIT $startIndex, $recordsPerPage ORDER BY date DESC";
$statement = $pdoObject->query($sql);
while ( $record = $statement->fetch(PDO::FETCH_ASSOC) ) {
echo '<p>'.$record['date'].'<br/>'.$record['userComment'].'<br/>';
}
$statement->closeCursor();
$pdoObject = null;
} catch (PDOException $e) {
echo 'PDO Exception: '.$e->getMessage();
die();
}?></p>
我正在尝试从数据库中获取结果并使用分页。问题是声明中要求的降序永远不会适用。为什么这不起作用?如果我不添加“ORDER BY date DESC”这一行就可以了,但是当我这样做时会打印出我正在尝试获取非对象的错误。
答案 0 :(得分:2)
你的语法不太正确,
改为使用这个,
$sql = "SELECT * FROM `usercom` ORDER BY `date` DESC LIMIT $startIndex, $recordsPerPage";