Building a Multi-Page Article System in ASP/PHP
By Mitchell Harper
If you're a web developer and have business-orientated clients, then I'm sure that you either have - or will have to - construct some sort of content management system to manage articles or content.
Some people would like to have you think that CMS's (content management systems) are hard to develop.
Don't be fooled. They are easy.
The one we are going to build today will let us store and display articles. Each article can have up to 20 pages, each of which will contain a title and some content. We will create one script to create new articles, and another to display them. A MySQL/SQL Server 2000 database will be used to store the articles.
Our database will contain just 2 tables: 1 for the articles and 1 for the pages. Each page will link back to its parent article with the use of a primary key in the articles table, and a foreign key in the pages table.
Jump to the MySQL command prompt and run the following code to create a new database and populate it with 2 tables, as described above:
create database myCMS;
use myCMS;
create table articles
(
articleId int auto_increment not null primary key,
title varchar(250),
summary text,
datePublished timestamp,
unique id(articleId)
);
create table pages
(
pageId int auto_increment not null primary key,
articleId int,
title varchar(250),
content text,
unique id(pageId)
); Use query analyzer to create a new database and populate it with 2 tables, as described above:
create database myCMS
go
use myCMS
go
create table articles
(
articleId int not null primary key identity(1,1),
title varchar(250),
summary text,
datePublished datetime default GETDATE()
)
create table pages
(
pageId int not null primary key identity(1,1),
articleId int,
title varchar(250),
content text
) Press F5 to execute the queries once you've copied them into the query analyzer window.
Our database is now in place. It's time to get creative with some JavaScript to build the multi-page article system. Here's how our page is going to look when we've finished:
As you can see, it's pretty simple. We will have an article title and summary, followed by a series of pages. Each of the buttons has an event linked to it in which JavaScript code is used to perform some operation on the current article page.
Our article system can allow us to:
- Add, edit and delete articles
- Shift the page order of each page in our article
- Remove all pages in one hit
- Delete pages on a page-by-page basis
- Update a page once it has already been created
Note: Our article system will add articles only. It is beyond the scope of this article for me to show you how to load articles back from the database or delete them.
The good thing about our article system is that there's very little server-side code. It's mostly client-side JavaScript, meaning that if you didn't use ASP or PHP, then you could easily take the code and convert it to Perl, ColdFusion, ASP.Net, etc.
Our basic layout is a couple of text boxes, a select box and a text box. The entire code for this article is available in the support material link on the last page. Let's now run through the steps of adding pages to an article. We will then look at the JavaScript code behind our article system.
Here's a diagram to illustrate the order in which the "add article" form should be completed:

As you can see, we start by entering an article title and summary. Next, we move onto adding pages to our article. We start with the page title (step 3) and then the page content (step 4). Once we have entered those, we click on the "Add Page" button (step 5). The "Add Page" button fires off some JavaScript which we will look at shortly. We then repeat steps 3 to 5 to add more pages.
Phew. OK. Now, let's get into the nitty-gritty and look at the JavaScript code behind it all. Don't worry, I will assume that you have limited JavaScript ability and I will try to explain everything as best as I can!
Each button is linked to a JavaScript function. Some of these functions are described below:
AddPage This function is activated when the "Add Page" button is clicked. It takes the title and content and adds them to a JavaScript array which is used to keep track of all the pages contained in the new article.
Its code looks like this:
function AddPage()
{
var pageTitle = new String();
var pageContent = new String();
var acount = arrTitles.length;
var thisForm = document.frmAdd;
if(acount < 20)
{
pageTitle = document.frmAdd.contentTitle.value;
pageContent = document.frmAdd.contentBody.value;
if(pageTitle.length == 0)
{ alert('You must enter a title for this page first.');
document.frmAdd.contentTitle.focus();
return;
}
if(pageContent.length == 0)
{ alert('You must enter some content for this page first.');
document.frmAdd.contentBody.focus();
return;
}
arrTitles[acount] = pageTitle;
arrContents[acount] = pageContent;
document.frmAdd.contentTitle.value = '';
document.frmAdd.contentBody.value = '';
ReloadPages();
document.frmAdd.contentTitle.focus();
}
else
{ alert('This article can have a maximum of twenty pages. Adding this page would exceed the limit.');
document.frmAdd.contentTitle.focus();
document.frmAdd.contentTitle.select();
}
} ClearPages This function is activated when the "Remove All Pages" button is clicked. It empties the arrays that contain the titles and content for each of the pages in this article.
It looks like this:
function ClearPages()
{
if(confirm('Warning: You are about to delete all of the pages from this article. Click OK to continue.'))
{
var thisForm = document.frmAdd;
arrTitles.length = 0;
arrContents.length = 0;
ReloadPages();
for(counter=0; counter<thisForm.articlePages.length; counter++)
{ thisForm.articlePages[counter].selected = false; }
thisForm.contentTitle.value = '';
thisForm.contentBody.value = '';
thisForm.cmdAdd.disabled = false;
thisForm.cmdUpdate.disabled = true;
thisForm.contentTitle.focus();
}
} MoveUp
This function is called when the "<" button is clicked. It moves the selected page up one spot in the list of pages. For example, if you selected page 2 in the list and clicked this button, then the MoveUp function would swap page 2 with page 1, this moving page 2 to the top of the list.
It looks like this:
function MoveUp()
{
var thisForm = document.frmAdd;
if(thisForm.articlePages.selectedIndex > 0)
{
thisIndex = thisForm.articlePages.selectedIndex-1;
tmp1 = arrTitles[thisForm.articlePages.selectedIndex-1];
tmp2 = arrTitles[thisForm.articlePages.selectedIndex];
tmp3 = arrContents[thisForm.articlePages.selectedIndex-1];
tmp4 = arrContents[thisForm.articlePages.selectedIndex];
arrTitles[thisForm.articlePages.selectedIndex] = tmp1;
arrTitles[thisForm.articlePages.selectedIndex-1] = tmp2;
arrContents[thisForm.articlePages.selectedIndex] = tmp3;
arrContents[thisForm.articlePages.selectedIndex-1] = tmp4;
ReloadPages();
thisForm.articlePages.selectedIndex = thisIndex;
}
}
DelPage
This function is called when the "x" button is clicked. It removes the selected page from the article. It does so by removing the title and content indexes in the JavaScript arrays for the selected page. It basically shifts any pages in front of the selected page one spot back in the array, overwriting the selected page with the one in front of it and reducing the size of the array by one.
It looks like this:
function DelPage()
{
var thisForm = document.frmAdd;
var thisIndex = thisForm.articlePages.selectedIndex;
if(thisIndex > -1)
{
if(confirm('Warning: You are about to delete this page from the article. Click OK to continue.'))
{
var a = 0;
var newTitles = new Array();
var newContents = new Array();
for(i = 0; i < arrTitles.length; i++)
{
if(i != thisIndex)
{
newTitles[a] = arrTitles[i];
newContents[a] = arrContents[i];
a = a + 1;
}
}
arrTitles = newTitles;
arrContents = newContents;
for(counter=0; counter<thisForm.articlePages.length; counter++)
{ thisForm.articlePages[counter].selected = false; }
ReloadPages();
document.all.contentTitle.value = '';
document.all.contentBody.value = '';
document.all.cmdAdd.disabled = false;
document.all.cmdUpdate.disabled = true;
thisForm.contentTitle.focus();
}
}
else
{
alert('Please select an article to delete.');
thisForm.contentPages.focus();
}
} AddPages This function is called when the "Add Article to Database" button is clicked. It loops through the title and content arrays which are used to hold the pages for the article and outputs each one into a hidden form variable which are then submitted with the form.
It looks like this:
function AddPages()
{
var thisForm = document.frmAdd;
var docLength = arrTitles.length;
var hasTitle = thisForm.articleTitle.value == '' ? false : true;
var hasSummary = thisForm.articleSummary.value == '' ? false : true;
if(hasTitle && hasSummary && docLength >= 1)
{
for(counter=0; counter < docLength; counter++)
{
x = counter + 1;
eval("thisForm.pageTitle"+x+".value = arrTitles["+counter+"];");
eval("thisForm.pageContent"+x+".value = arrContents["+counter+"];");
}
}
else
{
alert('Please make sure that you have entered an article title and summary and at least one page.');
thisForm.contentTitle.focus();
return false;
}
return true;
} That's the bulk of the JavaScript. Don't worry if you don't understand it totally.
Let's now get onto the ASP/PHP code to put our article into a database. I will also show you how to retrieve, list and display each article.
When the form is submitted, we have a number of variables available to us.
They are as follows:
articleTitle
articleSummary
pageTitle1 to pageTitle20
pageContent1 to pageContent20
If you match these up with the schema of our database, then you will see that we have all of the data we need to create entries in our database for each article. We will have 1 entry in the articles table and 1 or more entries in the pages table for each article. Each page is linked back to the article via the articleId field.
Let's now look at the code to save an article to the database.
ASP Code sub SaveArticle()
%><!-- #INCLUDE file="db.asp" --><%
dim articleId
dim articleTitle
dim articleSummary
dim arrPages
dim objDict
dim page
dim counter
dim i
set arrPages = Server.CreateObject("Scripting.Dictionary")
counter = 0
articleTitle = Request.Form("articleTitle")
articleSummary = Request.Form("articleSummary")
for i = 1 to 20
if Request.Form("pageTitle" & i) <> "" then
arrPages.Add Request.Form("pageTitle" & i), Request.Form("pageContent" & i)
end if
next
'Add an entry to the article table
objConn.Execute("insert into articles(title, summary) values('" & articleTitle & "', '" & articleSummary & "')")
if objConn.Errors.Count > 0 then
Response.Write "Couldn't add article"
Response.End
end if
objRS.Open("select top 1 articleId from articles order by articleId desc")
articleId = objRS.Fields(0).value
'Add one or more entries to the pages table
for each page in arrPages
objConn.Execute("insert into pages(articleId, title, content) values(" & articleId & ", '" & page & "', '" & arrPages(page) & "')")
if objConn.Errors.Count > 0 then
Response.Write "Couldn't add page"
Response.End
end if
next
%>
<font face="Verdana" size="4"><b>Article Added Successfully!</b></font><br><br>
<font face="Verdana" size="2">
<b>Details</b>
<ul>
<li>Article title: <i>"<% Response.Write articleTitle %>"</i></li>
<li>Article ID: <% Response.Write articleId %></li>
<li>Number of pages: <% Response.Write arrPages.count %></li>
</ul>
</font>
<%
end sub
PHP Code function SaveArticle()
{
include("db.php");
$articleTitle = $_POST["articleTitle"];
$articleSummary = $_POST["articleSummary"];
$arrPages = array();
$counter = 0;
// Loop to get the pages
for($i = 1; $i < 20; $i++)
{
if($_POST["pageTitle$i"] != "")
{
$arrPages[] = array("title" => $_POST["pageTitle$i"], "content" => $_POST["pageContent$i"]);
}
}
// Add an entry to the article table
@mysql_query("insert into articles(title, summary) values('$articleTitle', '$articleSummary')") or die("Couldn't add article: " . mysql_error());
// Grab the ID of the new article record
$articleId = mysql_insert_id();
// Add one or more entries to the pages table
for($i = 0; $i < sizeof($arrPages); $i++)
{
@mysql_query("insert into pages(articleId, title, content) values($articleId, '" . $arrPages[$i]["title"] . "', '" . $arrPages[$i]["content"] . "')") or die("Couldn't add page: " . mysql_error());
}
?>
<font face="Verdana" size="4"><b>Article Added Successfully!</b></font><br><br>
<font face="Verdana" size="2">
<b>Details</b>
<ul>
<li>Article title: <i>"<?php echo $articleTitle ?>"</i></li>
<li>Article ID: <?php echo $articleId; ?></li>
<li>Number of pages: <?php echo sizeof($arrPages); ?></li>
</ul>
</font>
<?php
} Now that we can create and save our articles, we need to display them. Let's now look at how to display a list of articles as well as each article on its own.
It's very easy to display a list of articles from the articles table in our database. We simply loop through the articles table and output the title and summary for each article. We also setup a link to read the entire article, which we will look at shortly. Shown below is the code for both ASP and PHP:
ASP Code <!-- #INCLUDE file="db.asp" -->
<%
objRS.Open "select * from articles order by articleId asc"
while not objRS.EOF
%>
<font face="Verdana" size="4"><b><%=objRS("title")%></b></font><br><br>
<font face="Verdana" size="2">
<%=objRS("summary")%><br><br>
<a href="fullarticle.asp?articleId=<%=objRS("articleId")%>">Read More...</a>
</font>
<hr><br>
<%
objRS.MoveNext
wend
%>
PHP Code include("db.php");
$result = mysql_query("select * from articles order by articleId asc");
while($row = mysql_fetch_array($result))
{
?>
<font face="Verdana" size="4"><b><?php echo $row["title"]; ?></b></font><br><br>
<font face="Verdana" size="2">
<?php echo $row["summary"]; ?><br><br>
<a href="fullarticle.asp?articleId=<?php echo $row["articleId"]; ?>">Read More...</a>
</font>
<hr><br>
<?php
} Here's the output from the code above:
To display an individual article, we simply list the pages in that article as links and start by displaying the title and content of the first page:
ASP Code <!-- #INCLUDE file="db.asp" -->
<%
articleId = Request.QueryString("articleId")
pageId = Request.QueryString("pageId")
if not isNumeric(articleId) then
Response.Write "Invalid article Id"
Response.End
end if
if pageId = "" then
objRS.Open("select top 1 pageId from pages where articleId=" & articleId)
pageId = objRS("pageId")
end if
if objRS.State = 1 then objRS.Close
objRS.Open("select * from articles inner join pages on articles.articleId = pages.articleId where articles.articleId = " & articleId & " and pages.pageId = " & pageId)
if objRS.EOF then
Response.Write "Article not found"
Response.End
end if
%>
<html>
<head>
<title>Multi-Page Article System</title>
</head>
<body bgcolor="#ffffff">
<font face="Verdana" size="5"><b><%=objRS.Fields(1)%></b></font><br><br>
<font face="Verdana" size="3"><b><i><%=objRS.Fields(6)%></i></b></font><br>
<font face="Verdana" size="2"><%=objRS.Fields(7)%></font><br><br>
<font face="Verdana" size="1">
Article Pages:
<%
'Display the pages in this article
if objRS.State = 1 then objRS.Close
objRS.Open("select * from pages where articleId = " & articleId)
while not objRS.EOF
if CStr(objRS("pageId")) = CStr(pageId) then
Response.Write "<li><b>" & objRS("title") & "</b></li>"
else
Response.Write "<li><a href='fullarticle.asp?articleId=" & articleId & "&pageId=" & objRS("pageId") & "'>" & objRS("title") & "</a></li>"
end if
objRS.MoveNext
wend
%>
</font>
</body>
</html> PHP Code <?php
include("db.php");
$articleId = @$_GET["articleId"];
$pageId = @$_GET["pageId"];
if(!is_numeric($articleId))
{
die("Invalid article Id");
}
if($pageId == "")
{
$result = mysql_query("select pageId from pages where articleId=" . $articleId . " limit 1");
$row = mysql_fetch_array($result);
$pageId = $row["pageId"];
}
$result = mysql_query("select * from articles inner join pages on articles.articleId = pages.articleId where articles.articleId = " . $articleId . " and pages.pageId = " . $pageId);
if(mysql_num_rows($result) == 0)
{
die("Article not found");
}
$row = mysql_fetch_array($result);
?>
<html>
<head>
<title>Multi-Page Article System</title>
</head>
<body bgcolor="#ffffff">
<font face="Verdana" size="5"><b><?php echo $row[1];?></b></font><br><br>
<font face="Verdana" size="3"><b><i><?php echo $row[6];?></i></b></font><br>
<font face="Verdana" size="2"><?php echo $row[7];?></font><br><br>
<font face="Verdana" size="1">
Article Pages:
<?php
//Display the pages in this article
$result = mysql_query("select * from pages where articleId = " . $articleId);
while($row = mysql_fetch_array($result))
{
if($pageId == $row["pageId"])
echo "<li><b>" . $row["title"] . "</b></li>";
else
echo "<li><a href='fullarticle.php?articleId=" . $articleId . "&pageId=" . $row["pageId"] . "'>" . $row["title"] . "</a></li>";
}
?>
</font>
</body>
</html> And the result? Well, take a look:

In this article we've seen how to develop a multi-page article publishing system. We've also seen how to list and display each article.
The code in this document is pretty rough, however it can be used in a CMS system with a bit of a clean up.
1 Response to "Building a Multi-Page Article System in ASP/PHP"
Fill in the form below to leave a comment and share your thoughts.