Reputation: 77
How to make my posts get ordered by created date instead of being ordered as I create them? So, from the new to the older. Automatically.
<?php
$db = new PDO('mysql:dbname=forum;host=localhost', 'root', '');
// User input
$page = isset($_GET['page']) ? (int)$_GET['page'] :1;
$perPage = isset($_GET['per-page']) && $_GET['per-page'] <= 50 ? (int)$_GET['per-page'] : 5;
// Positioning
$start = ($page > 1) ? ($page * $perPage) - $perPage : 0;
// Query
$posts = $db->prepare(
"
SELECT SQL_CALC_FOUND_ROWS id, title, photo_dir, photo, body, created
FROM posts
LIMIT {$start}, {$perPage}
"
);
$posts->execute();
$posts = $posts->fetchAll(PDO::FETCH_ASSOC);
// Pages
$total = $db->query("SELECT FOUND_ROWS() as total")->fetch()['total'];
$pages = ceil($total / $perPage);
?>
.
<body>
<div id="cont">
<?php foreach($posts as $post): ?>
<h2 id="naslov"><?php echo $post['title']; ?></h2>
<p id="vri"><?php echo $post['created']; ?></p>
<?php endforeach; ?>
<div class="pagination">
...
</div>
</div>
</body>
Upvotes: 3
Views: 229
Reputation: 77
// Query
$posts = $db->prepare(
"
SELECT SQL_CALC_FOUND_ROWS id, title, photo_dir, photo, body, created
FROM posts
ORDER BY created desc
LIMIT {$start}, {$perPage}
"
);
Upvotes: 2