我对PHP很陌生,最近几天我一直在尝试构建我的第一个项目,它主要是作为一个博客工作--这样我就能感觉到如何查询数据库之类的东西。
我现在希望能够在我的页面上分页结果,这是我到目前为止所得到的:
<?php
include_once 'inc/functions.inc.php';
include_once 'inc/db.inc.php';
$db = new PDO(DB_INFO, DB_USER, DB_PASS);
$id = (isset($_GET["id"])) ? (int) $_GET["id"] : NULL;
$e = retrievePosts($db, $id);
$fulldisp = array_pop($e);
?>
<div id="blogposts">
<?php
if ($fulldisp == 1) {
?>
<span class="postdate"><?php echo $e["date"] ?></span>
<span class="posttitle"><?php echo $e["title"] ?></span>
<br/>
<br/>
<span class="postbody">
<?php echo $e["body"] ?>
</span>
<?php
}//end if
else {
foreach ($e as $entry) {
?>
<div class="postholder">
<span class="postdate"><?php echo $entry["date"] ?></span>
<span class="posttitle">
<a href="?id=<?php echo $entry['id'] ?>"><?php echo $entry['title'] ?></a>
</span>
<br/>
<br/>
<span class="postbody">
<?php echo $entry["resume"] ?>
</span>
</div>
<?php
}//end foreach
}//end
?>
</div>这是我的职责:
<?php
function retrievePosts($db, $id = NULL) {
if (isset($id)) { //se foi fornecido ID
$sql = "SELECT title, body, date
FROM blog
WHERE id=?
LIMIT 1";
$stmt = $db->prepare($sql);
$stmt->execute(array($_GET["id"]));
$e = $stmt->fetch(); //guardar em array
$fulldisp = 1; //uma só entrada
}
else
{
$sql = "SELECT id, title, resume, date
FROM blog
ORDER BY date DESC";
foreach($db->query($sql) as $row)
{
$e[] = array("id" => $row["id"], "title" => $row["title"], "resume" => $row["resume"], "date" => $row["date"]);
}
$fulldisp = 0; //multiplas entradas
}
//funçoes só retornam um valor, inserimos fulldisp no fim de $e e separamos
//os valores de novo no index.php
array_push($e, $fulldisp);
return $e;
}
?>按照这种工作方式,页面是根据URL构建的:
如果那里有一个ID,它只显示该id的内容。
如果URL中没有id,那么它现在正在显示页面中的所有条目。
现在我希望能够对这些条目进行分页,所以在查看了Stackoverflow之后,似乎最流行的解决方案是使用Digg样式的分页类,在这里记录了:http://mis-algoritmos.com/digg-style-pagination-class
我已经下载了这个类,但是我不知道如何使这个类正常工作,我对这个类没有DB查询这一事实感到困惑(我预计这将使用极限),我想知道Stack上是否有人可以帮助我在我的代码上实现这个类,或者是否有一个关于如何实现这个类的详细文档。
发布于 2012-09-14 11:34:39
function retrievePosts($db, $id = NULL, $page = 1, $rpp = 5) {
if (isset($id)) { //se foi fornecido ID
$sql = "SELECT title, body, date
FROM blog
WHERE id=?
LIMIT 1";
$stmt = $db->prepare($sql);
$stmt->execute(array($id));
$e = $stmt->fetch(); //guardar em array
$fulldisp = 1; //uma só entrada
}
else
{
if(!is_numeric($page)) {
$page = 1;
}
if(!is_numeric($rpp)) {
$rpp = 5;
}
$sql = "SELECT id, title, resume, date
FROM blog
ORDER BY date DESC
LIMIT ?
OFFSET ?
";
$stmt = $db->prepare($sql);
$stmt->execute(array($page, $rpp * $page));
foreach($stmt->fetch() as $row)
{
$e[] = array("id" => $row["id"], "title" => $row["title"], "resume" => $row["resume"], "date" => $row["date"]);
}
$fulldisp = 0; //multiplas entradas
}
//funçoes só retornam um valor, inserimos fulldisp no fim de $e e separamos
//os valores de novo no index.php
array_push($e, $fulldisp);
return $e;
}$rpp -每页记录
我还认为:
$stmt->execute(array($_GET["id"]));应:
$stmt->execute(array($id));https://stackoverflow.com/questions/12423367
复制相似问题