Flow List, Ajax, PHP and MySQL
Updated: Dec 18, 2007
Views: 5451
Description: This tutorial will show you how to load page content from Flow List using Ajax technology and a dynamic XML file generated from a MySQL database using PHP. Asynchronous JavaScript and XML (Ajax) uses the javascript XMLHttpRequest object to send http requests between the user's browser and serverside scripts without reloading the current browser window. In this tutorial we will build a very simple music album display. The same techniques can be used in many different ways with Flow List, from photo albums to catalog displays.
This tutorial will show you how to load page content from Flow List using Ajax technology and a dynamic XML file generated from a MySQL database using PHP.
Asynchronous JavaScript and XML (Ajax) uses the javascript XMLHttpRequest object to send HTTP requests between the user's browser and serverside scripts without reloading the current browser window. In this tutorial we will build a very simple music album display. The same techniques can be used in many different ways with Flow List, from photo albums to catalog displays.
Note: The scripts I will be presenting here are for tutorial purposes only and should not be used in a live environment without more comprehensive security and error checking etc. - these are just the basics to help you get started.
You can see a working example of these techniques used in an installation of osCommerce here
My recommendation is to use these scripts on a local test environment and to build onto them whatever you need to use in a live environment. My personal preferences for development are Easyphp and Wamp, both of which allow simple installation of Apache Web Server, PHP and MySQL and phpMyAdmin on a PC and are free software. I use these extensively for developing web applications as they allow me to browser test entire PHP/MySQL driven websites on my local PC. I highly recommend using one of these to work through this tutorial.
*Note: When installing either of these development environments on Windows, do not allow the installer to install in the default "program files" directory. Instead, install them in either c:/easyphp/ or c:/wamp/ - this measure will save you endless headaches.
A working knowledge of PHP and MySQL and Javascript and Flash and phpMyAdmin is assumed, however the tutorial and scripts are extensively commented to help the learning process.
To complete this tutorial, you will also need the Flow List Component
Part I - The Database
Let's begin by creating an empty database using phpMyAdmin. Make sure that either EasyPHP or WAMP is started on your computer. You can open phpMyadmin in EasyPHP by right clicking the system tray icon and selecting "Administration" and then "Manage Database". If you are using WAMP, simply left click the tray icon and select "phpMyAdmin".
The default window of phpMyAdmin presents a dialog to " Create new database". Simply type in a name for your database, then click the "create" button - I have chosen "afc" as the name for my database.
Next we need to create a table "albums" in our new database to store our album data. Select the "SQL" tab in phpMyAdmin, then paste the following query in the "Run SQL query/queries on database" dialog. Then click "go".
CREATE TABLE `albums` (
`album_id` int(11) NOT NULL auto_increment,
`artist_name` varchar(96) default NULL,
`album_name` varchar(96) default NULL,
`album_description` text,
`album_image` varchar(64) default NULL,
`album_songlist` text,
PRIMARY KEY (`album_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
That is all we need to do in phpMyAdmin as we will be creating a simple web form to populate our database with album data.
Part II - Our Working Directories
We now need to create a directory structure in which to place our files for the project. These will be created in either c:/easyphp/www/ or c:/wamp/www/ - I will use "easyphp" for the remainder of this tutorial.
Browse to the appropriate location on your computer . With the /www/ directory open, right click and create a new directory with the name "afc". It is within this directory that we shall place our working files and sub directories.
Now open the /afc/ directory and within that create three more directories: /js/ and /include/ and /images/. Then open the /include/ directory and within that create one more directory /class/. You should now have the following directory structure:
c:/easyphp/www/afc/
c:/easyphp/www/afc/images/
c:/easyphp/www/afc/include/
c:/easyphp/www/afc/js/
c:/easyphp/www/afc/include/class/
Part III - The Database Class
Next we need to create a simple PHP database class to handle database queries between our PHP scripts and MySQL.
If you dont have a programmer's text editor, Notepad will do. Do NOT use Microsoft Word. I personally use Ultraedit, however there are many freeware editors to be found online that are specifically designed for programming. They include neat features such a syntax highlighting, which makes reading code so much easier and text search functions which are extremely useful.
Open your text editor and paste the following code into it.
<?php
/*
Suomedia - Dynamic Content Management
http://suomedia.com
Copyright (c) 2007 Suomedia
*/
class flowSQL {
var $db_server;
var $db_user;
var $db_pass;
var $database;
var $link;
// initialise database connection
function flowSQL($db_server = DATABASE_SERVER, $db_user = DB_USERNAME, $db_pass = DB_PASSWORD, $database = DATABASE) {
$this->db_server = $db_server;
$this->db_user = $db_user;
$this->db_pass = $db_pass;
$this->database = $database;
$this->connect();
}
// make connection
function connect() {
$this->link = mysql_connect($this->db_server, $this->db_user, $this->db_pass);
mysql_select_db($this->database, $this->link);
}
// query database
function query($query) {
$this->data = mysql_query($query, $this->link);
if(!$this->data)
{
die('MySQL Error: ' . mysql_error() . '<br />');
} else {
return($this->data);
}
}
// fetch query result
function fetch_array($data = '') {
if($data == '')
$data = $this->data;
$this->row = mysql_fetch_array($data, MYSQL_BOTH);
return($this->row);
}
// close database connection
function close() {
return(mysql_close($this->link));
}
}
?>
We will name our file "mysql.php" and save it in: c:/easyphp/www/afc/include/class/
The use of classes such as the above greatly reduces programming time in creating repetitive tasks. Take the time to study the code and its associated comments (comments are preceded with a double slash // )
Part IV - The Configuration File
The configuration file contains information that is used throughout our PHP scripts, such as server and database info. The below file is very standard for an EasyPHP installation. The database user "root" is the default MySQL user and works for both EasyPHP and WAMP installations. The root user does not require a password.
http://localhost/ can be used for browsing on an Easyphp or Wamp installation using your web browser - just like having a "mini internet" on your own PC.
Paste the following code into a new page in your text editor:
<?php
/*
Suomedia - Dynamic Content Management
http://suomedia.com
Copyright (c) 2007 Suomedia
*/
// Server Configuration
define('SERVER', 'http://localhost');
define('HOME_DIR', '/afc/');
define('IMAGE_PATH', 'images/');
// Database Configuration
define('DATABASE_SERVER', 'localhost');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', '');
define('DATABASE', 'afc');
// Database Tables
define('TABLE_ALBUMS', 'albums');
?>
We will name our file "config.php" and save it in: c:/easyphp/www/afc/include/ You may notice that our database class we created previously uses configuration information contained in the above configuration file: DATABASE_SERVER, DB_USERNAME, DB_PASSWORD and DATABASE.
Part V - The Database Form
Now we can create a simple PHP form to be used for populating our MySQL database with album data.
Our basic form will look like this:
<!doctype html public "-//W3C//DTD HTML 4.01 Transitional//EN">
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Flow List Ajax Tutorial</title>
</head>
<body marginwidth="0" marginheight="0" topmargin="0" bottommargin="0" leftmargin="0" rightmargin="0">
<table cellspacing=0 cellpadding=0 width=700 align=center><form name="create_albums" enctype="multipart/form-data" action="create_albums.php" method="post"><input type="hidden" name="action" value="1">
<tr>
<td align="center"><br /><h1>Create Albums</h1><br /></td>
</tr>
</table>
<table cellspacing=0 cellpadding=0 width=700 align=center>
<tr>
<td valign="top" align="right" style="padding-right:20px;">Artist Name:</td><td><input type="text" name="artist_name"><br /><br /></td>
</tr>
<tr>
<td valign="top" align="right" style="padding-right:20px;">Album Name:</td><td><input type="text" name="album_name"><br /><br /></td>
</tr>
<tr>
<td valign="top" align="right" style="padding-right:20px;">Album Description:</td><td><textarea name="album description" rows="15" cols="30"></textarea><br/><br /></td>
</tr>
<tr>
<td valign="top" align="right" style="padding-right:20px;">Album Songlist:</td><td><textarea name="album songlist" rows="15" cols="30"></textarea><br/><br /></td>
</tr>
<tr>
<td valign="top" align="right" style="padding-right:20px;">Album Image:</td><td><input type="file" name="album_image" size="40"><br /><br /></td>
</tr>
<tr>
<td valign="top" align="right" colspan="2" style="padding-right:180px;"></br><br /><input type="submit" name="submit" value="submit"></form></br><br /></td>
</tr>
</table>
<br /><br />
</body>
</html>
Paste the above into a new page in your text editor, name it "create_albums.php" and save it to c:/easyphp/afc/
You should now be able to open your web browser and to browse to http://localhost/afc/create_albums.php and view your newly created form.
Thus far our form only looks pretty and wont populate our database. For this we need the magic of PHP.
We will begin by calling our configuration file and database class into our new file. Paste the following at the very top of create_albums.php:
<?php
/*
Suomedia - Dynamic Content Management
http://suomedia.com
Copyright (c) 2007 Suomedia
*/
// include the configuration file and database class
require('include/config.php');
require('include/class/mysql.php');
?>
*Note: Make sure that you do not leave any "whitespace" at the top of your file. The very first line should begin with <?php
The above code will make our configuration data and database class available to PHP for use in our script.
Next we need to check if our form has been posted and if it has, to do stuff. Before the closing PHP tag (?>) above paste the following:
if (isset($_POST['action']) && $_POST['action'] == '1') {
// Do stuff
}
All of our neat PHP magic that will populate the database will now go within the above conditional statement where you now see "// Do stuff".
Our form tag contains the line: enctype="multipart/form-data". This means that we are also posting a file to be uploaded to our server - our album image which will reside in the /images/ directory. We will do our file upload as the first part of our form post and if it fails to cancel the remainder of the form post (in case you forget to include the image). We will include an appropriate message upon success or failure. For this we will need the following PHP code:
// lets put the image where it belongs
$image_path = IMAGE_PATH . basename($_FILES['album_image']['name']);
if(move_uploaded_file($_FILES['album_image']['tmp_name'], $image_path)) {
echo '<span style="background:#00FF00;">The file ' . basename($_FILES['album_image']['name']). ' has been uploaded!</span>';
} else {
echo '<span style="background:#FF0000;">There was an error uploading the file, please try again!</span>';
die();
}
The above should be pasted where you see "// Do stuff" in the previous code.
Now we need to put our form post data into a suitable array to be inserted into our database. For this we will use our "albums" database table column names as the array keys, with the posted form data as the values:
// Put our form post data into an array (column_name => value)
$album_data_array = array('artist_name' => $_POST['artist_name'],
'album_name' => $_POST['album_name'],
'album_description' => $_POST['album_description'],
'album_songlist' => $_POST['album_songlist'],
'album_image' => basename($_FILES['album_image']['name'])
);
Paste the above code directly following the previous.
Now we are ready to insert our posted form data into our database. First we initialise our database class. Then we build comma separated lists of our column names and posted values. Finally we insert the data using a single query:
// initialise the database class
$data = new flowSQL;
$columns = null;
$values = null;
reset($album_data_array);
// build comma separated lists of column names and values
while(list($column_name, $column_value) = each($album_data_array)) {
$columns .= $column_name . ',';
$values .= "'" . $column_value . "',"; // values must be enclosed in quotes
}
// remove the trailing commas
$columns = rtrim($columns, ',');
$values = rtrim($values, ',');
// insert it all into our database
$data->query("insert into " . TABLE_ALBUMS . " (" . $columns . ") values (" . $values . ")");
$data->close();
Paste the above code directly below the previous. The top of your create_albums.php file should now look as follows:
<?php
/*
Suomedia - Dynamic Content Management
http://suomedia.com
Copyright (c) 2007 Suomedia
*/
// include the configuration file and database class
require('include/config.php');
require('include/class/mysql.php');
if (isset($_POST['action']) && $_POST['action'] == '1') {
// lets put the image where it belongs
$image_path = IMAGE_PATH . basename( $_FILES['album_image']['name']);
if(move_uploaded_file($_FILES['album_image']['tmp_name'], $image_path )) {
echo '<span style="background:#00FF00;">The file ' . basename( $_FILES['album_image']['name']). ' has been uploaded</span>';
} else {
echo '<span style="background:#FF0000;">There was an error uploading the file, please try again!</span>';
die();
}
// Put our form post data into an array (column_name => value)
$album_data_array = array('artist_name' => $_POST['artist_name'],
'album_name' => $_POST['album_name'],
'album_description' => $_POST['album_description'],
'album_songlist' => $_POST['album_songlist'],
'album_image' => basename($_FILES['album_image']['name'])
);
// initialise the database class
$data = new flowSQL;
$columns = null;
$values = null;
reset($album_data_array);
// build comma separated lists of column names and values
while(list($column_name, $column_value) = each($album_data_array)) {
$columns .= $column_name . ',';
$values .= "'" . $column_value . "',"; // values must be enclosed in quotes
}
// remove the trailing commas
$columns = rtrim($columns, ',');
$values = rtrim($values, ',');
// insert it all into our database
$data->query("insert into " . TABLE_ALBUMS . " (" . $columns . ") values (" . $values . ")");
$data->close();
}
?>
Our form is now complete. Save your file, then you can again open your web browser and browse to http://localhost/afc/create_albums.php and test the form. You can open phpMyAdmin and select your database from the left column, then select your "albums" table. Click the "Browse" tab to view your data.
Part VI - A Dynamic XML File
Now we will create an XML file in PHP that will retrieve data from the "albums" table in our database for display in Flow List. Open a new page in your text editor and paste the following code:
<?php
/*
Suomedia - Dynamic Content Management
http://suomedia.com
Copyright (c) 2007 Suomedia
*/
// include the configuration file and database class
require('include/config.php');
require('include/class/mysql.php');
// initialise the database class
$data = new flowSQL;
// opening XML tag
echo "<content>";
// fetch all albums from the albums database table
$album_query = $data->query("select * from " . TABLE_ALBUMS . "");
// build the xml content for each album
while($album_result = $data->fetch_array($album_query)) {
echo " <image>";
echo " <path>";
echo SERVER . HOME_DIR . 'images/' . $album_result['album_image'];
echo "</path>";
echo " <description>";
echo $album_result['album_name'];
echo "</description>";
echo " <data>";
echo urlencode('javascript:loadContent("' . $album_result['album_id'] . '","content.php","mycontent","<img style=vertical-align:middle src=images/loading.gif> Please wait...");');
echo "</data>";
echo " </image>";
}
// closing XML tag
echo "</content>";
$data->close();
?>
We will name our file "album_xml.php" and save it to c:/easyphp/afc/
Thankfully Flash will accept XML data from files with any file extension so long as the data is valid XML. We will be able to call this file directly into Flow List to display all the albums we have in our database.
You may test this file by opening your browser to: http://localhost/afc/album_xml.php
If you view the page source you will see a nicely formatted XML file, perfect for Flow List.
The line contained within the <data> tags of our XML file will fire the Ajax function that will load our page content as each album is selected. Lets take a look at that.
Part VII - The Magic of Ajax
If you have been expecting to download some obscure and massive javascript libraries you will be disappointed. Here is all the javascript that is needed to admirably display our album content using Ajax:
var request;
/*
key = album_id
file = the file we will load using Ajax
elem = the id of the page element where we wish to load our document
img = the name of our "loading" image
*/
function loadContent(key,file,elem,img) {
var url=file+"?value="+key;
if (img) {
getObject(elem).innerHTML = img; // display a "loading" image
}
// Internet Explorer
try {
request = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e) {
try {
request = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(oc) {
request = null;
}
}
// Other browsers
if (!request && typeof XMLHttpRequest != "undefined") {
request = new XMLHttpRequest();
}
if (request != null) {
request.onreadystatechange=function(){
if(request.readyState!=4)return;
if(request.status==200){
getObject(elem).innerHTML = request.responseText // display our content
}
}
request.open("GET", url, true);
request.send(null);
}
}
// browser compatibility
function getObject(name) {
var ns4 = (document.layers) ? true : false;
var w3c = (document.getElementById) ? true : false;
var ie4 = (document.all) ? true : false;
if (ns4) return eval('document.' + name);
if (w3c) return document.getElementById(name);
if (ie4) return eval('document.all.' + name);
return false;
}
Open a new page in your text editor and copy and paste the above code into it. Save it as "ajax.js" in c:/easyphp/afc/js/
The script requires a "loading.gif" image file to display while the page content is loading. You may download one here: www.suomedia.com/images/loading.gif Save this image to c:/easyphp/afc/images/
Part VIII - The Content File
The content file is the file that will load album content onto our display page using Ajax. When a user clicks an image in Flow List our Ajax function is fired. This sends a http get request to the web server requesting the content file to load. The request includes the album_id so our content file "knows" which album to load.
<?php
/*
Suomedia - Dynamic Content Management
http://suomedia.com
Copyright (c) 2007 Suomedia
*/
// include the configuration file and database class
require('include/config.php');
require('include/class/mysql.php');
if (isset($_GET['value'])) {
// initialise the database class
$data = new flowSQL;
$album_query = $data->query("select * from " . TABLE_ALBUMS . " where album_id = '" . (int)$_GET['value'] . "'");
$album_result = $data->fetch_array($album_query);
$data->close();
?>
<table cellspacing=0 cellpadding=0 width=400 align=center>
<tr>
<td align="center"><br /><br /><img src="images/<?php echo $album_result['album_image']; ?>"><br /><br /></td>
</tr>
<tr>
<td align="center"><h3><?php echo $album_result['album_name']; ?><br /><br /></h3></td>
</tr>
<tr>
<td><b>Artist: <?php echo $album_result['artist_name']; ?><b><br /><br /></td>
</tr>
<tr>
<td><?php echo $album_result['album_description']; ?><br /><br /></td>
</tr>
<tr>
<td><b>Songlist:</b><br /><br /><?php echo $album_result['album_songlist']; ?><br /><br /></td>
</tr>
</table>
<?php
}
?>
Open a new page in your text editor and copy and paste the above code into it. Save it as "content.php" in c:/easyphp/afc/
If you would like to test your content file you can do so as follows: assuming that you have already tested the create_albums.php file and have some albums in your database, open your browser to: http://localhost/afc/content.php?value=1
This will display the first album in your database.
Part IX - The Flow List Object
Now its time to create our Flow List object for our display page.
Open Flash and create a new flash document (File > New > Flash Document). If you are using Flash CS3 make sure you create an ActionScript 2.0 document.
Open the components window (Window > Components), expand the AF Components node and drag the Flow List component onto the stage. Give it an instance name myFlow.
Create a new timeline layer and name it name it actions. Select the first frame of the actions layer and open Actions window (Window > Actions). Paste the following code inside:
// load selected item
myFlow.addEventListener("ITEM_ON_PRESS", this);
function ITEM_ON_PRESS(evnt:Object) {
getURL(unescape(evnt.target.data));
}
Next click the Flow List component on the stage and select the "parameters" tab. Set the contentXML path as follows:
contentXML:http://localhost/afc/album_xml.php
Export your movie as "albums.swf" to c:/easyphp/afc/
Part X - The Display Page
The display page will display our Flow List object and into it will load our album data as each image is clicked.
Open a new page in your text editor and paste in the following code:
<!doctype html public "-//W3C//DTD HTML 4.01 Transitional//EN">
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Flow List Ajax Tutorial</title>
<script type="text/javascript" src="js/ajax.js"></script>
</head>
<body marginwidth="0" marginheight="0" topmargin="0" bottommargin="0" leftmargin="0" rightmargin="0">
<table cellspacing=0 cellpadding=0 width=700 align=center>
<tr>
<td align="center"><br /><h1>My Albums</h1><br /></td>
</tr>
</table>
<table cellspacing=0 cellpadding=0 width=700 align=center>
<tr>
<td align="center"><embed width="530" height="167" menu="true" loop="true" play="true" src="albums.swf" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash"></embed></td>
</tr>
</table>
<table cellspacing=0 cellpadding=0 width=400 align=center>
<tr>
<td align="center" id="mycontent">My Content</td>
</tr>
</table>
<br /><br />
</body>
</html>
As you can see, this file is entirely HTML and can be named and saved as you wish, whether HTML or as a PHP file. I have named mine "index.html". Save the file in c:/easyphp/afc/
You can now open your web browser and browse to your newly created album display: http://localhost/afc/index.html
Thats it. Feel free to contact me through the Flow List Forums: www.afcomponents.com/forum/profile.php
Enjoy!
Matti Ressler
Suomedia
Matti Ressler is the CEO of Suomedia who specialise in dynamic web application development and ecommerce systems. He is also a Senior Team Member of the osCommerce open source ecommerce project.
www.suomedia.com
Asynchronous JavaScript and XML (Ajax) uses the javascript XMLHttpRequest object to send HTTP requests between the user's browser and serverside scripts without reloading the current browser window. In this tutorial we will build a very simple music album display. The same techniques can be used in many different ways with Flow List, from photo albums to catalog displays.
Note: The scripts I will be presenting here are for tutorial purposes only and should not be used in a live environment without more comprehensive security and error checking etc. - these are just the basics to help you get started.
You can see a working example of these techniques used in an installation of osCommerce here
My recommendation is to use these scripts on a local test environment and to build onto them whatever you need to use in a live environment. My personal preferences for development are Easyphp and Wamp, both of which allow simple installation of Apache Web Server, PHP and MySQL and phpMyAdmin on a PC and are free software. I use these extensively for developing web applications as they allow me to browser test entire PHP/MySQL driven websites on my local PC. I highly recommend using one of these to work through this tutorial.
*Note: When installing either of these development environments on Windows, do not allow the installer to install in the default "program files" directory. Instead, install them in either c:/easyphp/ or c:/wamp/ - this measure will save you endless headaches.
A working knowledge of PHP and MySQL and Javascript and Flash and phpMyAdmin is assumed, however the tutorial and scripts are extensively commented to help the learning process.
To complete this tutorial, you will also need the Flow List Component
Part I - The Database
Let's begin by creating an empty database using phpMyAdmin. Make sure that either EasyPHP or WAMP is started on your computer. You can open phpMyadmin in EasyPHP by right clicking the system tray icon and selecting "Administration" and then "Manage Database". If you are using WAMP, simply left click the tray icon and select "phpMyAdmin".
The default window of phpMyAdmin presents a dialog to " Create new database". Simply type in a name for your database, then click the "create" button - I have chosen "afc" as the name for my database.
Next we need to create a table "albums" in our new database to store our album data. Select the "SQL" tab in phpMyAdmin, then paste the following query in the "Run SQL query/queries on database" dialog. Then click "go".
CREATE TABLE `albums` (
`album_id` int(11) NOT NULL auto_increment,
`artist_name` varchar(96) default NULL,
`album_name` varchar(96) default NULL,
`album_description` text,
`album_image` varchar(64) default NULL,
`album_songlist` text,
PRIMARY KEY (`album_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
That is all we need to do in phpMyAdmin as we will be creating a simple web form to populate our database with album data.
Part II - Our Working Directories
We now need to create a directory structure in which to place our files for the project. These will be created in either c:/easyphp/www/ or c:/wamp/www/ - I will use "easyphp" for the remainder of this tutorial.
Browse to the appropriate location on your computer . With the /www/ directory open, right click and create a new directory with the name "afc". It is within this directory that we shall place our working files and sub directories.
Now open the /afc/ directory and within that create three more directories: /js/ and /include/ and /images/. Then open the /include/ directory and within that create one more directory /class/. You should now have the following directory structure:
c:/easyphp/www/afc/
c:/easyphp/www/afc/images/
c:/easyphp/www/afc/include/
c:/easyphp/www/afc/js/
c:/easyphp/www/afc/include/class/
Part III - The Database Class
Next we need to create a simple PHP database class to handle database queries between our PHP scripts and MySQL.
If you dont have a programmer's text editor, Notepad will do. Do NOT use Microsoft Word. I personally use Ultraedit, however there are many freeware editors to be found online that are specifically designed for programming. They include neat features such a syntax highlighting, which makes reading code so much easier and text search functions which are extremely useful.
Open your text editor and paste the following code into it.
<?php
/*
Suomedia - Dynamic Content Management
http://suomedia.com
Copyright (c) 2007 Suomedia
*/
class flowSQL {
var $db_server;
var $db_user;
var $db_pass;
var $database;
var $link;
// initialise database connection
function flowSQL($db_server = DATABASE_SERVER, $db_user = DB_USERNAME, $db_pass = DB_PASSWORD, $database = DATABASE) {
$this->db_server = $db_server;
$this->db_user = $db_user;
$this->db_pass = $db_pass;
$this->database = $database;
$this->connect();
}
// make connection
function connect() {
$this->link = mysql_connect($this->db_server, $this->db_user, $this->db_pass);
mysql_select_db($this->database, $this->link);
}
// query database
function query($query) {
$this->data = mysql_query($query, $this->link);
if(!$this->data)
{
die('MySQL Error: ' . mysql_error() . '<br />');
} else {
return($this->data);
}
}
// fetch query result
function fetch_array($data = '') {
if($data == '')
$data = $this->data;
$this->row = mysql_fetch_array($data, MYSQL_BOTH);
return($this->row);
}
// close database connection
function close() {
return(mysql_close($this->link));
}
}
?>
We will name our file "mysql.php" and save it in: c:/easyphp/www/afc/include/class/
The use of classes such as the above greatly reduces programming time in creating repetitive tasks. Take the time to study the code and its associated comments (comments are preceded with a double slash // )
Part IV - The Configuration File
The configuration file contains information that is used throughout our PHP scripts, such as server and database info. The below file is very standard for an EasyPHP installation. The database user "root" is the default MySQL user and works for both EasyPHP and WAMP installations. The root user does not require a password.
http://localhost/ can be used for browsing on an Easyphp or Wamp installation using your web browser - just like having a "mini internet" on your own PC.
Paste the following code into a new page in your text editor:
<?php
/*
Suomedia - Dynamic Content Management
http://suomedia.com
Copyright (c) 2007 Suomedia
*/
// Server Configuration
define('SERVER', 'http://localhost');
define('HOME_DIR', '/afc/');
define('IMAGE_PATH', 'images/');
// Database Configuration
define('DATABASE_SERVER', 'localhost');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', '');
define('DATABASE', 'afc');
// Database Tables
define('TABLE_ALBUMS', 'albums');
?>
We will name our file "config.php" and save it in: c:/easyphp/www/afc/include/ You may notice that our database class we created previously uses configuration information contained in the above configuration file: DATABASE_SERVER, DB_USERNAME, DB_PASSWORD and DATABASE.
Part V - The Database Form
Now we can create a simple PHP form to be used for populating our MySQL database with album data.
Our basic form will look like this:
<!doctype html public "-//W3C//DTD HTML 4.01 Transitional//EN">
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Flow List Ajax Tutorial</title>
</head>
<body marginwidth="0" marginheight="0" topmargin="0" bottommargin="0" leftmargin="0" rightmargin="0">
<table cellspacing=0 cellpadding=0 width=700 align=center><form name="create_albums" enctype="multipart/form-data" action="create_albums.php" method="post"><input type="hidden" name="action" value="1">
<tr>
<td align="center"><br /><h1>Create Albums</h1><br /></td>
</tr>
</table>
<table cellspacing=0 cellpadding=0 width=700 align=center>
<tr>
<td valign="top" align="right" style="padding-right:20px;">Artist Name:</td><td><input type="text" name="artist_name"><br /><br /></td>
</tr>
<tr>
<td valign="top" align="right" style="padding-right:20px;">Album Name:</td><td><input type="text" name="album_name"><br /><br /></td>
</tr>
<tr>
<td valign="top" align="right" style="padding-right:20px;">Album Description:</td><td><textarea name="album description" rows="15" cols="30"></textarea><br/><br /></td>
</tr>
<tr>
<td valign="top" align="right" style="padding-right:20px;">Album Songlist:</td><td><textarea name="album songlist" rows="15" cols="30"></textarea><br/><br /></td>
</tr>
<tr>
<td valign="top" align="right" style="padding-right:20px;">Album Image:</td><td><input type="file" name="album_image" size="40"><br /><br /></td>
</tr>
<tr>
<td valign="top" align="right" colspan="2" style="padding-right:180px;"></br><br /><input type="submit" name="submit" value="submit"></form></br><br /></td>
</tr>
</table>
<br /><br />
</body>
</html>
Paste the above into a new page in your text editor, name it "create_albums.php" and save it to c:/easyphp/afc/
You should now be able to open your web browser and to browse to http://localhost/afc/create_albums.php and view your newly created form.
Thus far our form only looks pretty and wont populate our database. For this we need the magic of PHP.
We will begin by calling our configuration file and database class into our new file. Paste the following at the very top of create_albums.php:
<?php
/*
Suomedia - Dynamic Content Management
http://suomedia.com
Copyright (c) 2007 Suomedia
*/
// include the configuration file and database class
require('include/config.php');
require('include/class/mysql.php');
?>
*Note: Make sure that you do not leave any "whitespace" at the top of your file. The very first line should begin with <?php
The above code will make our configuration data and database class available to PHP for use in our script.
Next we need to check if our form has been posted and if it has, to do stuff. Before the closing PHP tag (?>) above paste the following:
if (isset($_POST['action']) && $_POST['action'] == '1') {
// Do stuff
}
All of our neat PHP magic that will populate the database will now go within the above conditional statement where you now see "// Do stuff".
Our form tag contains the line: enctype="multipart/form-data". This means that we are also posting a file to be uploaded to our server - our album image which will reside in the /images/ directory. We will do our file upload as the first part of our form post and if it fails to cancel the remainder of the form post (in case you forget to include the image). We will include an appropriate message upon success or failure. For this we will need the following PHP code:
// lets put the image where it belongs
$image_path = IMAGE_PATH . basename($_FILES['album_image']['name']);
if(move_uploaded_file($_FILES['album_image']['tmp_name'], $image_path)) {
echo '<span style="background:#00FF00;">The file ' . basename($_FILES['album_image']['name']). ' has been uploaded!</span>';
} else {
echo '<span style="background:#FF0000;">There was an error uploading the file, please try again!</span>';
die();
}
The above should be pasted where you see "// Do stuff" in the previous code.
Now we need to put our form post data into a suitable array to be inserted into our database. For this we will use our "albums" database table column names as the array keys, with the posted form data as the values:
// Put our form post data into an array (column_name => value)
$album_data_array = array('artist_name' => $_POST['artist_name'],
'album_name' => $_POST['album_name'],
'album_description' => $_POST['album_description'],
'album_songlist' => $_POST['album_songlist'],
'album_image' => basename($_FILES['album_image']['name'])
);
Paste the above code directly following the previous.
Now we are ready to insert our posted form data into our database. First we initialise our database class. Then we build comma separated lists of our column names and posted values. Finally we insert the data using a single query:
// initialise the database class
$data = new flowSQL;
$columns = null;
$values = null;
reset($album_data_array);
// build comma separated lists of column names and values
while(list($column_name, $column_value) = each($album_data_array)) {
$columns .= $column_name . ',';
$values .= "'" . $column_value . "',"; // values must be enclosed in quotes
}
// remove the trailing commas
$columns = rtrim($columns, ',');
$values = rtrim($values, ',');
// insert it all into our database
$data->query("insert into " . TABLE_ALBUMS . " (" . $columns . ") values (" . $values . ")");
$data->close();
Paste the above code directly below the previous. The top of your create_albums.php file should now look as follows:
<?php
/*
Suomedia - Dynamic Content Management
http://suomedia.com
Copyright (c) 2007 Suomedia
*/
// include the configuration file and database class
require('include/config.php');
require('include/class/mysql.php');
if (isset($_POST['action']) && $_POST['action'] == '1') {
// lets put the image where it belongs
$image_path = IMAGE_PATH . basename( $_FILES['album_image']['name']);
if(move_uploaded_file($_FILES['album_image']['tmp_name'], $image_path )) {
echo '<span style="background:#00FF00;">The file ' . basename( $_FILES['album_image']['name']). ' has been uploaded</span>';
} else {
echo '<span style="background:#FF0000;">There was an error uploading the file, please try again!</span>';
die();
}
// Put our form post data into an array (column_name => value)
$album_data_array = array('artist_name' => $_POST['artist_name'],
'album_name' => $_POST['album_name'],
'album_description' => $_POST['album_description'],
'album_songlist' => $_POST['album_songlist'],
'album_image' => basename($_FILES['album_image']['name'])
);
// initialise the database class
$data = new flowSQL;
$columns = null;
$values = null;
reset($album_data_array);
// build comma separated lists of column names and values
while(list($column_name, $column_value) = each($album_data_array)) {
$columns .= $column_name . ',';
$values .= "'" . $column_value . "',"; // values must be enclosed in quotes
}
// remove the trailing commas
$columns = rtrim($columns, ',');
$values = rtrim($values, ',');
// insert it all into our database
$data->query("insert into " . TABLE_ALBUMS . " (" . $columns . ") values (" . $values . ")");
$data->close();
}
?>
Our form is now complete. Save your file, then you can again open your web browser and browse to http://localhost/afc/create_albums.php and test the form. You can open phpMyAdmin and select your database from the left column, then select your "albums" table. Click the "Browse" tab to view your data.
Part VI - A Dynamic XML File
Now we will create an XML file in PHP that will retrieve data from the "albums" table in our database for display in Flow List. Open a new page in your text editor and paste the following code:
<?php
/*
Suomedia - Dynamic Content Management
http://suomedia.com
Copyright (c) 2007 Suomedia
*/
// include the configuration file and database class
require('include/config.php');
require('include/class/mysql.php');
// initialise the database class
$data = new flowSQL;
// opening XML tag
echo "<content>";
// fetch all albums from the albums database table
$album_query = $data->query("select * from " . TABLE_ALBUMS . "");
// build the xml content for each album
while($album_result = $data->fetch_array($album_query)) {
echo " <image>";
echo " <path>";
echo SERVER . HOME_DIR . 'images/' . $album_result['album_image'];
echo "</path>";
echo " <description>";
echo $album_result['album_name'];
echo "</description>";
echo " <data>";
echo urlencode('javascript:loadContent("' . $album_result['album_id'] . '","content.php","mycontent","<img style=vertical-align:middle src=images/loading.gif> Please wait...");');
echo "</data>";
echo " </image>";
}
// closing XML tag
echo "</content>";
$data->close();
?>
We will name our file "album_xml.php" and save it to c:/easyphp/afc/
Thankfully Flash will accept XML data from files with any file extension so long as the data is valid XML. We will be able to call this file directly into Flow List to display all the albums we have in our database.
You may test this file by opening your browser to: http://localhost/afc/album_xml.php
If you view the page source you will see a nicely formatted XML file, perfect for Flow List.
The line contained within the <data> tags of our XML file will fire the Ajax function that will load our page content as each album is selected. Lets take a look at that.
Part VII - The Magic of Ajax
If you have been expecting to download some obscure and massive javascript libraries you will be disappointed. Here is all the javascript that is needed to admirably display our album content using Ajax:
var request;
/*
key = album_id
file = the file we will load using Ajax
elem = the id of the page element where we wish to load our document
img = the name of our "loading" image
*/
function loadContent(key,file,elem,img) {
var url=file+"?value="+key;
if (img) {
getObject(elem).innerHTML = img; // display a "loading" image
}
// Internet Explorer
try {
request = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e) {
try {
request = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(oc) {
request = null;
}
}
// Other browsers
if (!request && typeof XMLHttpRequest != "undefined") {
request = new XMLHttpRequest();
}
if (request != null) {
request.onreadystatechange=function(){
if(request.readyState!=4)return;
if(request.status==200){
getObject(elem).innerHTML = request.responseText // display our content
}
}
request.open("GET", url, true);
request.send(null);
}
}
// browser compatibility
function getObject(name) {
var ns4 = (document.layers) ? true : false;
var w3c = (document.getElementById) ? true : false;
var ie4 = (document.all) ? true : false;
if (ns4) return eval('document.' + name);
if (w3c) return document.getElementById(name);
if (ie4) return eval('document.all.' + name);
return false;
}
Open a new page in your text editor and copy and paste the above code into it. Save it as "ajax.js" in c:/easyphp/afc/js/
The script requires a "loading.gif" image file to display while the page content is loading. You may download one here: www.suomedia.com/images/loading.gif Save this image to c:/easyphp/afc/images/
Part VIII - The Content File
The content file is the file that will load album content onto our display page using Ajax. When a user clicks an image in Flow List our Ajax function is fired. This sends a http get request to the web server requesting the content file to load. The request includes the album_id so our content file "knows" which album to load.
<?php
/*
Suomedia - Dynamic Content Management
http://suomedia.com
Copyright (c) 2007 Suomedia
*/
// include the configuration file and database class
require('include/config.php');
require('include/class/mysql.php');
if (isset($_GET['value'])) {
// initialise the database class
$data = new flowSQL;
$album_query = $data->query("select * from " . TABLE_ALBUMS . " where album_id = '" . (int)$_GET['value'] . "'");
$album_result = $data->fetch_array($album_query);
$data->close();
?>
<table cellspacing=0 cellpadding=0 width=400 align=center>
<tr>
<td align="center"><br /><br /><img src="images/<?php echo $album_result['album_image']; ?>"><br /><br /></td>
</tr>
<tr>
<td align="center"><h3><?php echo $album_result['album_name']; ?><br /><br /></h3></td>
</tr>
<tr>
<td><b>Artist: <?php echo $album_result['artist_name']; ?><b><br /><br /></td>
</tr>
<tr>
<td><?php echo $album_result['album_description']; ?><br /><br /></td>
</tr>
<tr>
<td><b>Songlist:</b><br /><br /><?php echo $album_result['album_songlist']; ?><br /><br /></td>
</tr>
</table>
<?php
}
?>
Open a new page in your text editor and copy and paste the above code into it. Save it as "content.php" in c:/easyphp/afc/
If you would like to test your content file you can do so as follows: assuming that you have already tested the create_albums.php file and have some albums in your database, open your browser to: http://localhost/afc/content.php?value=1
This will display the first album in your database.
Part IX - The Flow List Object
Now its time to create our Flow List object for our display page.
Open Flash and create a new flash document (File > New > Flash Document). If you are using Flash CS3 make sure you create an ActionScript 2.0 document.
Open the components window (Window > Components), expand the AF Components node and drag the Flow List component onto the stage. Give it an instance name myFlow.
Create a new timeline layer and name it name it actions. Select the first frame of the actions layer and open Actions window (Window > Actions). Paste the following code inside:
// load selected item
myFlow.addEventListener("ITEM_ON_PRESS", this);
function ITEM_ON_PRESS(evnt:Object) {
getURL(unescape(evnt.target.data));
}
Next click the Flow List component on the stage and select the "parameters" tab. Set the contentXML path as follows:
contentXML:http://localhost/afc/album_xml.php
Export your movie as "albums.swf" to c:/easyphp/afc/
Part X - The Display Page
The display page will display our Flow List object and into it will load our album data as each image is clicked.
Open a new page in your text editor and paste in the following code:
<!doctype html public "-//W3C//DTD HTML 4.01 Transitional//EN">
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Flow List Ajax Tutorial</title>
<script type="text/javascript" src="js/ajax.js"></script>
</head>
<body marginwidth="0" marginheight="0" topmargin="0" bottommargin="0" leftmargin="0" rightmargin="0">
<table cellspacing=0 cellpadding=0 width=700 align=center>
<tr>
<td align="center"><br /><h1>My Albums</h1><br /></td>
</tr>
</table>
<table cellspacing=0 cellpadding=0 width=700 align=center>
<tr>
<td align="center"><embed width="530" height="167" menu="true" loop="true" play="true" src="albums.swf" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash"></embed></td>
</tr>
</table>
<table cellspacing=0 cellpadding=0 width=400 align=center>
<tr>
<td align="center" id="mycontent">My Content</td>
</tr>
</table>
<br /><br />
</body>
</html>
As you can see, this file is entirely HTML and can be named and saved as you wish, whether HTML or as a PHP file. I have named mine "index.html". Save the file in c:/easyphp/afc/
You can now open your web browser and browse to your newly created album display: http://localhost/afc/index.html
Thats it. Feel free to contact me through the Flow List Forums: www.afcomponents.com/forum/profile.php
Enjoy!
Matti Ressler
Suomedia
Matti Ressler is the CEO of Suomedia who specialise in dynamic web application development and ecommerce systems. He is also a Senior Team Member of the osCommerce open source ecommerce project.
www.suomedia.com