Deprecated: Function ereg() is deprecated in /home3/vvaswani/db-mysql.php on line 174

Deprecated: Function split() is deprecated in /home3/vvaswani/public_html/community/columns/trog/article.php on line 101

Deprecated: Function eregi_replace() is deprecated in /home3/vvaswani/sql.php on line 301

Deprecated: preg_replace(): The /e modifier is deprecated, use preg_replace_callback instead in /home3/vvaswani/public_html/community/columns/trog/article.php on line 107

Deprecated: preg_replace(): The /e modifier is deprecated, use preg_replace_callback instead in /home3/vvaswani/public_html/community/columns/trog/article.php on line 109

Deprecated: Function ereg_replace() is deprecated in /home3/vvaswani/public_html/community/columns/trog/article.php on line 124

Deprecated: Function ereg_replace() is deprecated in /home3/vvaswani/public_html/community/columns/trog/article.php on line 125

Deprecated: Function split() is deprecated in /home3/vvaswani/public_html/community/columns/trog/article.php on line 127

Deprecated: Function ereg() is deprecated in /home3/vvaswani/db-mysql.php on line 174

Deprecated: Function ereg() is deprecated in /home3/vvaswani/db-mysql.php on line 174

Deprecated: Function ereg() is deprecated in /home3/vvaswani/db-mysql.php on line 174

Deprecated: Function ereg() is deprecated in /home3/vvaswani/db-mysql.php on line 174

Deprecated: Function ereg() is deprecated in /home3/vvaswani/db-mysql.php on line 174

Deprecated: Function ereg() is deprecated in /home3/vvaswani/db-mysql.php on line 174

Deprecated: Function ereg() is deprecated in /home3/vvaswani/db-mysql.php on line 174

Deprecated: Function ereg() is deprecated in /home3/vvaswani/db-mysql.php on line 174

Deprecated: Function ereg() is deprecated in /home3/vvaswani/db-mysql.php on line 174

Deprecated: Function ereg() is deprecated in /home3/vvaswani/db-mysql.php on line 174
The Melonfire Community - Trog
Logo         Community
  Trog
Services
The Company
Community
Columns
Your Account
Contact Us
 
 
XForms Basics (part 2)
Find out how to submit XForms data to a server-side script or save it to a local client file.

| Data Overload |

The previous example showed you how to store the information provided by the user in a local file on the client. Though this seems interesting at first glance, it isn't very useful in real life (when was the last time you wanted to do this?) Most often, you would want the data to be sent to the server, safe and secure in a database or other storage engine. How does XForms stand up to this challenge? Pretty well, actually - and it even adds some interesting attributes to control the data being submitted.

In order to demonstrate, I'll revise the previous example to submit the user data to a server-side script, which takes care of adding it to a MySQL database. In this example, the database is called "db1", the table is called "immigrants", and the SQL code to create the table looks like this:


CREATE TABLE `immigrants` (
  `id` int(11) NOT NULL auto_increment,
  `name` varchar(30) NOT NULL default '',
  `citizenship` varchar(50) NOT NULL default '',
  `purpose` char(1) NOT NULL default '',
  `immunization` varchar(50) NOT NULL default '',
  `address` varchar(255) NOT NULL default '',
   PRIMARY KEY  (`id`)
)


As you can see, this is pretty straightforward stuff, with each field of the table mapping to a node in the XML file created in the previous example.

Next up, altering the XForm model to point to a server-side PHP script instead of a local file:


<!-- form model -->
<xforms:model id="immigration">
   <xforms:instance src="immigration.xml" />
   <xforms:submission id="submit" action="/scripts/register.php" method="post" />
</xforms:model>


Notice that no change is needed to the form input controls, or any other section of the XForm - this is an example of the separation between form and function that XForms promises.

Finally, here's the PHP script that takes the submitted form data and converts it into an INSERT query:


<?php

// initialize some variables;
$currentTag = "";
$values = array();
$allowedFields = array("name", "citizenship", "purpose", "immunization", "address");

// database parameters
$host = "localhost";
$usr = "john";
$pwd = "doe";
$db = "db1";

// handlers
function startElementHandler($parser, $name, $attributes)
{
   global $currentTag;
   $currentTag = $name;
}

function endElementHandler($parser, $name)
{
   global $values, $currentTag;  
   global $connection, $table;
  
   if(strtolower($name) == "immigrant")
   {
      // generate SQL
      $query = "INSERT INTO immigrants";
      $query .= "(name, citizenship, purpose, immunization, address)";
      $query .= "VALUES(\"" . join("\",\"",$values) . "\");";
           
      // uncomment for debug purposes
      // print $query;                 
     
      // execute query
      $result = mysql_query($query) or die("Error in query: $query. " . mysql_error());
     
      // reset variables
      $values = array();
      $currentTag = "";
   }
}

function characterDataHandler($parser, $data)
{
   global $currentTag, $values, $allowedFields;
  
   $currentTag = strtolower($currentTag);
  
   if(in_array($currentTag, $allowedFields) && trim($data) != "")
   {
      $values[$currentTag] = mysql_escape_string($data);
   }
  
}

$parser = xml_parser_create();

// get the XML data
$data = $HTTP_RAW_POST_DATA;

// set SAX parser options
xml_parser_set_option($parser,XML_OPTION_CASE_FOLDING,0);
xml_parser_set_option($parser,XML_OPTION_SKIP_WHITE,1);

// set element handlers
xml_set_element_handler($parser, "startElementHandler", "endElementHandler");
xml_set_character_data_handler($parser, "characterDataHandler");

// connect to database
$conn = mysql_connect($host, $usr, $pwd) or die("Unable to connect to the database");
mysql_select_db($db) or die("Unable to select database");

// parse XML
if (!xml_parse($parser, $data ))
{
    die(sprintf("XML error: %s at line %d",
    xml_error_string(xml_get_error_code($parser)),
    xml_get_current_line_number($parser)));
}

// clean up
xml_parser_free($parser);
mysql_close();

?>


Now try it out and see for yourself - enter some data into the form, submit it and then check the database to see if your values were inserted correctly. Here's what you might see:


mysql> SELECT * FROM immigrants;
+----+-----------+-------------+---------+--------------+-----------------+
| id | name      | citizenship | purpose | immunization | address         |
+----+-----------+-------------+---------+--------------+-----------------+
|  1 | Chewbacca | Tatooine    | B       | 56 113       | Planet Tatooine |
+----+-----------+-------------+---------+--------------+-----------------+
1 row in set (0.00 sec)


How did this happen? Well, unlike traditional forms, which submit data using name-value pairs, XForms submits data as a well-formed XML document. This document can then be parsed using either a DOM or SAX parser, or even transferred directly to any other application that understands XML.

PHP comes with a built-in SAX parser, which is what I've used in the example above to parse the XML document. SAX, or the Simple API for XML, is one of the most common methods of parsing an XML document. Essentially, a SAX parser reads the XML document sequentially, triggering specific user-defined functions when it finds an opening tag, character data, closing tag, CDATA block and so on. In the example above, these user-defined functions are called startElementHandler(), endElementHandler() and characterDataHandler().


$parser = xml_parser_create();
xml_set_element_handler($parser, "startElementHandler", "endElementHandler");
xml_set_character_data_handler($parser, "characterDataHandler");


Of these, the major work in the script above is done by the characterDataHandler() function - this reads the various values entered by the user from the XML document tree and builds the SQL query after using the mysql_escape_string() function to make the values ready for insertion in the database.


function characterDataHandler($parser, $data)
{
   global $currentTag, $values, $allowedFields;
  
   $currentTag = strtolower($currentTag);
  
   if(in_array($currentTag, $allowedFields) && trim($data) != "")
   {
      $values[$currentTag] = mysql_escape_string($data);
   }
  
}


The script above won't make much sense to you unless you've played a little with SAX. In case you haven't, drop by http://www.melonfire.com/community/columns/trog/article.php?id=71 and find out what you missed, then come back here and review the script again. You can also read more about SAX at http://www.saxproject.org/ and http://www.xmlphp.com/

You can also parse the XML document submitted by the XForm using the DOM - I leave that to you as an exercise.


How to do Everything with PHP & MySQL
How to do Everything with PHP & MySQL, the best-selling book by Melonfire, explains how to take full advantage of PHP's built-in support for MySQL and link the results of database queries to Web pages. You'll get full details on PHP programming and MySQL database development, and then you'll learn to use these two cutting-edge technologies together. Easy-to-follow sample applications include a PHP online shopping cart, a MySQL order tracking system, and a PHP/MySQL news publishing system.

Read more, or grab your copy now!


previous page more like this  print this article  next page
 
Search...
 
In trog...
Logging With PHP
Building A Quick-And-Dirty PHP/MySQL Publishing System
Output Buffering With PHP
Date/Time Processing With PHP
Creating Web Calendars With The PEAR Calendar Class
more...
 
In the hitg report...
Crime Scenes
Animal Attraction
Lord Of The Strings
more...
 
In boombox...
Patience - George Michael
Think Tank - Blur
My Private Nation - Train
more...
 
In colophon...
Hostage - Robert Crais
The Dead Heart - Douglas Kennedy
Right As Rain - George Pelecanos
more...
 
In cut!...
American Chai
The Core
Possession
more...
 
Find out how you can use this article on your own Web site!


Copyright © 1998-
Strict Standards: mktime(): You should be using the time() function instead in /home3/vvaswani/public_html/community/columns/trog/article.php on line 731
2018 Melonfire. All rights reserved
Terms and Conditions | Feedback