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>");
}
?>

No Comments

No comments yet.

RSS feed for comments on this post.

Sorry, the comment form is closed at this time.