Technology Careers
HDFC Data Digits HDFC ERGO Technocrat Kotak Mahindra Bank-PGP in Full Stack Software Engineering CSB Bank-Digital Transformation Skills Program FreeCharge by Axis Bank - FinTech Engineering Program Post Graduate Program in Full Stack Software Engineering
Banking and Finance Careers
Axis Bank – Priority Banking Program Axis Bank Young Bankers Program HDFC - Relationship Manager Axis Bank - Virtual Sales & Relationship Management Program Excelerate - Wealth Manager Program HDFC - Certification in Virtual Relationship Management HDFC- Trade Finance Operations IndusInd Bank – Banking Sales and Business Development Bajaj Finserv – Beyond Program
Add To Bookmark

Building a CMS with PHP and MySQL


By NIIT Editorial

Published on 20/06/2021

10 minutes

A Content Management System (CMS) is a web application that is utilized to oversee contents with tasks such as create, alter and delete content by various users to display to end-users. A CMS commonly has two significant segments: the Content Management Application (CMA), as the front-end UI that permits a client, even with restricted skill, to add, alter, and eliminate content from a site without the intercession of a website admin; and a Content Delivery Application (CDA), that accumulates the substance and updates the site. Many organizations utilize content management systems in their websites to distribute content identified with their business. To understand the concepts of building a software you can check out courses offered by the software institute NIIT.

Getting Started: Create the database

The first thing we have to do is to create a MySQL database to store our content.

  1. Open a terminal window and run the MySQL client program:

 

Terminal

mysql -u username -p

 

  1. Now create the database
    1. In the mysql> prompt, type:

 

Terminal

create database cms;

 

  1. Quit the MySQL client program:

 

Terminal

exit

You’ve created a new and empty database in which you can put the database tables and content.

Create an articles database table

Our CMS has just a single database table: articles. This holds all of the articles in the system. 

Create a text file tables.sql. A table's schema depicts the sorts of information that the table can hold, along with the other data about the table.
 

Text

DROP TABLE IF EXISTS articles;

CREATE TABLE articles

(

  id              smallint unsigned NOT NULL auto_increment,

 

  publicationDate date NOT NULL,                # When the article was published

 

  title           varchar(255) NOT NULL,        # Full title of the article

 

  summary         text NOT NULL,                # A short summary of the article

 

  content         mediumtext NOT NULL,          # The HTML content of the article

 

  PRIMARY KEY     (id)

);

 

The code characterizes the schema for the articles table. It's written in SQL, the language used to create and control information bases in MySQL and some other database systems).

Breakdown of the code:

  • Make the articles table 

DROP TABLE IF EXISTS: Articles eliminate any current articles table and information in the event if that already exists. We do this since we can't characterize a table with a similar name as a current table. 

  • Add the publicationDate field 

The following line makes the publicationDate field, which stores the date that each article was distributed. This field has a data type of date, which implies it can store “date” values.

  • Add the essential key 

The CREATE TABLE characterizes a key for the table. A key can also be called an index, and in basic terms, it makes it faster to discover data in the table, to the detriment of some additional extra room. Therefore, we make the id field a PRIMARY KEY. Each table can have a solitary PRIMARY KEY; this is the key that recognizes each record in the table. Also, by adding this key, MySQL can recover an article dependent on its ID rapidly.
 

Since we've made our table schema, we need to stack it into MySQL to make the actual table. To do this, open up a terminal window and change the folder containing your tables.sql file:

 

Terminal

mysql -u username -p cms < tables.sql


Create a configuration file

 

Since you've made your database, you'll begin to compose your PHP code. 

Create the configuration file to store various settings for the CMS. This file will be utilized by all the script files in the CMS.

In the cms folder, create a file called config.php:

 

Text

<?php

ini_set( "display_errors", true );

date_default_timezone_set( "Australia/Sydney" );  

// http://www.php.net/manual/en/timezones.php

define( "DB_DSN", "mysql:host=localhost;dbname=cms" );

define( "DB_USERNAME", "username" );

define( "DB_PASSWORD", "password" );

define( "CLASS_PATH", "classes" );

define( "TEMPLATE_PATH", "templates" );

define( "HOMEPAGE_NUM_ARTICLES", 5 );

define( "ADMIN_USERNAME", "admin" );

define( "ADMIN_PASSWORD", "mypass" );

require( CLASS_PATH . "/Article.php" );

 

function handleException( $exception ) {

  echo "Sorry, a problem occurred. Please try later.";

  error_log( $exception->getMessage() );

}

 

set_exception_handler( 'handleException' );

?>

 

Breakdown of the code:
 

  • Show errors in the program

The ini_set() line causes mistake messages to be shown in the program. This is useful for troubleshooting. However, it should be set to false on the live site since it tends to be a security hazard. 

  • Set the timezone 

The CMS will utilize PHP's date() function, and we need to reveal the PHP server's timezone.

  • Set the database access subtleties

Now we characterize a steady DB_DSN that reveals to PHP where to discover the MySQL database. Ensure the dbname parameter coordinates with the name of your CMS database. We likewise store the MySQL username and secret key to get to the CMS database in the constants DB_USERNAME and DB_PASSWORD.

  • Set the ways 

Set 2-way names in the config document: CLASS_PATH, which is the way to the class files, and TEMPLATE_PATH, which is the place where the content should search for the HTML template files.

  • Set the administrator username and secret key 

ADMIN_USERNAME and ADMIN_PASSWORD constants contain the login subtleties for the CMS admin. Once more, you'll need to change these to your own qualities.  

  • Incorporate the Article class 

The Article class file is required by all contents in our application, and we need to incorporate it here.

  • Make an exception handler

We characterize handleException(), a basic function to deal with any PHP exemptions raised as the code runs. The function shows a nonexclusive error message and logs the actual exception message to the web server's error log.

Build the Article class

Now build the Article PHP class as it handles the bare essentials of storing articles in the database and recovering articles from the database. After building this class, it will be simple for our other CMS contents to create, update, recover and delete articles. 

In the cms folder, create a classes folder. In that classes folder, create a new file called Article.php:

 

Text 

<?php

 

/**

 * Class to handle articles

 */

 

class Article

{

 

  // Properties

 

  /**

  * @var int The article ID from the database

  */

  public $id = null;

 

  /**

  * @var int When the article was published

  */

  public $publicationDate = null;

 

  /**

  * @var string Full title of the article

  */

  public $title = null;

 

  /**

  * @var string A short summary of the article

  */

  public $summary = null;

 

  /**

  * @var string The HTML content of the article

  */

  public $content = null;

 

  /**

  * Sets the object's properties using the values in the supplied array

  *

  * @param assoc The property values

  */

 

  public function __construct( $data=array() ) {

    if ( isset( $data['id'] ) ) $this->id = (int) $data['id'];

    if ( isset( $data['publicationDate'] ) ) $this->publicationDate = (int) $data['publicationDate'];

    if ( isset( $data['title'] ) ) $this->title = preg_replace ( "/[^\.\,\-\_\'\"\@\?\!\:\$ a-zA-Z0-9()]/", "", $data['title'] );

    if ( isset( $data['summary'] ) ) $this->summary = preg_replace ( "/[^\.\,\-\_\'\"\@\?\!\:\$ a-zA-Z0-9()]/", "", $data['summary'] );

    if ( isset( $data['content'] ) ) $this->content = $data['content'];

  }

 

  /**

  * Sets the object's properties using the edit form post values in the supplied array

  *

  * @param assoc The form post values

  */

 

  public function storeFormValues ( $params ) {

 

    // Store all the parameters

    $this->__construct( $params );

 

    // Parse and store the publication date

    if ( isset($params['publicationDate']) ) {

      $publicationDate = explode ( '-', $params['publicationDate'] );

 

      if ( count($publicationDate) == 3 ) {

        list ( $y, $m, $d ) = $publicationDate;

        $this->publicationDate = mktime ( 0, 0, 0, $m, $d, $y );

      }

    }

  }

 

  /**

  * Returns an Article object matching the given article ID

  *

  * @param int The article ID

  * @return Article|false The article object, or false if the record was not found or there was a problem

  */

 

  public static function getById( $id ) {

    $conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );

    $sql = "SELECT *, UNIX_TIMESTAMP(publicationDate) AS publicationDate FROM articles WHERE id = :id";

    $st = $conn->prepare( $sql );

    $st->bindValue( ":id", $id, PDO::PARAM_INT );

    $st->execute();

    $row = $st->fetch();

    $conn = null;

    if ( $row ) return new Article( $row );

  }

 

  /**

  * Returns all (or a range of) Article objects in the DB

  *

  * @param int Optional The number of rows to return (default=all)

  * @return Array|false A two-element array : results => array, a list of Article objects; totalRows => Total number of articles

  */

 

  public static function getList( $numRows=1000000 ) {

    $conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );

    $sql = "SELECT SQL_CALC_FOUND_ROWS *, UNIX_TIMESTAMP(publicationDate) AS publicationDate FROM articles

            ORDER BY publicationDate DESC LIMIT :numRows";

 

    $st = $conn->prepare( $sql );

    $st->bindValue( ":numRows", $numRows, PDO::PARAM_INT );

    $st->execute();

    $list = array();

 

    while ( $row = $st->fetch() ) {

      $article = new Article( $row );

      $list[] = $article;

    }

 

    // Now get the total number of articles that matched the criteria

    $sql = "SELECT FOUND_ROWS() AS totalRows";

    $totalRows = $conn->query( $sql )->fetch();

    $conn = null;

    return ( array ( "results" => $list, "totalRows" => $totalRows[0] ) );

  }

 

  /**

  * Inserts the current Article object into the database, and sets its ID property.

  */

 

  public function insert() {

 

    // Does the Article object already have an ID?

    if ( !is_null( $this->id ) ) trigger_error ( "Article::insert(): Attempt to insert an Article object that already has its ID property set (to $this->id).", E_USER_ERROR );

 

    // Insert the Article

    $conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );

    $sql = "INSERT INTO articles ( publicationDate, title, summary, content ) VALUES ( FROM_UNIXTIME(:publicationDate), :title, :summary, :content )";

    $st = $conn->prepare ( $sql );

    $st->bindValue( ":publicationDate", $this->publicationDate, PDO::PARAM_INT );

    $st->bindValue( ":title", $this->title, PDO::PARAM_STR );

    $st->bindValue( ":summary", $this->summary, PDO::PARAM_STR );

    $st->bindValue( ":content", $this->content, PDO::PARAM_STR );

    $st->execute();

    $this->id = $conn->lastInsertId();

    $conn = null;

  }

 

  /**

  * Updates the current Article object in the database.

  */

 

  public function update() {

 

    // Does the Article object have an ID?

    if ( is_null( $this->id ) ) trigger_error ( "Article::update(): Attempt to update an Article object that does not have its ID property set.", E_USER_ERROR );

   

    // Update the Article

    $conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );

    $sql = "UPDATE articles SET publicationDate=FROM_UNIXTIME(:publicationDate), title=:title, summary=:summary, content=:content WHERE id = :id";

    $st = $conn->prepare ( $sql );

    $st->bindValue( ":publicationDate", $this->publicationDate, PDO::PARAM_INT );

    $st->bindValue( ":title", $this->title, PDO::PARAM_STR );

    $st->bindValue( ":summary", $this->summary, PDO::PARAM_STR );

    $st->bindValue( ":content", $this->content, PDO::PARAM_STR );

    $st->bindValue( ":id", $this->id, PDO::PARAM_INT );

    $st->execute();

    $conn = null;

  }

 

  /**

  * Deletes the current Article object from the database.

  */

 

  public function delete() {

 

    // Does the Article object have an ID?

    if ( is_null( $this->id ) ) trigger_error ( "Article::delete(): Attempt to delete an Article object that does not have its ID property set.", E_USER_ERROR );

 

    // Delete the Article

    $conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );

    $st = $conn->prepare ( "DELETE FROM articles WHERE id = :id LIMIT 1" );

    $st->bindValue( ":id", $this->id, PDO::PARAM_INT );

    $st->execute();

    $conn = null;

  }

 

}

 

?>

 

The front-end index.php script

Now make index.php, the script that controls the display of the front-end pages of the website. Save the file in the cms folder you made before:

 

Text File

<?php

 

require( "config.php" );

$action = isset( $_GET['action'] ) ? $_GET['action'] : "";

 

switch ( $action ) {

  case 'archive':

    archive();

    break;

  case 'viewArticle':

    viewArticle();

    break;

  default:

    homepage();

}

 

function archive() {

  $results = array();

  $data = Article::getList();

  $results['articles'] = $data['results'];

  $results['totalRows'] = $data['totalRows'];

  $results['pageTitle'] = "Article Archive | Widget News";

  require( TEMPLATE_PATH . "/archive.php" );

}

 

function viewArticle() {

  if ( !isset($_GET["articleId"]) || !$_GET["articleId"] ) {

    homepage();

    return;

  }

 

  $results = array();

  $results['article'] = Article::getById( (int)$_GET["articleId"] );

  $results['pageTitle'] = $results['article']->title . " | Widget News";

  require( TEMPLATE_PATH . "/viewArticle.php" );

}

 

function homepage() {

  $results = array();

  $data = Article::getList( HOMEPAGE_NUM_ARTICLES );

  $results['articles'] = $data['results'];

  $results['totalRows'] = $data['totalRows'];

  $results['pageTitle'] = "Widget News";

  require( TEMPLATE_PATH . "/homepage.php" );

}

 

?>

 

The back-end admin.php script

The admin script is a bit more intricate than index.php since it manages all the admin functions for the CMS. The fundamental structure, however, is similar to index.php.

Save the file, admin.php, in a similar folder as your index.php script:

 

Text

<?php

 

require( "config.php" );

session_start();

$action = isset( $_GET['action'] ) ? $_GET['action'] : "";

$username = isset( $_SESSION['username'] ) ? $_SESSION['username'] : "";

 

if ( $action != "login" && $action != "logout" && !$username ) {

  login();

  exit;

}

 

switch ( $action ) {

  case 'login':

    login();

    break;

  case 'logout':

    logout();

    break;

  case 'newArticle':

    newArticle();

    break;

  case 'editArticle':

    editArticle();

    break;

  case 'deleteArticle':

    deleteArticle();

    break;

  default:

    listArticles();

}

 

function login() {

 

  $results = array();

  $results['pageTitle'] = "Admin Login | Widget News";

 

  if ( isset( $_POST['login'] ) ) {

 

    // User has posted the login form: attempt to log the user in

 

    if ( $_POST['username'] == ADMIN_USERNAME && $_POST['password'] == ADMIN_PASSWORD ) {

 

      // Login successful: Create a session and redirect to the admin homepage

      $_SESSION['username'] = ADMIN_USERNAME;

      header( "Location: admin.php" );

 

    } else {

 

      // Login failed: display an error message to the user

      $results['errorMessage'] = "Incorrect username or password. Please try again.";

      require( TEMPLATE_PATH . "/admin/loginForm.php" );

    }

 

  } else {

 

    // User has not posted the login form yet: display the form

    require( TEMPLATE_PATH . "/admin/loginForm.php" );

  }

 

}

 

function logout() {

  unset( $_SESSION['username'] );

  header( "Location: admin.php" );

}

 

function newArticle() {

 

  $results = array();

  $results['pageTitle'] = "New Article";

  $results['formAction'] = "newArticle";

 

  if ( isset( $_POST['saveChanges'] ) ) {

 

    // User has posted the article edit form: save the new article

    $article = new Article;

    $article->storeFormValues( $_POST );

    $article->insert();

    header( "Location: admin.php?status=changesSaved" );

 

  } elseif ( isset( $_POST['cancel'] ) ) {

 

    // User has cancelled their edits: return to the article list

    header( "Location: admin.php" );

  } else {

 

    // User has not posted the article edit form yet: display the form

    $results['article'] = new Article;

    require( TEMPLATE_PATH . "/admin/editArticle.php" );

  }

 

}

 

function editArticle() {

 

  $results = array();

  $results['pageTitle'] = "Edit Article";

  $results['formAction'] = "editArticle";

 

  if ( isset( $_POST['saveChanges'] ) ) {

 

    // User has posted the article edit form: save the article changes

 

    if ( !$article = Article::getById( (int)$_POST['articleId'] ) ) {

      header( "Location: admin.php?error=articleNotFound" );

      return;

    }

 

    $article->storeFormValues( $_POST );

    $article->update();

    header( "Location: admin.php?status=changesSaved" );

 

  } elseif ( isset( $_POST['cancel'] ) ) {

 

    // User has cancelled their edits: return to the article list

    header( "Location: admin.php" );

  } else {

 

    // User has not posted the article edit form yet: display the form

    $results['article'] = Article::getById( (int)$_GET['articleId'] );

    require( TEMPLATE_PATH . "/admin/editArticle.php" );

  }

 

}

 

function deleteArticle() {

 

  if ( !$article = Article::getById( (int)$_GET['articleId'] ) ) {

    header( "Location: admin.php?error=articleNotFound" );

    return;

  }

 

  $article->delete();

  header( "Location: admin.php?status=articleDeleted" );

}

 

function listArticles() {

  $results = array();

  $data = Article::getList();

  $results['articles'] = $data['results'];

  $results['totalRows'] = $data['totalRows'];

  $results['pageTitle'] = "All Articles";

 

  if ( isset( $_GET['error'] ) ) {

    if ( $_GET['error'] == "articleNotFound" ) $results['errorMessage'] = "Error: Article not found.";

  }

 

  if ( isset( $_GET['status'] ) ) {

    if ( $_GET['status'] == "changesSaved" ) $results['statusMessage'] = "Your changes have been saved.";

    if ( $_GET['status'] == "articleDeleted" ) $results['statusMessage'] = "Article deleted.";

  }

 

  require( TEMPLATE_PATH . "/admin/listArticles.php" );

}

 

?>

 

Create the front-end templates

We've made all the PHP code for our CMS's functionality. The subsequent step is to make the HTML templates for both the front-end and admin pages.

  • The include files

Create a folder called template in your cms folder. Now create a folder called include in the templates folder. In this folder, we will put the header and footer markup that is common to each page of the site.

Create a new file called header.php in the include folder:

 

Text

<!DOCTYPE html>

<html lang="en">

  <head>

    <title><?php echo htmlspecialchars( $results['pageTitle'] )?></title>

    <link rel="stylesheet" type="text/css" href="style.css" />

  </head>

  <body>

    <div id="container">

 

      <a href="."><img id="logo" src="images/logo.jpg" alt="Widget News" /></a>

 

The code basically shows the markup to begin the HTML page. It utilizes the $results['pageTitle'] variable passed from the primary script (index.php or admin.php) to set the title component and furthermore links to a stylesheet, style.css

Now create a file called footer.php in the same folder:

 

Text

    <div id="footer">

        Widget News &copy; 2011. All rights reserved. <a href="admin.php">Site Admin</a>

      </div>

 

    </div>

  </body>

</html>

 

  • homepage.php

Now go to the templates folder and create a homepage.php template file there:

 

Text

<?php include "templates/include/header.php" ?>

 

      <ul id="headlines">

 

<?php foreach ( $results['articles'] as $article ) { ?>

 

        <li>

          <h2>

            <span class="pubDate"><?php echo date('j F', $article->publicationDate)?></span><a href=".?action=viewArticle&amp;articleId=<?php echo $article->id?>"><?php echo htmlspecialchars( $article->title )?></a>

          </h2>

          <p class="summary"><?php echo htmlspecialchars( $article->summary )?></p>

        </li>

 

<?php } ?>

 

      </ul>

 

      <p><a href="./?action=archive">Article Archive</a></p>

 

<?php include "templates/include/footer.php" ?>

The template shows the article features on the landing page as an unordered list. It loops through the various articles stored in $results['articles'] and displays each article's distribution date, title, and summary. The title is connected back to '.' (index.php), passing action=viewArticle, and the ID of the article, in the URL. This permits the visitor to peruse an article by clicking its title.

  • archive.php

Now create an archive.php template file in the templates folder:

 

Text

<?php include "templates/include/header.php" ?>

 

      <h1>Article Archive</h1>

 

      <ul id="headlines" class="archive">

 

<?php foreach ( $results['articles'] as $article ) { ?>

 

        <li>

          <h2>

            <span class="pubDate"><?php echo date('j F Y', $article->publicationDate)?></span><a href=".?action=viewArticle&amp;articleId=<?php echo $article->id?>"><?php echo htmlspecialchars( $article->title )?></a>

          </h2>

          <p class="summary"><?php echo htmlspecialchars( $article->summary )?></p>

        </li>

 

<?php } ?>

 

      </ul>

 

      <p><?php echo $results['totalRows']?> article<?php echo ( $results['totalRows'] != 1 ) ? 's' : '' ?> in total.</p>

 

      <p><a href="./">Return to Homepage</a></p>

 

<?php include "templates/include/footer.php" ?>

 

The template displays the archive of the articles in the CMS. It's practically indistinguishable from homepage.php. It adds the CSS class to the unordered list so we can style the list items a bit diversely to the landing page, and it likewise adds the year to the article distribution dates.

The page incorporates an all-out tally of the articles for the database, recovered by  $results['totalRows']. Instead of the archive’s link at the end of the page, it incorporates the "Return to Homepage" link.
 

  • viewArticle.php

This front-end template shows an article to the user. Now create a file called viewArticle.php in the templates folder.

 

Text

<?php include "templates/include/header.php" ?>

 

      <h1 style="width: 75%;"><?php echo htmlspecialchars( $results['article']->title )?></h1>

      <div style="width: 75%; font-style: italic;"><?php echo htmlspecialchars( $results['article']->summary )?></div>

      <div style="width: 75%;"><?php echo $results['article']->content?></div>

      <p class="pubDate">Published on <?php echo date('j F Y', $results['article']->publicationDate)?></p>

 

      <p><a href="./">Return to Homepage</a></p>

 

<?php include "templates/include/footer.php" ?>


Back-end templates

We've already made the templates for the front end of the site. Now we need to create the three admin templates. 

  • loginForm.php

Now create a folder named admin inside the templates folder. In the admin folder, make the first of the three templates, loginForm.php:

 

Text

<?php include "templates/include/header.php" ?>

 

      <form action="admin.php?action=login" method="post" style="width: 50%;">

        <input type="hidden" name="login" value="true" />

 

<?php if ( isset( $results['errorMessage'] ) ) { ?>

        <div class="errorMessage"><?php echo $results['errorMessage'] ?></div>

<?php } ?>

 

        <ul>

 

          <li>

            <label for="username">Username</label>

            <input type="text" name="username" id="username" placeholder="Your admin username" required autofocus maxlength="20" />

          </li>

 

          <li>

            <label for="password">Password</label>

            <input type="password" name="password" id="password" placeholder="Your admin password" required maxlength="20" />

          </li>

 

        </ul>

 

        <div class="buttons">

          <input type="submit" name="login" value="Login" />

        </div>

 

      </form>

 

<?php include "templates/include/footer.php" ?>

 

  • listArticles.php

Now make the second admin template in the admin folder and name it listArticles.php:

 

Text

<?php include "templates/include/header.php" ?>

 

      <div id="adminHeader">

        <h2>Widget News Admin</h2>

        <p>You are logged in as <b><?php echo htmlspecialchars( $_SESSION['username']) ?></b>. <a href="admin.php?action=logout"?>Log out</a></p>

      </div>

 

      <h1>All Articles</h1>

 

<?php if ( isset( $results['errorMessage'] ) ) { ?>

        <div class="errorMessage"><?php echo $results['errorMessage'] ?></div>

<?php } ?>

 

<?php if ( isset( $results['statusMessage'] ) ) { ?>

        <div class="statusMessage"><?php echo $results['statusMessage'] ?></div>

<?php } ?>

 

      <table>

        <tr>

          <th>Publication Date</th>

          <th>Article</th>

        </tr>

 

<?php foreach ( $results['articles'] as $article ) { ?>

 

        <tr onclick="location='admin.php?action=editArticle&amp;articleId=<?php echo $article->id?>'">

          <td><?php echo date('j M Y', $article->publicationDate)?></td>

          <td>

            <?php echo $article->title?>

          </td>

        </tr>

 

<?php } ?>

 

      </table>

 

      <p><?php echo $results['totalRows']?> article<?php echo ( $results['totalRows'] != 1 ) ? 's' : '' ?> in total.</p>

 

      <p><a href="admin.php?action=newArticle">Add a New Article</a></p>

 

<?php include "templates/include/footer.php" ?>

 

The template shows the list of articles for the admin to alter.After showing any error or status messages, it loops through various article objects stored in $results['articles'], showing each article's distribution date and title in a table row.

  • editArticles.php

Create the final template, editArticles.php, in the admin folder:

 

Text

<?php include "templates/include/header.php" ?>

 

      <div id="adminHeader">

        <h2>Widget News Admin</h2>

        <p>You are logged in as <b><?php echo htmlspecialchars( $_SESSION['username']) ?></b>. <a href="admin.php?action=logout"?>Log out</a></p>

      </div>

 

      <h1><?php echo $results['pageTitle']?></h1>

 

      <form action="admin.php?action=<?php echo $results['formAction']?>" method="post">

        <input type="hidden" name="articleId" value="<?php echo $results['article']->id ?>"/>

 

<?php if ( isset( $results['errorMessage'] ) ) { ?>

        <div class="errorMessage"><?php echo $results['errorMessage'] ?></div>

<?php } ?>

 

        <ul>

 

          <li>

            <label for="title">Article Title</label>

            <input type="text" name="title" id="title" placeholder="Name of the article" required autofocus maxlength="255" value="<?php echo htmlspecialchars( $results['article']->title )?>" />

          </li>

 

          <li>

            <label for="summary">Article Summary</label>

            <textarea name="summary" id="summary" placeholder="Brief description of the article" required maxlength="1000" style="height: 5em;"><?php echo htmlspecialchars( $results['article']->summary )?></textarea>

          </li>

 

          <li>

            <label for="content">Article Content</label>

            <textarea name="content" id="content" placeholder="The HTML content of the article" required maxlength="100000" style="height: 30em;"><?php echo htmlspecialchars( $results['article']->content )?></textarea>

          </li>

 

          <li>

            <label for="publicationDate">Publication Date</label>

            <input type="date" name="publicationDate" id="publicationDate" placeholder="YYYY-MM-DD" required maxlength="10" value="<?php echo $results['article']->publicationDate ? date( "Y-m-d", $results['article']->publicationDate ) : "" ?>" />

          </li>

 

        </ul>

 

        <div class="buttons">

          <input type="submit" name="saveChanges" value="Save Changes" />

          <input type="submit" formnovalidate name="cancel" value="Cancel" />

        </div>

 

      </form>

 

<?php if ( $results['article']->id ) { ?>

      <p><a href="admin.php?action=deleteArticle&amp;articleId=<?php echo $results['article']->id ?>" onclick="return confirm('Delete This Article?')">Delete This Article</a></p>

<?php } ?>

 

<?php include "templates/include/footer.php" ?>

 

The structure incorporates a region for error messages and the fields for the article title, content, summary, and distribution date. At last, there are two buttons for saving and dropping changes and a link to permit the administrator to delete the recently altered article.

Conclusion

A CMS is used for Enterprise Content Management (ECM) and Web Content Management (WCM). ECM generally upholds various users in a collaborative environment by coordinating document management, advanced resource management, and record maintenance.

PHP programming language is one of the solutions for creating sites and online applications. Since PHP cannot store information on its own and depends on a database for storing data safely. MySQL is the best option for PHP designers. As an open-source Relational Database Management System (RDBMS) that utilizes SQL language, MySQL database assists with mechanizing information recovery and offers help in PHP-MySQL web applications development. CMS is pretty standard but gives the starting point to build one's CMS driven websites using PHP and MySQL. To learn more about various programming languages checkout software developer training courses by NIIT.



PGP in Full Stack Product Engineering

Become an Industry-Ready StackRoute Certified Full Stack Product Engineer who can take up Product Development and Digital Transformation projects. Job Assured Program* with a minimum CTC of ₹7LPA*

Job Assured Program*

Easy Financing Options

Top