Thursday, March 11, 2010

Flash ActionScript3 MySql Querys

One way how to send sql querys in flash is using some kind of server side scripts that receive an URLRequest from flash and send it to sql server.

Here is one way how to do it.

write a php script that takes sql query from request url as a $_GET or $_POST parameter and sends it to sql server. If sql database,username,password are defined in the php file, flash doesnt need to send anything else but a query string e.g "select * from users"

if u want to select database and authenticate yourself within flash, u need to get those variables from GET or POST aswell.

here is my example php script.
-------------------------------
//put php starting tag here,< ? php
//$_GET['default'] we use this parameter to toggle between sql settings defined in php and possible settings sent from actionscript



if( $_GET['default'] == "true")
{
$mysql_host = "mysql12.000webhost.com";
$mysql_database = "a8621303_drupal";
$mysql_user = "a8621303_a862130";
$mysql_password = "852456x";
$con_users = mysql_connect($mysql_host,$mysql_user,$mysql_password);
}
else
{

$mysql_host = $_GET['host'];
$mysql_database = $_GET['database'];
$mysql_user = $_GET['user'];
$mysql_password = $_GET['pass'];
$con_users = mysql_connect($mysql_host,$mysql_user,$mysql_password);
}
mysql_select_db($mysql_database, $con_users);

$query = $_GET['query'];
/* 
NOTE: you shouldnt send queries like this to db without sanitizing/escaping input first 
*/
$result = mysql_query($query);
while($row = mysql_fetch_array( $result ))
{
print_r($row);
}
?>


--------------------------------------
and here is actionscript part that sends the url requests to php script
--------------------------------------
//some global variables
var sqlLoader:URLLoader = new URLLoader();
var sqlRelay :String = "http://sebstorage.comlu.com/FlashToSql.php";//path to php script
var sqlQuery :String = "SELECT * FROM workers";//example query

sqlLoader.addEventListener(Event.COMPLETE,sqlLoaded);//to know when sql data came back
function sqlLoaded(event:Event):void
{
trace(sqlLoader.data);
}
function SendDefaultSqlQuery(query:String):void
{
var urlRequest:URLRequest = new URLRequest(sqlRelay+"? query="+query+"&default=true")
sqlLoader.load(urlRequest);
}
the above function sends GET parameter default, which means that php will use the settings defined in php file.


function SendSqlQuery(query:String,database:String,pass:String,user:String,host:String):void
{
var urlRequest:URLRequest = new URLRequest(sqlRelay+"?host="+host+"&user="+user+"&pass="+pass+"&database="+database+"&query="+query);
sqlLoader.load(urlRequest);
}
this function sends information for sql connection and the query string