Get up to 80 % extra points for free! More info:

Lesson 7 - NOO-CMS - Displaying articles in PHP

In the previous lesson, NOO-CMS - Article editor in PHP, we created a simple article editor for our content management system in PHP and inserted a homepage article from the MySQL database. In today's lesson, we will create an index page that displays articles.

Error page

Using the article editor create an article with a URL set to "error" and save it into the database. This article will be displayed in case a user tries to access an article that no longer exists.

Article for the error 404 in PHP - Databases in PHP for Beginners

Displaying an article

To print an specific article, we'll create an index.php file and insert the following block of HTML into it:

<!DOCTYPE html>
<html lang="en">

    <head>
        <meta charset="utf-8" />
        <meta name="description" content="<?= htmlspecialchars($article['description']) ?>" />
        <link rel="shortcut icon" href="images/icon.ico" />
        <link rel="stylesheet" href="style.css" type="text/css" />
        <title><?= htmlspecialchars($article['title']) ?></title>
    </head>

    <body>
        <header>
            <div id="logo"><h1>HoBi</h1></div>
            <nav>
                <ul>
                    <li><a href="index.php?article=home">Home</a></li>
                    <li><a href="articles.php">Articles</a></li>
                    <li><a href="index.php?article=contact">Contact</a></li>
                </ul>
            </nav>
        </header>

        <article>
            <div id="centerer">
                <header>
                    <h1><?= htmlspecialchars($article['title']) ?></h1>
                </header>

                <section>
                    <?= $article['content'] ?>
                </section>
                <div class="clear"></div>
            </div>
        </article>

        <footer>
            Created by &copy;HoBi for <a href="http://ict.social">ICT.SOCIAL</a>
            <a href="administration.php">Administration</a>
        </footer>
    </body>
</html>

This time, we use the $article variable to print its data into the HTML head and the article content into the page body.

As you may have guessed, we also need to add a block of PHP over the HTML:

<?php

require('Db.php');
Db::connect('127.0.0.1', 'noocms_db', 'root', '');

if (isset($_GET['article']))
    $url = $_GET['article'];
else
    $url = 'home';

$article = Db::queryOne('
    SELECT *
    FROM article
    WHERE url=?
', $url);
if (!$article)
{
    if ($url != 'error')
    {
        header('Location: index.php?article=error');
        exit();
    }
    else
        die('Requested article was not found');
}

?>

The code is very simple. Once we have a stable connection with the database, we use the GET global array to check whether an article URL address has been entered. If one had been provided, we set the $url variable to whatever it was. If not, we default to the home page.

We load the requested article from the database into the $article variable based on the given URL. If the article retrieval is not successful, we redirect the user to error article. If there was an error while loading the error article (which can happen :) ), we terminate the application with an error message.

That's it! Now let's move over to index.php:

Displaying articles from database in PHP - Databases in PHP for Beginners

As you can see, the article was loaded from the database and it looks just like we wrote it in the editor.

Printing the article list

Our system should be able to print a list of all of the articles in the database as well, ordered from newest to oldest. If an administrator is signed-in, he/she should be able to edit or delete the articles in that list.

Let's create a file named articles.php with the following HTML block:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8" />
    <link rel="shortcut icon" href="images/icon.ico" />
    <link rel="stylesheet" href="style.css" type="text/css" />
    <title>Article list</title>
</head>

<body>
    <header>
        <div id="logo"><h1>HoBi</h1></div>
        <nav>
            <ul>
                <li><a href="index.php?article=home">Home</a></li>
                <li><a href="articles.php">Articles</a></li>
                <li><a href="index.php?article=contact">Contact</a></li>
            </ul>
        </nav>
    </header>

    <article>
        <div id="centerer">
            <header>
                <h1>Article list</h1>
            </header>

            <section>
                <table>
                <?php
                    foreach ($articles as $article)
                    {
                        echo('<tr><td><h2>
                                <a href="index.php?article=' . htmlspecialchars($article['url']) . '">
                                ' . htmlspecialchars($article['title']) . '</a>
                            </h2>' . htmlspecialchars($article['description']));
                            if (!empty($_SESSION['user_admin']))
                                echo(' <a href="editor.php?url=' . htmlspecialchars($article['url']) . '">Edit</a>
                                       <a href="articles.php?remove=' . htmlspecialchars($article['article_id']) . '">Remove</a>
                                ');
                        echo('</td></tr>');
                    }
                ?>
                </table>
            </section>
            <div class="cleaner"></div>
        </div>
    </article>

    <footer>
        Created by &copy;HoBi for <a href="http://ict.social">ICT.SOCIAL</a>
        <a href="administration.php">Administration</a>
    </footer>
    </body>
</html>

Here, we work with the $articles variable, in which the articles from the database are stored. We print them into a table and if an administrator is signed-in, we add links to them so they could remove/edit them as they please. We use the editor.php script for editing, and the articles.php for removing.

Let's add the final block of PHP above the HTML:

<?php
session_start();

require('Db.php');
Db::connect('127.0.0.1', 'noocms_db', 'root', '');

if (isset($_GET['remove']) && !empty($_SESSION['user_admin']))
{
    Db::query('
        DELETE FROM article
        WHERE article_id=?
    ', $_GET['remove']);
    header('Location: articles.php');
    exit();
}

$articles = Db::queryAll('
    SELECT *
    FROM article
    ORDER BY article_id DESC
');

?>

What the condition above means is that if a "remove" parameter is present in GET and an administrator is signed-in, the script deletes the article based on the given ID (that we got from the GET global array). Then, we load all of the articles into the $articles variable using a simple SQL query.

A job well done, guys!

List of the articles in the database in PHP - Databases in PHP for Beginners

Now you can write any number of articles for your blog, company website, or technically, anything you could come up with :)

The point of this course was to get acquainted with databases and you all how to work with them. The next step to improving your skills is to check out our Object-oriented programming in PHP course, where you will find lessons about creating modern information systems, step-by-step. The completed NOO-CMS code can be downloaded from the attachment below.


 

Download

By downloading the following file, you agree to the license terms

Downloaded 754x (395.4 kB)

 

Previous article
NOO-CMS - Article editor in PHP
All articles in this section
Databases in PHP for Beginners
Article has been written for you by David Capka Hartinger
Avatar
User rating:
3 votes
The author is a programmer, who likes web technologies and being the lead/chief article writer at ICT.social. He shares his knowledge with the community and is always looking to improve. He believes that anyone can do what they set their mind to.
Unicorn university David learned IT at the Unicorn University - a prestigious college providing education on IT and economics.
Activities