Interested in building your own CMS? In this article Mitchell shows us how to build a multi-page article system that can be used in any web-based CMS...
Building a Multi-Page Article System With ASP/PHP - Saving Articles to the Database (Page 4 of 6 )
When the form is submitted, we have a number of variables available to us. They are:
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
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
// 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()); }
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.