blog::getAllPosts PHP Method

getAllPosts() public method

public getAllPosts ( $orderBy = "desc" )
    function getAllPosts($orderBy = "desc")
    {
        require_once $_SERVER['DOCUMENT_ROOT'] . DIRECTORY_SEPARATOR . "classes" . DIRECTORY_SEPARATOR . "settings.class.php";
        $settings = new settings();
        if ($settings::db_driver == "xml") {
            // XML
            $posts = array();
            $blogPosts = simplexml_load_file($_SERVER['DOCUMENT_ROOT'] . DIRECTORY_SEPARATOR . "data" . DIRECTORY_SEPARATOR . "blogPosts.xml");
            foreach ($blogPosts as $blogPost) {
                $posts[] = array("title" => $blogPost->title, "date" => $blogPost->date, "author" => $blogPost->author, "contents" => $blogPost->contents);
            }
            // Sort the results by date either desc or asc.
            if (strtolower($orderBy) == "desc") {
                usort($posts, function ($a, $b) {
                    return strtotime($b["date"]) - strtotime($a["date"]);
                });
            } else {
                usort($posts, function ($a, $b) {
                    return strtotime($a["date"]) - strtotime($b["date"]);
                });
            }
        } else {
            // PDO
            require_once $_SERVER['DOCUMENT_ROOT'] . DIRECTORY_SEPARATOR . "classes" . DIRECTORY_SEPARATOR . "common.class.php";
            $common = new common();
            $dbh = $common->pdoOpen();
            $sql = "SELECT * FROM " . $settings::db_prefix . "blogPosts ORDER BY date " . $orderBy;
            $sth = $dbh->prepare($sql);
            $sth->execute();
            $posts = $sth->fetchAll(PDO::FETCH_ASSOC);
            $sth = NULL;
            $dbh = NULL;
            return $posts;
        }
        return $posts;
    }

Usage Example

示例#1
0
/////////////////////////////////////////////////////////////////////////////////////
session_start();
// Load the require PHP classes.
require_once '../../classes/common.class.php';
require_once '../../classes/account.class.php';
require_once '../../classes/blog.class.php';
$common = new common();
$account = new account();
$blog = new blog();
// Check if the user is logged in.
if (!$account->isAuthenticated()) {
    // The user is not logged in so forward them to the login page.
    header("Location: login.php");
}
// Get titles and dates for all blog posts.
$allPosts = $blog->getAllPosts();
// Pagination.
$itemsPerPage = 10;
$page = isset($_GET['page']) ? $_GET['page'] : 1;
$posts = $common->paginateArray($allPosts, $page, $itemsPerPage - 1);
////////////////
// BEGIN HTML
require_once '../includes/header.inc.php';
?>

            <h1>Blog Management</h1>
            <hr />
            <h2>Blog Posts</h2>
            <a href="/admin/blog/add.php" class="btn btn-info" style="margin-bottom:  10px;" role="button">Add Post</a>
            <div class="table-responsive">
                <table class="table table-striped table-condensed">