Making a flash content management system with PHP and XML

Making a flash content management system with PHP and XML


This is a tutorial on how to create a content management system using flash actionscript 3.0, PHP and XML

This tutorial may be a long one, the other tutorial on here about handling XML with flash is a bit out dated so I will go over that bit again in AS3.

There are 4 files in this tutorial and a MySQL database to hold content. I will teach you how to make a simple news content management system using flash, php and xml.


Creating the database
You will need a database to hold your information. The information you will need to store is as follows:
newsID
newsTitle
newsContent
newsDate

Here is the SQL code to create this table:

CREATE TABLE IF NOT EXISTS `news` (
`newsID` int(11) NOT NULL auto_increment,
`newsTitle` varchar(100) NOT NULL,
`newsContent` text NOT NULL,
`newsDate` datetime NOT NULL,
PRIMARY KEY (`newsID`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=10 ;



Writing to the database
Ok, first of all we need to write to the database in order to view it within flash. To do this we will need 2 files, a submit.html page and a submit.php file.

submit.html

<html>
<head>
<title>My First Content Management System</title>
</head>
<body>
<form id="add_news" action="submit.php" method="post" >
<label for="Title">Title: </label>
<input type="text" name="newsTitle" value="" />
<label for="Content">Content: </label>
<input type="text" name="newsContent" value="" />
<input type="submit" />
</form>
</body>


I'm not really going to go through this, there are many HTML form tutorials on the internet. All this basically does is put a form on the page with 2 boxes, a title box and a content box.

submit.php
As with my other tutorials I will show you the code to implement the page then I will go through it section by section.

<?php
$newsTitle = $_POST["newsTitle"];
$newsContent = $_POST["newsContent"];
$newsDate = date("Y-m-d H:i:s");

$insertNewsSQL = "INSERT INTO news (newsTitle, newsContent, newsDate) VALUES ('$newsTitle', '$newsContent', '$newsDate')";
mysql_query($insertNewsSQL) or die('Sorry, but there has been an error');
echo 'News inserted.';
?>

Note that this is the very basics of inputting information to a MySQL database, you should protect your everything from possible SQL injection before putting it into the database.

Now to go through the code:

<?php
$newsTitle = $_POST["newsTitle"];
$newsContent = $_POST["newsContent"];
$newsDate = date("Y-m-d H:i:s");


If you have no idea what is going on here please go look at A beginners guide to PHP. Basically we assign the $_POST variables which have been sent from the previous form to their own variables. In the third line we also assign todays date in a MySQL DateTime format to the new variable $newsDate.


$insertNewsSQL = "INSERT INTO news (newsTitle, newsContent, newsDate) VALUES ('$newsTitle', '$newsContent', '$newsDate')";
mysql_query($insertNewsSQL) or die('Sorry, but there has been an error');
echo 'News inserted.';
?>

In the first line, we create a new SQL query, this will insert information from the variables above into the database as follows:
$newsTitle goes into the newsTitle column
$newsContent goes into the newsContent column
$newsDate goes into the newsDate column

The second line actually performs the MySQL function, if there is an error it will print the string 'Sorry, but there has been an error'. The third line just outputs a confirmation message.


Retrieving the information from the database and parsing into XML
To do this we will just use one .php file and use a header to serve the content as if it was XML. The reason we need the information in a XML fomat is so that it is a nice simple neutral language that many programs can understand. For us the program will be flash :)

<?php
//database connections
$hostname = "########";
$user = "#########";
$pass = "###########";
$database = "##########";

$connection = mysql_connect($hostname, $user, $pass) or die(mysql_error());
mysql_select_db($database, $connection) or die(mysql_error());

header("Content-Type: application/xml; charset=ISO-8859-1");

echo '<?xml version="1.0" encoding="UTF-8"?>';
echo '<news>';
$newsSQL = mysql_query("SELECT * FROM news ORDER BY newsID DESC");
while($news = mysql_fetch_array($newsSQL)){
echo '<article>';
echo '<newsTitle>' . $news["newsTitle"] . '</newsTitle>';
echo '<newsContent>' . $news["newsContent"] . '</newsContent>';
echo '<newsDate>' . $news["newsDate"] . '</newsDate>';
echo '</article>';
}
echo '</news>';
?>


This code will basically connect to the database, and then display the news articles in an xml format.

Ok so now I will break the code down.

<?php
//database connections
$hostname = "########";
$user = "#########";
$pass = "###########";
$database = "##########";

$connection = mysql_connect($hostname, $user, $pass) or die(mysql_error());
mysql_select_db($database, $connection) or die(mysql_error());

This first section, you should replace all the '########' with your database information :). All this first section will do is connect to the database, ready for the information to be displayed.


header("Content-Type: application/xml; charset=ISO-8859-1");

This line tells the browser that the content that follows will be xml, and will be parsed as xml rather than php.


echo '<?xml version="1.0" encoding="UTF-8"?>';
echo '<news>';

In this section we start displaying some xml, the first line sets up a typical xml document and the second line displays the opening tag for all of our articles.


$newsSQL = mysql_query("SELECT * FROM news ORDER BY newsID DESC"); //query database
while($news = mysql_fetch_array($newsSQL)){ //fetch results
echo '<article>'; //start article tag
echo '<newsTitle>' . $news["newsTitle"] . '</newsTitle>'; //display news title
echo '<newsContent>' . $news["newsContent"] . '</newsContent>'; //display content
echo '<newsDate>' . $news["newsDate"] . '</newsDate>'; //display date
echo '</article>'; //end article tag
}

I commented each line here to give a rough idea of what is going on. This section of the code queries the database for all news items and orders them descending (newest first). It then loops through each result and prints an opening and closing <article></article> tag around each of the items. Each item is wrapped in its own tag. The above XML will be displayed as follows:

<news>
<article>
<newsTitle>This is a news title!</newsTitle>
<newsContent>This is the content of our news item</newsContent>
<newsDate>2009-06-25 21:41:00</newsDate>
</article>
</news>



The Flash part
Ok, begin by creating a new document. On this document select the text tool and drag it across the stage. Click Ctrl + F3 to open up the properties menu, make sure the text box is selected. You need to make the textbox multiline and give it an instance name of 'newsOutput' as follows:
http://www.tutorialhelpcentre.com/images/tutorialimages/fcms_1.jpg

Now you are all set up to grab the xml. click the first frame in the timeline and press F9 to open up the actions menu. Now you will need to enter the following code:

var xmlLoader:URLLoader = new URLLoader();
var xmlData:XML = new XML();

xmlLoader.addEventListener(Event.COMPLETE, LoadXML);
xmlLoader.load(new URLRequest("http://www.tutorialhelpcentre.com/tutsource/news.php"));

function LoadXML(e:Event):void {
xmlData = new XML(e.target.data);
ParseNews(xmlData);
}

function ParseNews(newsInput:XML):void {
var newsArticles:XMLList = newsInput.article;
newsOutput.text = "";
for each(var newsInfo:XML in newsArticles){ //loop through each article
newsOutput.appendText(newsInfo.newsTitle.text() + '\n');
newsOutput.appendText(newsInfo.newsContent.text() + '\n');
newsOutput.appendText(newsInfo.newsDate.text() + '\n\n');
}
}


This is quite a large chunk of code so I will break it down into 3 segments.

var xmlLoader:URLLoader = new URLLoader();
var xmlData:XML = new XML();

xmlLoader.addEventListener(Event.COMPLETE, LoadXML);
xmlLoader.load(new URLRequest("http://www.tutorialhelpcentre.com/tutsource/news.php"));

This first line assigns a new URLLoader for loading the xml document into flash. the second line tells flash that the variable xmlData will contain an XML document.
We then set up a listener to let us let us know when the xml document has loaded, go to the function 'loadXML'. Finally we request the XML document from the URL.


function LoadXML(e:Event):void {
xmlData = new XML(e.target.data);
ParseNews(xmlData);
}

This is the function which loads the data fromt he xml file into the xmlData variable. Once we have the xml document in the variable we send it into the ParseNews function.


function ParseNews(newsInput:XML):void {
var newsArticles:XMLList = newsInput.article;
newsOutput.text = "";

This is the function which will parse the news into the textbox. the first line takes the variable sent to it and gives it the variable name 'newsInput' so that it can be referenced. We then create a new variable called 'newsArticles' this is assigned everything between each of the <article></article> tags, which will be each of our news articles. The last line resets the textbox.


for each(var newsInfo:XML in newsArticles){ //loop through each article
newsOutput.appendText(newsInfo.newsTitle.text() + '\n');
newsOutput.appendText(newsInfo.newsContent.text() + '\n');
newsOutput.appendText(newsInfo.newsDate.text() + '\n\n');
}
}

This is the final section of code, we loop through each of the <article></article> tags and get the information from inside.

newsOutput.appendText(newsInfo.newsTitle.text() + '\n');

This code is repeated 3 times, in the code above we grab the text from between the 'newsTitle' tags and append it to the textbox. The other lines just do the same thing but with the newsContent and newDate.

Done! There is your first flash content management system! If there are any problems, feel free to leave a comment below.



Submit Comment

Comments

  1. yash on October 13, 2010
    please provide example project file.
    tested project plz.......

  2. Rajesh kanna on February 19, 2010
    Will do when i get back, unfortunately havent got anything on me except my pc :( if you click on the contact tab and shoot me an email ill try to help you out personally :)

  3. Steve on October 25, 2009
    First Add

  4. Matt on October 08, 2009
    Have you got your source anywhere and have you copied this tutorial word-for-word? If you're still having problems use the contact button above and send me a quick mail

  5. Santosh on October 08, 2009
    Nice,but I have faced a problem,i.e First time when inserted 5 records that time shows this 5 record but when inserted next 2 two records and output file shows the first 5 records not all 7 records.Can any one tell me why it happening?

  6. Matt on July 28, 2009
    Will do when i get back, unfortunately havent got anything on me except my iphone :( if you click on the contact tab and shoot me an email ill try to help you out personally :)

  7. KJ on July 28, 2009
    Hi Matt,
    I downloaded the MAMP server and tried to set everything up but without no luck.
    Would it be possible to ask you for a more detailed description on where your scripts are to be uploaded and how the server is set up for local testing?

    Cheers, your help is greatly appreciated.

  8. Matt on July 27, 2009
    As for testing the CMS locally, you would need a local server for the PHP file, there are plenty of good free ones out there like MAMP :) The flash will run without a local server and can call from a website :)

  9. Matt on July 27, 2009
    Thanks for the comments guys, I don't actually have the source files as I wrote it as I went a long and did a bit of testing here and there. On holiday at the moment but I will upload some when I get back :)

  10. KJ on July 27, 2009
    Excellent tut mate, I've been looking for something like this the whole day!!!
    Is there a way to test the CMS locally? And I agree with John, it would be greatly appreciated if you could upload the source files.

    Good work Matt and keep up the good work, it is greatly appreciated

  11. John on July 18, 2009
    Very nice tut, but as always, source files are always nice for longer tuts like this. ^_^

  12. Matt on July 11, 2009
    Thanks for the link-back :)

  13. ScriptPlazza.com on July 11, 2009
    http://www.scriptplazza.com/2009/07/flash-content-management-system-with.html

    nice tutorial good work