August 23, 2009   Posted by: Anthony G. Cyphers

PHP: SQL2XML

This bit of code will connect to a MySQL database, run the passed query, and return the results as XML. I wrote this for use with FLEX, and it works quite well.

<?php

// Database configuration.
define("db_host", "localhost");
define("db_user", "some_user");
define("db_pass", "mypass");
define("db_name", "mydb");

// Authenticate calling application
define("auth_user", "someUserName");
define("auth_pass", "someUniquePhrase");

//Set our header…
header("Content-type: text/xml");
// and send our first line…
?>
<?xml version=’1.0′?>
<?php

// Kick things off…
user_authenticate();

function db_connect ()
{
mysql_connect(db_host,db_user,db_pass);
mysql_select_db(db_name);
}

function print_error($error)
{
// We print the error as XML so that the FLEX app can handle these problems.
echo("<flexsqlresult>");
echo("<error>" . $error . "</error>");
echo("</flexsqlresult>");
}

function user_authenticate ()
{
// Make sure they send user and pass data that matches our globals defined above.
if(isset($_REQUEST['authuser']) && isset($_REQUEST['authpass']))
{
if(($_REQUEST['authuser'] == auth_user) && ($_REQUEST['authpass'] == auth_pass))
{
if(isset($_REQUEST['qry']))
{
// Everything checks out, let’s run the query.
run_Query(trim(urldecode($_REQUEST['qry'])));
} else {
// The query was empty, error.
print_error("Bad query");
}
} else {
// Their user/pass info didn’t match, error.
print_error("Authentication invalid");
}
} else {
// No user/pass info, error.
print_error("No authentication specified.");
}
}

function run_Query ($query)
{
// Connect to our database…
db_connect();
// Run our query…
$resultID = mysql_query($query) or print_error("SQL Error: " . mysql_errno($resultID) . " – " . mysql_error($resultID));
// Start XML output…
echo("<flexsqlresult>");
$rowcount = 0;
while ($row = mysql_fetch_array($resultID))
{
echo("<datarow" . $rowcount . ">");
foreach($row as $key=>$value)
{
// Make sure the column name isn’t numeric, otherwise the XML will be invalid.
if(is_integer($key) != true)
{
/// Spit out our Name/Value row.
echo("<" . $key . ">" . $value . "</" . $key . ">");
}
}
echo("</datarow" . $rowcount . ">");
$rowcount++;
}
echo("</flexsqlresult>");
}
?>

Comments Off posted in: Programming
There are not tags associated with this post.
About the author

Anthony G. Cyphers - The sole proprietor of CyphersTECH Consulting. With a history in development dating back to DOS, he knows his stuff. He began programming in QuickBasic, and moved up through Visual Basic classic until the .NET platform was released. After spending some time working in .NET, he discovered what was then called "REALbasic", and has been developing for that platform ever since. Languages: ActionScript, JavaScript, PHP, VB, REALbasic, VB.NET, PERL