Hi.
I'm working on my own CMS, i want the script to echo 3 posts in every page, and want the script to echo from the recent post and back to the oldest post. I mean like this:
For example there is totaly 30 posts;
First page => posts 30-29-28
Second page => posts 27-26-25
....
This is my script:
<?php
include('connection.php');
$error = FALSE;
$result = FALSE;
try {
$row = $conn->query("SELECT MAX(id) AS last_id FROM Posts")->fetch(PDO::FETCH_OBJ);
echo $row->last_id;
echo "<hr>";
$last_id = $row->last_id;
$total = $conn->query("SELECT COUNT(id) as rows FROM Posts")
->fetch(PDO::FETCH_OBJ);
$perpage = 3;
$posts = $total->rows;
$pages = floor($posts / $perpage);
$get_pages = isset($_GET['page']) ? $_GET['page'] : 0;
$number = trim($get_pages);
$number = filter_var($number, FILTER_VALIDATE_INT, $data);
$prev = $number - 1;
$next = $number + 1;
if($get_pages == 0){
$b = $last_id - 3;
for($a = $last_id ; $a > $b ; $a--){
$stmt = $conn->prepare("SELECT ID, Title, Author, Content FROM Posts WHERE ID=(:id)");
$stmt->bindParam(':id', $a, PDO::PARAM_INT);
$stmt->execute();
$result = $stmt->fetchAll();
foreach($result as $key => $row) {
echo $row['Title'] . "<br>";
}
}
}else{
echo $get_pages . "<br>";
$b = ($last_id - (3 * $get_pages));
echo $b . "<br>";
$c = $b - 3;
echo $c . "<br>";
for($a = $b ; $a > $c ; $a--){
echo $a . "<br>";
$stmt = $conn->prepare("SELECT ID, Title, Author, Content FROM Posts WHERE ID=(:id)");
$stmt->bindParam(':id', $a, PDO::PARAM_INT);
$stmt->execute();
$result = $stmt->fetchAll();
foreach($result as $key => $row) {
echo $row['Title'] . "<br>";
}
}
}
} catch(PDOException $e) {
echo "Query error:".$sql . "<br>" . $e->getMessage();
}
$conn = null;
?>
<html>
<body>
<?php
if($result && count($result) > 0)
{
echo "<h4>Total pages ($pages)</h4>";
# first page
if($number <= 0)
echo "<span>« prev</span> | <a href=\"?page=$next\">next »</a>";
# last page
elseif($number >= $pages)
echo "<a href=\"?page=$prev\">« prev</a> | <span>next »</span>";
# in range
else
echo "<a href=\"?page=$prev\">« prev</a> | <a href=\"?page=$next\">next »</a>";
}
else
{
echo "<p>No results found.</p>";
}
?>
</body>
</html>
It works but there is only a problem with the IDs that their posts has been deleted. When script send the id number to the db, if the post of the id doesn't exist, so there is nothing to be echo on the page and because of this part:
$c = $b - 3;
for($a = $b ; $a > $c ; $a--){
the script won't look for and call for more than 3 posts even if those posts were empty.