Tom Atkinson
Tom Atkinson

Reputation: 31

Sorting the return of a MySQL PHP PDO query

I am creating a website for my network and I have a basic CMS on the home page that shows news articles. It all works apart from one thing, the newest post is at the bottom of the list and the oldest is at the top. I would like the newest at the top and the oldest at the bottom. I am using PDO for fetching the news and PHP to display it. Here is the fetch news code:

<?php
class Article{

    public function fetch_all() {
        global $pdo;
        $query = $pdo->prepare("SELECT * FROM articles");
        $query->execute();
        return $query->fetchAll();
    }

    public function fetch_data($id) {
        global $pdo;
        $query = $pdo->prepare("SELECT * FROM articles WHERE  article_id = ? ");
        $query->bindValue(1, $id);
        $query->execute();
        return $query->fetch();
      }
    }

Upvotes: 3

Views: 2802

Answers (3)

potashin
potashin

Reputation: 44581

You can use order by clause with desc – descending order:

order by article_id desc

Upvotes: 4

John Foley
John Foley

Reputation: 4479

Just modify fetch_all() and you should be good.

public function fetch_all() {
    global $pdo;
    $query = $pdo->prepare("SELECT * FROM articles ORDER BY article_id DESC");
    $query->execute();
    return $query->fetchAll( PDO::FETCH_ASSOC );
}

Upvotes: 1

Andy Hall
Andy Hall

Reputation: 464

$query = $pdo->prepare("SELECT * FROM articles ORDER BY article_date DESC");

Edit: Accidentally copied the wrong query, concept remains the same.

Upvotes: 1

Related Questions