Lesson 7 - NOO-CMS - Displaying articles in PHP

PHP Databases for beginners 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

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

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

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

Downloaded 167x (395.4 kB)

 

 

Article has been written for you by David Capka
Avatar
Do you like this article?
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 College The author learned IT at the Unicorn College - a prestigious college providing education on IT and economics.
Thumbnail
All articles in this section
Databases in PHP for beginners
Activities (6)

 

 

Comments

Avatar
lawrence njoroge:2/26/2017 0:31

heloo i want some little asistance please, i want to make a code that directs the admin to the administration page and the other users to articles page how to i do that
sign in php code

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

if (isset($_SESSION['user_id']))
{
        header('Location: administration.php');
        exit();
}

if ($_POST)
{
        $user = Db::queryOne('
                SELECT user_id, admin
                FROM user
                WHERE name=? AND password=SHA1(?)
        ', $_POST['name'], $_POST['password'] . "t&#ssdf54gh");
        if (!$user)
                $notice = 'Invalid name or password.';

        if(user)
        {
                $_SESSION['user_id'] = $user['user_id'];
                $_SESSION['user_name'] = $_POST['name'];
                $_SESSION['user_admin'] = $user['admin'];
                header('Location: administration.php');
                exit();
        }
 else
         {$_SESSION['user_id'] = $user['user_id'];
           $_SESSION['user_name'] = $_POST['name'];
           header('Location: reports.php');
           exit();


         }
}
?>

adimistration code

<?php
session_start();
if (!isset(!$_SESSION['user_id']))
{
        header('Location: sign-in.php');
        exit();
}

if (isset($_GET['sign-out']))
{
        session_destroy();
        header('Location: sign-in.php');
        exit();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
        <meta charset="utf-8" />
        <link rel="stylesheet" href="style.css" type="text/css" />
        <title>Administration</title>
</head>

<body>
    <header>
                        <div id="logo"><h1></h1></div>
                <nav>
                        <ul>
                            <li><a href="home.php">Home</a></li>
                                <li><a href="about.php">About us</a></li>
                                <li><a href="members.php">members</a></li>
                                <li><a href="contact.php">Contact</a></li>
                                <li><a href="administration.php?sign-out">Sign-out</a></li>>
                        </ul>
                </nav>
</header>
<article>
        <div id="centerer">
                <header>
                        <h1>Administration</h1>
                </header>
                <section>
                        <p>Welcome to the administration, you're signed in as <?= htmlspecialchars($_SESSION['user_name']) ?>.</p>
                        <?php
                                if ($_SESSION['user_admin'])
                                        echo("You don't have an administrator role, ask the administrator for it.");
                        ?>
                        <h2><a href="editor.php">Article editor</a></h2>
                        <h2><a href="articles.php">Article list</a></h2>
                        <h2> register a new member<a href="sign-up.php">sign-up</a> </h2>
                </section>
                <div class="clear"></div>
        </div>
</article>
    <footer>
        Made by &copy;<a href="http://www.facebook.com/lawnj">lawrence</a>
    </footer>
</body>
</html>
Reply 2/26/2017 0:31
where there is will there is a way
Avatar
IT Man
Member
Avatar
Replies to lawrence njoroge
IT Man:2/26/2017 1:47

You have admin permission in $_SESSION['user_admin'], so use something like this:

if (isset($_SESSION['user_admin']) && $_SESSION['user_admin'] == 1)
{
    header('Location: admin-page.php');
    exit();
}
else
{
    header('Location: article.php');
    exit();
}
Reply 2/26/2017 1:47
Don't be silly and smile!
Avatar
Replies to IT Man
lawrence njoroge:2/26/2017 13:28

still the code doesn't work

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

if (isset($_SESSION['user_id']))
{
        header('Location: administration.php');
        exit();
}

if ($_POST)
{
        $user = Db::queryOne('
                SELECT user_id, admin
                FROM user
                WHERE name=? AND password=SHA1(?)
        ', $_POST['name'], $_POST['password'] . "t&#ssdf54gh");
        if (!$user) {
        $notice = 'Invalid name or password.';
    }else
        {
                $_SESSION['user_id'] = $user['user_id'];
                $_SESSION['user_name'] = $_POST['name'];
     if (isset($_SESSION['user_admin']) && $_SESSION['user_admin'] == 1)
{
    header('Location: administration.php');
    exit();
}
else
{
    header('Location: reports.php');
    exit();
}

        }
}
?>

the admin an other users are taken to the reports.php page

Reply 2/26/2017 13:28
where there is will there is a way
Avatar
IT Man
Member
Avatar
Replies to lawrence njoroge
IT Man:2/26/2017 16:10

Yes, sure. You removed setting permission for $_SESSION. So before if with redirects add this:

$_SESSION['user_admin'] = $user['admin'];
Reply  +1 2/26/2017 16:10
Don't be silly and smile!
Avatar
Replies to IT Man
lawrence njoroge:2/27/2017 11:06

Thank you man 8-)

Reply  +1 2/27/2017 11:06
where there is will there is a way
To maintain the quality of discussion, we only allow registered members to comment. Sign in. If you're new, Sign up, it's free.

5 messages from 5 displayed.