<

Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x

How to build a CMS: Displaying the content

Published on
5,580 Points
2,480 Views
1 Endorsement
Last Modified:
This article shows how a content item can be identified directly or through translation of a navigation type. It then shows how this information can be used to create a menu for further navigation.
This article is part of a series of articles that intends to demonstrate ‘How to build a content management system’. If you are reading this in isolation, you may wish to consider reading the first article, which gives a brief overview of each step in the process and gives this article further context.

In this article I intend to show how a content item can be identified directly (using type and id) or through the translation of a navigation type, then how this information can be used to create a menu for further navigation.
 
To begin with, we will look at the index.php file that was introduced in the previous article in a little more detail, then expand upon this to show how our content is selected and shown.

Enable error reporting
This simply enables PHP error reporting, which you will find very useful later down the line, when you come to make changes to the code and struggle to find out where the problems lie…
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

Open in new window


Open Connection to database
Open and test the connection to your MySQL database using the details you created earlier.
/* Open a connection */
$mysqli = new mysqli("localhost", "DATABASE_NAME", "DATABASE_PASSWORD", "DATABASE_USER");
/* check connection */
if (mysqli_connect_errno()) { printf("Connect failed: %s\n", mysqli_connect_error()); exit(); }

Open in new window


Process Input
This line of code processes all POST and GET requests that have been sent to the page, then creates a new php variable by the same name for you to use throughout your code. 

In the first instance, you will only be using the ‘id’ variable that we will place in the query string later on in the example. However, as you further develop your system, that same line of code will process all FORM data that has been sent to the page (for example when creating new pages).
 
/* process input */
foreach($_REQUEST as $key => $value){ $$key = $value;}

Open in new window


Find the home page
This is important because if a user goes to the root of the site, or incorrectly enters information into the address bar, we need to be able to send them to the home page by default. For simplicity, in this example we simply tell the code to use ’id#1’, however later examples will find the correct id, based on the ordering of the main menu.
 
/* find homepage */
$homepageid=1;

Open in new window


Display content item to user
 
In order to display a content item to the user, we need to know the type and id of the item. This information can be passed to us directly, or through the use of a navigation type.

Both methods are equally important. As you can imagine, it is important to be able to access every single content item via one method or another. However, we wouldn’t necessarily want every single item added to the navigation. Using a navigation level enables us to map a route to selected items for our end users, whilst hiding non-essential information.
 
To the end user, the system is therefore navigated using the ‘id’ variable which will be passed from page to page as a parameter in the URL. This ‘id’ will then map directly to a row in the ‘nav’ table.  Each ‘nav’ instance has two defined fields type and typeid which are extracted everytime we process the navigation.
 
Our system identifies when we are using the navigation level, if only the [id] parameter is detected as input. In which case it retrieves the type and typeid from the nav table for later use.
 
/* process nav to determine type & typeid */
if(isset($id)){
$sql = "SELECT type, typeid FROM nav WHERE id = $id";
	if ($result = $mysqli->query($sql)) {
		$row = $result->fetch_assoc();
		foreach($row as $key => $value) {
			$$key = html_entity_decode($value, ENT_QUOTES);
		}
		$result->free();
	}
}

Open in new window


If instead our system detects both the [type] and [typeid] parameters have been passed as input, then it knows to skip the above step and use the inputted variables instead.

Process output
This next section retrieves information from the database to display to the user at a later stage.
Using the two variables we found in the previous section, the code below retrieves the row from the ‘page’ table (stored in variable $type), where the id is equal to the variable $typeid. Each field from the retrieved row is then stored as a variable by the same name, for future use.

For example, if you are on the home page, the variables would store:  $page_id=’1’, $page_title=’welcome to our website’, $page_content=’Content for the welcome page’.
 
/* process output */
$sql = "SELECT * FROM $type WHERE `id` = '$typeid'";
if ($result = $mysqli->query($sql)) {
	$row = $result->fetch_assoc();
	foreach($row as $key => $value) {
		$newvarible =$type."_".$key;
		$$newvarible = html_entity_decode($value, ENT_QUOTES);
	}
	$result->free();
}

Open in new window


Output to the user
In this example, we will only output the raw data without any consideration to layout / style etc.

In order to do this, we simply provide a basic HTML template and use the PHP echo command to output the two variables $page_title and $page_content.

Note: the ‘content’ field for each page will include HTML formatting, therefore we don’t need to worry about adding this to the page template. Future articles will show you how to incorporate a WSYWIG editor into the system, which will send formatted data to the database.
 
echo "<h3>$page_title</h3>
      $page_content";

Open in new window


Process navigation
This last bit of code retrieves all ‘nav’ items that have been related to the ‘menu’ (id#1) in the relations table. We then use an INNER JOIN to combine the data from the ‘nav’ table for future use. We then cycle through each record using a WHILE statement and create a list of links.

The ‘title’ attribute is used for the anchor text, and the ‘id’ attribute is used appended to the HREF string as follows: index.php?id=XX. Upon a new page being loaded, this ‘id’ is then processed and instructs the rest of the system what information to display.
 
/* process navigation */
$sql = "SELECT nav.id, nav.title FROM relations INNER JOIN nav ON relations.childtypeid=nav.id WHERE parenttype = 'menu' AND parenttypeid = '1'";
if ($result = $mysqli->query($sql)) {
	echo "<ul>";
	while ($row = $result->fetch_assoc()) {
		echo "<li><a href='index.php?id={$row['id']}'>{$row['title']}</a></li>";
	}
	echo "</ul>";
}

Open in new window


Close database connection
This final statement closes the MySQLi connection.
 
<?php $mysqli->close(); ?>

Open in new window


The code below shows how we incorporate these additional features into the working example from the previous article:
<html>
	<body>
		<h1><u>CMS Example #2</u></h1>
<?php
/* Enable error reporting */
error_reporting(E_ALL);
ini_set('display_errors', 1);

/* Open a connection */
$mysqli = new mysqli("localhost", "DATABASE_NAME", "DATABASE_PASSWORD", "DATABASE_USER");
/* check connection */
if (mysqli_connect_errno()) { printf("Connect failed: %s\n", mysqli_connect_error()); exit(); }

/* process input - create a variable for each input and assign the value*/
foreach($_REQUEST as $key => $value){ $$key = $value;}

/* process actions */
if(isset($action)){

	echo "<p>PROCESSING ACTION...</p>";

	if($action=="login"){

		echo "<p>PROCESSING LOGIN...</p>";
		
		unset($action);

		echo "<p>LOGIN SUCCESS... REDIRECTING TO DASHBOARD</p>";

		$display="dashboard";

	}
}

/* find homepage */
$homepageid=1;

if(isset($display)){
	if($display=="login") {

		echo 	"<p>LOGIN VIEW<p>
			 <p>To login, please <a href='index.php?action=login'>click here</a>.";

	}elseif($display=="dashboard") {

		echo 	"<p>DASHBOARD VIEW</p>
			 <ul>
				<li>To view all pages <a href='index.php?display=view&type=page'>click here</a>.</li>
				<li>To add a new page <a href='index.php?display=add&type=page'>click here</a>.</li>
			</ul>";

	}elseif($display=="add") {

		echo "<p>ADD VIEW</p>";

	}elseif($display=="view") {

		echo "<p>DISPLAY ALL VIEW</p>";

	}
}elseif(isset($id)||(isset($type)&&isset($typeid))){

	/* process nav to determine type & typeid */

	if(isset($id)){
		$sql = "SELECT type, typeid FROM nav WHERE id = $id";
		if ($result = $mysqli->query($sql)) {
			$row = $result->fetch_assoc();
			foreach($row as $key => $value) {
				$$key = html_entity_decode($value, ENT_QUOTES);
			}
			$result->free();
		}
	}

	/* process output */

	$sql = "SELECT * FROM $type WHERE `id` = '$typeid'";
	if ($result = $mysqli->query($sql)) {
		$row = $result->fetch_assoc();
		foreach($row as $key => $value) {
			$newvarible =$type."_".$key;
			$$newvarible = html_entity_decode($value, ENT_QUOTES);
		}
		$result->free();
	}

	echo 	"<h3>$page_title</h3>
		$page_content";
	
}else{

	/* display home page */
	echo "<p>HOME PAGE</p>";

}
?>
		<h2>Menu</h2>
		<?php
		/* process navigation */
		$sql = "SELECT nav.id, nav.title FROM relations INNER JOIN nav ON relations.childtypeid=nav.id WHERE parenttype = 'menu' AND parenttypeid = '1'";
		if ($result = $mysqli->query($sql)) {
			echo "<ul>";
			while ($row = $result->fetch_assoc()) {
				echo "<li><a href='index.php?id={$row['id']}'>{$row['title']}</a></li>";
			}
			echo "</ul>";
            $result->free();
		}
$mysqli->close();
		?>
	</body>
</html>

Open in new window


You can find a working example of code above at the following url:
http://www.suremedia.co.uk/cms-example-2/index.php

You can also download the SQL for the example using the link below:
example1.sql

In summary, we have shown the two different methods for identifying which content item to display and the process of outputting the information. We have also looked at how a 'navigation' layer can be added to control exactly which content items are navigable to the user.

In the next article Building a CMS: User authentication and security we look at the login process in a lot more detail and also introduce a number of small measures to protect our system against malicious use.
 
1
Comment
Author:Dean OBrien
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
0 Comments

Featured Post

Get your Disaster Recovery as a Service basics

Disaster Recovery as a Service is one go-to solution that revolutionizes DR planning. Implementing DRaaS could be an efficient process, easily accessible to non-DR experts. Learn about monitoring, testing, executing failovers and failbacks to ensure a "healthy" DR environment.

Join & Write a Comment

The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …
Video by: Mark
This lesson goes over how to construct ordered and unordered lists and how to create hyperlinks.

Keep in touch with Experts Exchange

Tech news and trends delivered to your inbox every month