Vous êtes sur la page 1sur 10

Building an XML Flash Application with PHP and MySQL Pt.

I
Gareth Downes-Powell

Building an XML Flash Application with PHP and MySQL Pt.I


In this tutorial, we will be building a Flash Application that displays information held in a MySQL database, using PHP and XML to pass data between the database and Flash. In the first part of this tutorial we'll be creating the database, and PHP pages, which will query the database and return the results in the form of an XML document. In the second part of the tutorial, we will be building the Flash application to display the XML data passed by the PHP pages in real time to the user.

The Project
In this tutorial, we're going to create the Flash application shown below, for the fictional Jungle Pet Store.

The finished application will display an inventory of the animals on sale at the pet store, along with a picture and a short description of the particular animal. Customers can select from different type of animals, such as amphibians, snakes etc, and a list is automatically updated showing the various types of animals in that category. Clicking on a particular animal shows more details about that animal. The details of the animals in stock are held in a MySQL database, and are read using PHP. The Flash application contacts a PHP page sending the information required. The PHP page then reads the information from the database, and sends it back to Flash in XML format. The Flash application then reads the XML and uses it to display the data.

Requirements
MySQL PHP with the DOM extension enabled Flash MX Professional

Copyright 2004 DMXzone.com All Rights Reserved To get more go to DMXzone.com

Page 1 of 10

Building an XML Flash Application with PHP and MySQL Pt.I


Gareth Downes-Powell

Creating the Database


The first stage in creating the application is to create the database.

Creating the Database and MySQL user


Using a database tool such as phpMyAdmin (available from http://www.phpmyadmin.net/) create a new database named jungle. Next, create a new MySQL user to access the database with the following details: Username: jungle Password: petstore

Creating the Database Tables


Now that we have our database set up, we need to create the tables that we'll use.

Creating the Categories table


The first table we will use will hold the list of categories of animal and is named categories. This table has the following fields: Field Name id category Type integer (11) varchar(75) Extra auto_increment

You can create this table by executing the following SQL. CREATE TABLE categories ( id int(11) NOT NULL auto_increment, category varchar(75) NOT NULL default '', PRIMARY KEY (id) ) TYPE=MyISAM;

Creating the Inventory Table


Next, let's create the table which will hold the details about each of the animals on sale. Create a new table called inventory and add the following fields. Field Name id name category price description image Type integer (11) varchar(100) varchar(75) varchar(10) varchar(250) varchar(200) Extra auto_increment

Copyright 2004 DMXzone.com All Rights Reserved To get more go to DMXzone.com

Page 2 of 10

Building an XML Flash Application with PHP and MySQL Pt.I


Gareth Downes-Powell

Again, you can create this table easily by running the SQL shown below: CREATE TABLE inventory ( id int(11) NOT NULL auto_increment, name varchar(100) NOT NULL default '', category varchar(75) NOT NULL default '', price varchar(10) NOT NULL default '', description varchar(250) NOT NULL default '', image varchar(200) NOT NULL default '', PRIMARY KEY (id) ) TYPE=MyISAM;

Adding Data to the Tables


Once the tables have been created, the next stage is to populate them with some example data.

Adding Data to the Categories Table


Using the SQL below insert the data into the categories table (this can be done easily by executing it through a tool such as phpMyAdmin, or by adding the data manually): INSERT INSERT INSERT INSERT INTO INTO INTO INTO categories categories categories categories VALUES VALUES VALUES VALUES (1, (2, (3, (4, 'Amphibians'); 'Snakes'); 'Spiders'); 'Insects');

This gives us the categories we will be using for the example.

Adding Data to the Inventory Table


The next step is to add data to the inventory table so we have some descriptions of the animals themselves, along with the category each animal falls in. The SQL that will insert the sample data I've been working with is:

Copyright 2004 DMXzone.com All Rights Reserved To get more go to DMXzone.com

Page 3 of 10

Building an XML Flash Application with PHP and MySQL Pt.I


Gareth Downes-Powell

INSERT INTO inventory VALUES (2, 'Grey Tree Frog', 'Amphibians', '45.00', 'The chameleon of the frog world, can change to almost any natural colour', '/images/greytreefrog.jpg'); INSERT INTO inventory VALUES (1, 'American Green Tree Frog', 'Amphibians', '39.99', 'Easy to keep, changes colour from yellow to dark brown', '/images/americantreefrog.jpg'); INSERT INTO inventory VALUES (3, 'Poison Frog', 'Amphibians', '74.99', 'Dendrobates Azureus - Stunning unnatural blue frogs, need some experience to keep them successfully', '/images/azureus.jpg'); INSERT INTO inventory VALUES (4, 'Garter Snake', 'Snakes', '25.99', 'Common snakes, easy to look after and keep', '/images/garter.jpg'); INSERT INTO inventory VALUES (5, 'Jungle Carpet Python', 'Snakes', '149.99', 'Medium sized pythons, growing to 6 or 7 foot. Good Feeders at all ages', '/images/junglecarpetpython.jpg'); INSERT INTO inventory VALUES (6, 'Cobra', 'Snakes', '249.99', 'Highly venemous snakes, experienced handlers only', '/images/cobra.jpg'); INSERT INTO inventory VALUES (7, 'Mexican Red Kneed Tarantula', 'Spiders', '45.99', 'Usually peaceful, however can release hairs which can cause blindness or rashes', '/images/mexicanredknee.jpg'); INSERT INTO inventory VALUES (8, 'Black Widow', 'Spiders', '99.99', 'Highly venemous spiders, for experienced collectors only', '/images./blackwidow.jpg'); INSERT INTO inventory VALUES (9, 'Mouse Spider', 'Spiders', '89.99', 'Mouse Spider native to Australia, often confused with funnel-web spiders', '/images/mousespider.jpg'); INSERT INTO inventory VALUES (10, 'Giant Snail', 'Insects', '9.99', 'Giant Snails, interesting pets with a life span of up to 20 years!', '/images/giantsnail.jpg'); INSERT INTO inventory VALUES (11, 'Crickets', 'Insects', '2.99', 'Sold in packs of 24. Interesting pets or ideal as food for other animals', '/images/cricket.jpg'); INSERT INTO inventory VALUES (12, 'Locusts', 'Insects', '4.99', 'Easy to keep, ideal for studying', 'images/locusts.jpg'); Now that we have filled our database with data, we can move on and start creating the PHP pages, which will read from the database, and send the data in XML format to the Flash application.

Creating the PHP Pages


In this section of the tutorial we need to look at building some PHP to cover three areas. Our first task will be to code up a database connection. Then we'll build a page that can be used to read from the categories table. This page will execute an SQL statement against the categories table and will then convert all the information returned into XML format, ready to be read through the Flash application. Lastly, for this article, we'll create a page to work with the inventory information.

Creating a Database Connection File dbConnection.php


The first page that we are going to create will be used an as an include file, and will contain the information required to connect to the database. It makes sense to have this information in a separate file, so that in future if the database connection information changes (say we change servers) then we only need to change one file, and don't have to change any code on any other pages.

Copyright 2004 DMXzone.com All Rights Reserved To get more go to DMXzone.com

Page 4 of 10

Building an XML Flash Application with PHP and MySQL Pt.I


Gareth Downes-Powell

Create a new PHP page in Dreamweaver MX, and delete all the automatically generated code so the page is blank. Create in a new directory called includes in the root directory of your website, and save the file in the includes directory as dbConnection.php. Next, in code view, add the code shown below to the page (this code assumes the PHP server and the MySQL server are on the same computer): <?php // Database Connection Parameters $dbHost = "localhost"; $dbName = "jungle"; $dbUser = "jungle"; $dbPass = "petstore"; ?> In the code above, we have the hostname of the MySQL server which is localhost if the PHP server and MySQL server are on the same computer. We also have the name of the database, and the username and password used to connect to it (that we defined at the start of the article). Save the page, close it and upload to your web server. Next job reading data from the categories table

Creating the category.php page


In Dreamweaver MX, open a new PHP page. Because this page will only be called through Flash and is never called directly, we don't need any HTML on this page the output will be pure XML. Delete all the code automatically placed on the page by Dreamweaver, and then save the page as category.php.

Reading from the Database


The first section of code we need to add to the page is to enable the categories to be extracted from the database. Switch into code view, and add the following code to the page: <?php // Include Database Connection File require_once("C:/webserver/includes/dbConnection.php"); // Open Database Connection and Select Database $dbLink = mysql_connect($dbHost, $dbUser, $dbPass); if (!$dbLink){ die ("Database: Couldn`t connect to mySQL Server"); } mysql_select_db($dbName, $dbLink) or die ("Database: Couldn`t open Database"); // Create SQL Query $sql = "SELECT category FROM categories ORDER BY category ASC "; // Execute SQL Query and Read in Records $dbResult = mysql_query($sql, $dbLink) or die ("MySQL Error: " . mysql_error() ); $numRecords = mysql_num_rows($dbResult); $recordset = ""; for($i=0;$i<$numRecords;$i++){ $recordset[] = mysql_fetch_assoc($dbResult); } mysql_close($dbLink); ?>
Copyright 2004 DMXzone.com All Rights Reserved To get more go to DMXzone.com

Page 5 of 10

Building an XML Flash Application with PHP and MySQL Pt.I


Gareth Downes-Powell

First, we add the dbConnection.php include file to the page, which will make the database connection variables available to us. Next, we open a connection to the database using the mysql_connect() command passing it the database server address, and the username and password needed to connect (from the include file). A link to the database connection is passed back which we store in $dbLink. If the database connection cannot be opened we stop the script using the die() command and display a message to the user. Next, we use the mysql_select_db() command to tell MySQL which database we want to work with. Again, if the command fails we use the die() command to stop the script as there's no point in continuing. We then create the SQL statement to select all the categories from the categories table, ordered in alphabetical order. The next step is to execute the SQL query using the mysql_query() command, passing it the query and the link to the open database connection. As usual, if the command fails we use the die() command to stop the script, displaying the error returned to the user with the mysql_error() command. We then use the mysql_num_rows() command to find the number of records returned by the query, passing it the link to the database result returned by the mysql_query() command. We then use a for loop, which runs once for every record returned, using the mysql_fetch_assoc() to read in a record at a time, in the form of an array, passing the command the link to the database results. We place each record into an array called $recordset, ready to transform into XML in the next section of code. Finally, we close the link to the open database connection using the mysql_close() command.

Converting the Data to XML


Now that we have the data read from the database held in an array called $recordset, the next step is to convert the data to XML. Add the code below to the page, underneath the mysql_close() command: // Turn $recordset array into XML using DOM extension if($numRecords > 0){ $doc = new_xmldoc("1.0"); // Add a root node $root = $doc->add_root("categories"); // Add Select Category Header $child = $root->new_child("category","Select Category..."); // Create Child Elements foreach($recordset as $record){ $child = $root->new_child("category",$record['category']); } // Output XML Document echo $doc->dumpmem(); } First, we check that at least one record has been returned by the results of the database query, as there is no point in creating a new XML document if there is no data to add to it.
Copyright 2004 DMXzone.com All Rights Reserved To get more go to DMXzone.com

Page 6 of 10

Building an XML Flash Application with PHP and MySQL Pt.I


Gareth Downes-Powell

If there are records available, then we new use the new_xmldoc() command to create a link to a new XML document, passing it "1.0" indicating that we want the XML document in version one format (which is standard). Next, we need to add an XML root element to the document, named categories, using the add_root() command. Now that we have a root node, we can start adding child nodes. We can do this by using the new_child() command, passing it the element name and the text to go between the elements. First, we add a child node which will act as a header for the list using new_child("category","Select Category"). In the XML document, this will appear as "<category>Select Category</category>". We then need to add a child element for each record held in $recordset. To do this, we use a foreach() loop to loop through each record in $recordset. We use the new_child() command, passing it the name of the tag, "category", and the data to go between the tags, which is the category from the database. Finally, now that all the data has been added to the XML document, we use the dumpmem() command to output the XML document. Save the page as before we move on we'll test it.

Testing the Page


Upload the page to your web server, along with the dbConnection.php include file in the includes directory. Open the page in your browser, and you should see XML similar to the following: <?xml version="1.0" ?> <categories> <category>Select Category...</category> <category>Amphibians</category> <category>Insects</category> <category>Snakes</category> <category>Spiders</category> </categories> Here, you can see that we have a file with a categories root node, and then category child nodes underneath this, listing the categories from the database. Save this XML in a file called categories.xml, as we'll use this later when we create the Flash side of the application (you can save files directly from Internet Explorer and some other browsers, or alternatively you can copy and paste the XML into a text editor and save the file).

Creating the inventory.php page


The next page that we are going to create is to display the inventory data from the database. The page will be called with a URL parameter, in a form similar to the example shown below: http://www.site.com/inventory.php?category=insects When the page is called, it will query the database, and return all records that correspond to the category passed as the URL parameter.

Copyright 2004 DMXzone.com All Rights Reserved To get more go to DMXzone.com

Page 7 of 10

Building an XML Flash Application with PHP and MySQL Pt.I


Gareth Downes-Powell

Create a new PHP page, and delete all the code automatically added to the page by Dreamweaver MX so the page is completely blank. Save the page as inventory.php.

Reading from the Database


The first step in building this page, is to add the code to query the database. This will be similar to that on the category.php page. Switch to Code View and add the following code: <?php // Include Database Connection File require_once("C:/webserver/includes/dbConnection.php"); // Open Database Connection $dbLink = mysql_connect($dbHost, $dbUser, $dbPass); if (!$dbLink){ die ("Database: Couldn`t connect to mySQL Server"); } mysql_select_db($dbName, $dbLink) or die ("Database: Couldn`t open Database"); // Read URL Parameter - Category if (!get_magic_quotes_gpc()) { $varCategory = addslashes($_GET['category']); } else { $varCategory = $_GET['category']; } $varCategory = strip_tags($varCategory); // Create SQL Query $sql = "SELECT name,category,price,description,image FROM inventory WHERE category = '" . $varCategory . "' ORDER BY name ASC "; // Execute SQL Query and Read in Records $dbResult = mysql_query($sql, $dbLink) or die ("MySQL Error: " . mysql_error() ); $numRecords = mysql_num_rows($dbResult); $recordset = ""; for($i=0;$i<$numRecords;$i++){ $recordset[] = mysql_fetch_assoc($dbResult); } mysql_close($dbLink); ?> The first thing the code does is to include the dbConnection.php include file to make the database connection parameters available to the page. As before we open a connection to the MySQL server with the mysql_connnect command, putting the link to the open connection in $dbLink. If the connection fails, we use the die() command to stop the script. We then tell MySQL which database we want to work with using the mysql_select_db() command. Because, we want to use the category passed through the URL in the SQL statement, we need to ensure there are no invalid characters that could be used maliciously in the SQL. We do this by checking whether magic quotes is enabled, and if not we use addslashes() to "clean" the data and escape any characters that could cause problems. We then create the SQL statement, selecting only the records where the category in the inventory table matches the category sent through the URL. We then execute the query using the mysql_query() command, or stop the script if there is an error using the die() command. We then check the number of records returned
Copyright 2004 DMXzone.com All Rights Reserved To get more go to DMXzone.com

Page 8 of 10

Building an XML Flash Application with PHP and MySQL Pt.I


Gareth Downes-Powell

by the query using the mysql_num_rows() command, passing it the result returned from the mysql_query() command. Finally, we use a for loop to read in each returned record into a variable called $recordset using the mysql_fetch_assoc() command. The last step is to close the open database connection as we no longer require it using the mysql_close() command.

Converting the Data to XML


Now that we have the data retrieved from the database in a variable, we next need to convert the data to XML, ready to pass back to the Flash application. Add the following code to the page underneath the mysql_close() command. // Turn $recordset array into XML using DOM extension $doc = new_xmldoc("1.0"); // Add a root node $root = $doc->add_root("petdata"); if($numRecords > 0){ // Create Child Elements foreach($recordset as $record){ $child = $root->new_child("animal",""); $child->new_child("name",$record['name']); $child->new_child("category",$record['category']); $child->new_child("price",$record['price']); $child->new_child("description",$record['description']); $child->new_child("image",$record['image']); } } else { $child = $root->new_child("animal",""); $child->new_child("name","No Current Stock"); $child->new_child("category",""); $child->new_child("price",""); $child->new_child("description",""); $child->new_child("image",""); } // Output XML Document echo $doc->dumpmem(); First, we use the new_xmldoc() command to create a new XML document, again using the version 1.0 standard. Next, we add a root node called "petdata". We then check if any results have been returned from the database query. If some results have been returned, we loop through the records in $recordset using a foreach loop. For each new recordset, we add a new child element called "animal", and then add child elements to that containing the name, category, price, description and image fields, each as separate elements under the animal element. If there are no records returned from the database query, then we create a root node called animal and then add an empty record, with a name of "No Current Stock", which will display in the Flash application. Finally, we output the completed XML document using the dumpmem() command. Save the page before you test it.
Copyright 2004 DMXzone.com All Rights Reserved To get more go to DMXzone.com

Page 9 of 10

Building an XML Flash Application with PHP and MySQL Pt.I


Gareth Downes-Powell

Testing the Page


You can now test the page, by calling the URL in your browser, along with a URL parameter selecting a category e.g. http://www.websites.com/inventory.php?category=snakes or http://www.websites.com/inventory.php?category=amphibians You should see results similar to that shown below (for amphibians): <?xml version="1.0"?> <petdata> <animal> <name>American Green Tree Frog</name> <category>Amphibians</category> <price>39.99</price> <description>Easy to keep, changes colour from yellow to dark brown</description> <image>/images/americantreefrog.jpg</image> </animal> <animal> <name>Grey Tree Frog</name> <category>Amphibians</category> <price>45.00</price> <description>The chameleon of the frog world, can change to almost any natural colour</description> <image>/images/greytreefrog.jpg</image> </animal> <animal> <name>Poison Frog</name> <category>Amphibians</category> <price>74.99</price> <description>Dendrobates Azureus - Stunning unnatural blue frogs, need some experience to keep them successfully</description> <image>/images/azureus.jpg</image> </animal> </petdata> Here you can see we have a root element named "petdata", with each animal having its own child element named "animal". Under these we have more child elements representing the various data about each animal. Save this XML as inventory.xml as we will use this in our Flash application in the next article.

Summary
At this stage we have created a database and populated it with data about the animals on sale in the Jungle Pet Store. We have also created two pages, category.php, which retrieves the categories from the database and using the PHP DOM extension, transforms the data into an XML document, and inventory.php which pulls all records from the database corresponding to a certain category passed in the URL, and again returns this data as an XML document. In the next part of this tutorial we will build the Flash side of this tutorial, which takes the XML data generated by the PHP pages and displays it in real time to the user.
Copyright 2004 DMXzone.com All Rights Reserved To get more go to DMXzone.com

Page 10 of 10

Vous aimerez peut-être aussi