connect as3 to mysql not work - php

I tried to link my actionscript3 application to the database ... Here are my codes.
MY AS3 CODE:
import flash.events.*;
import flash.net.URLLoader;
import flash.net.URLRequest;
import flash.net.URLVariables;
import flash.net.URLRequestMethod;
const SENT_SUCCESS:String = "Successful";
const SENT_FAILED:String = "Unsuccessful";
var tmr:Timer;
function resetTextFields():void {
username.text = String("username");
password.text = String("password");
}
function afterTmrWait(evt:TimerEvent):void {
tmr.stop();
tmr.removeEventListener(TimerEvent.TIMER, afterTmrWait);
}
function submitForm(evt:MouseEvent):void {
var passChecks:Boolean = true;
if(username.text == String("")) {
passChecks = false;<br>
}
if(password.text == String("")) <br>{<br>
passChecks = false;
}
if(passChecks) {
var urlVars:URLVariables = new URLVariables();
var urlReq:URLRequest = new URLRequest("php/login.php");
var ldr:URLLoader = new URLLoader();
urlVars.username = username.text;
urlVars.password = password.text;
urlReq.data = urlVars;
urlReq.method = URLRequestMethod.POST;
ldr.addEventListener(Event.COMPLETE, serverFeedback);
ldr.load(urlReq);
ldr.dataFormat = URLLoaderDataFormat.VARIABLES;
}
}
function serverFeedback(evt:Event):void {
var ldr:URLLoader = evt.target as URLLoader;
var urlVars:URLVariables = new URLVariables(ldr.data);
if(urlVars.result == SENT_SUCCESS) {
login_result.gotoAndStop(2);
resetTextFields();
} else if(urlVars.result == SENT_FAILED) {
login_result.gotoAndStop(3);
}
tmr = new Timer(3000, 1);
tmr.addEventListener(TimerEvent.TIMER, afterTmrWait);
tmr.start();
}
login_btn.addEventListener(MouseEvent.CLICK, submitForm);
resetTextFields();
MY PHP CODE:
<?php
$username = $_POST['username'];
$password = $_POST['password'];
if(exist($_POST['username']) && exist($_POST['password'])) {
$mysql = mysql_connect("host", "username", "password", "database");
$password = md5(stripslashes($mysql->real_escape_string($password)));
$outcome = $mysql->query("SELECT * FROM user WHERE username='{$username}' AND password='{$password}' LIMIT 1");
if(!$outcome->null_rows) {
echo( "result=Unsuccessful" );
} else {
echo( "result=Successful" );
}
}
?>
AND I GET THIS ERROR IN FLASH:
Error: Error #2101: The String passed to URLVariables.decode() must be a URL-encoded query string containing name/value pairs.
at Error$/throwError()
at flash.net::URLVariables/decode()
at flash.net::URLVariables()
at flash.net::URLLoader/onComplete()
PLEASE HELP ME, WHAT I DO WRONG?

The URLLoader dataFormat by default is text. You need to add
ldr.dataFormat=URLLoaderDataFormat.VARIABLES;
so it does throw an error when you try
var urlVars:URLVariables = new URLVariables(ldr.data);

set dataFormat before load request..
your code
ldr.load(urlReq);
ldr.dataFormat = URLLoaderDataFormat.VARIABLES;
try this....
ldr.dataFormat = URLLoaderDataFormat.VARIABLES;
ldr.load(urlReq);

Related

Update Database with Adobe Flash

I have trouble to edit data in my database (MySQL).
I try to edit data with Flash (.swf)
Here is the flow of my program
Data -> Edit data with flash -> Data updated
My PHP script
<?php
mysql_pconnect ("localhost", "root", "");
mysql_select_db ("adaptasi");
$qResult = mysql_query ('UPDATE materi
SET isi = "????"
WHERE id = 1');
$rString ="";
echo "edit=".$rString;
?>
and my Actionscript for flash
var result:LoadVars = new LoadVars();
var edit:LoadVars = new LoadVars();
var filepath:String;
result.onLoad = function(success:Boolean) {
if (success) {
text_morfologi.text = result.result;
trace("success");
} else {
trace('error...');
}
};
filepath = "http://localhost/adaptasi/";
result.sendAndLoad(filepath + "morfologi.php", result, "GET");
btnedit.setStyle("fontSize", 22);
btnsave.setStyle("fontSize", 22);
btnedit.visible = true;
btnedit.onRelease = function() {
text_morfologi.type = "input";
btnedit.visible = false;
btnsave.visible = true;
}
btnsave.onRelease = function() {
edit.onLoad = function(success:Boolean){
if (success) {
text_morfologi.text = edit.edit;
trace("success");
} else {
trace('error...');
}
};
filepath = "http://localhost/adaptasi/";
edit.sendAndLoad(filepath + "editmorfologi.php", edit, "GET");
btnedit.visible = true;
btnsave.visible = false;
output.text = "data berhasil diubah...";
}
I can execute that script from flash. But I don't know what should I insert into SET in SQL Update...

Flash AS2 Store score in mysql database

i need to store variable score in database here's my code:
AS2 code:
on(press)
{ var score = scorer.score
var myDataResponse:LoadVars = new LoadVars();
var myData:LoadVars = new LoadVars();
score.sendAndLoad("score.php", myDataResponse, "POST");
myDataResponse.onLoad = function() {
if (this.result == "OK") {
result= "Score Sent.";
} else {
result= this.result;
}
}
}
PHP code:
<?php
$score = $_POST['score'];
$con = mysql_connect("localhost","root","");
mysql_select_db("test",$con);
$q = ("INSERT INTO score(count) VALUES ('$score')");
mysql_query($q) or die ("error");
?>
i run .swf in localhost but didnt save the score
Change the AS3 code for onPress Method:
var loader : URLLoader = new URLLoader();
var request : URLRequest = new URLRequest("/score.php");
request.method = URLRequestMethod.POST;
var variables : URLVariables = new URLVariables();
variables.score = score;
request.data = variables;
// Handlers
loader.addEventListener(Event.COMPLETE, on_complete);
loader.load(request);
private function on_complete(e : Event):void{
result= "Score Sent.";
}

retieve data from database using as3

I had created a database "new" using xampp localhost database had 2 tables user and score. I had an AS3 code which had 2 input textfield to insert user and score value into database tables.
Now I am trying to retrieve the inserted scores from database using user name. I have taken another text field to take user name and a button when I write "sarah" and click button it will return the score of sarah which is already inserted in database. But code is showing an error. I tried a lot but can not fix it.please help.here is my code
AS3 code:
btn2.addEventListener(MouseEvent.MOUSE_DOWN, fetchscore);
function fetchscore(event:MouseEvent)
{
var phpVars:URLVariables = new URLVariables();
var phpFileRequest:URLRequest = new URLRequest('http://localhost/collectscore.php');
phpFileRequest.method = URLRequestMethod.POST;
var phpLoader:URLLoader = new URLLoader();
phpLoader.dataFormat = URLLoaderDataFormat.VARIABLES;
phpLoader.addEventListener(Event.COMPLETE, showResult);
phpVars.systemCall = "processLogin";
phpVars.cname = Name.text;
phpLoader.load(phpFileRequest);
}
function showResult(e:Event)
{
//trace(phpVars.result);
result_text.text = "" + e.target.data.systemResult;
}
fetchscore.php
<?php
include('connect.php');
$username = $_POST['cname'];
if ($_POST['systemCall'] == "processLogin"){
$sqlqry = "SELECT * FROM scoreu WHERE username='$username'";//scoreu is my DBtable with two field user and score
$query = mysqli_query($sqlqry);
$login_counter = mysqli_num_rows($query);
if ($login_counter > 0) {
while ($data = mysqli_fetch_array($query)) {
if (mysqli_query($link), "SELECT score FROM scoreu WHERE user='$username'")) {
$findscore = $data['score'];
print 'result=$findscore';
}
}
} else {
print 'result=The login details dont match names.';
}
}
?>
connect.php
<?php
// connect.php
$db_name = 'new';
$db_username = 'root';
$db_password = '';
$db_host = 'localhost';
$link = mysqli_connect($db_host, $db_username, $db_password, $db_name);
if (mysqli_connect_errno()) {
die('Failed to connect to the server : '.mysqli_connect_error());
}
?>
You have some "problems" in your code, lets start by the PHP code.
PHP code :
<?php
// collectscore.php
include('connect.php');
$username = $_POST['cname'];
if ($_POST['systemCall'] == "processLogin"){
// you need only one request to get the score
$query = mysqli_query($link, "SELECT score FROM scoreu WHERE user = '$username'");
// you have to fetch the result into a php var
if ($data = mysqli_fetch_assoc($query)) {
$findscore = $data['score'];
// you should use double quotes when passing vars into a string
// otherwise, if you want use single quotes, you can write it : print 'result='.$findscore;
print "result=$findscore";
} else {
print 'result=The login details dont match names.';
}
}
?>
ActionScript code :
function fetchscore(event:MouseEvent): void
{
var phpVars:URLVariables = new URLVariables();
phpVars.systemCall = "processLogin";
phpVars.cname = cname.text; // name text field
var phpFileRequest:URLRequest = new URLRequest('http://127.0.0.1/collectscore.php');
phpFileRequest.method = URLRequestMethod.POST;
// you forgot to send your POST vars, for that, we use URLRequest.data
phpFileRequest.data = phpVars;
var phpLoader:URLLoader = new URLLoader();
phpLoader.dataFormat = URLLoaderDataFormat.VARIABLES;
phpLoader.addEventListener(Event.COMPLETE, showResult);
phpLoader.load(phpFileRequest);
}
function showResult(e:Event):void
{
// here the var should be the same as in the PHP script, result in this case : print "result=$findscore";
trace(e.target.data.result);
}
Hope that can help.

Flash retrieve JSON result from MYSQL

My app makes a call from Flash to get back list of countries but in my PHP the result is returning empty, i have created the table using phpMyAdmin and i have two rows in there.
Here is the code Action script 3:
package {
import flash.net.URLRequest;
import flash.net.URLVariables;
import flash.events.Event;
import flash.net.URLLoader;
import flash.net.URLLoaderDataFormat;
import flash.events.EventDispatcher;
public class SQL extends EventDispatcher{
var url:String = "";
var urlRequest:URLRequest;
public function SQL() {
// constructor code
}
public function Post(url:String, urlVaribles:URLVariables = null):void{
this.url = url;
this.urlRequest = this.urlRequestObj();
var loader:URLLoader = new URLLoader();
if(urlVaribles){
this.urlRequest.data = urlVaribles;
loader.dataFormat = URLLoaderDataFormat.VARIABLES;
}
loader.addEventListener(Event.COMPLETE, dataPostOnLoad);
loader.load(this.urlRequest);
}
public function Get(url:String, urlVaribles:URLVariables = null):void{
this.url = url;
this.urlRequest = this.urlRequestObj();
var loader:URLLoader = new URLLoader();
if(urlVaribles){
this.urlRequest.data = urlVaribles;
loader.dataFormat = URLLoaderDataFormat.VARIABLES;
}
loader.addEventListener(Event.COMPLETE, dataGetOnLoad);
loader.load(this.urlRequest);
}
private function urlRequestObj():URLRequest{
return new URLRequest(this.url);
}
private function dataPostOnLoad(evt:Event):void{
var evt2:SQLEvent=new SQLEvent(SQLEvent.POST_COMPLETE, evt.target.data);
dispatchEvent(evt2);
}
private function dataGetOnLoad(evt:Event):void{
trace("IN GET " + evt.target.data);
var evt2:SQLEvent=new SQLEvent(SQLEvent.GET_COMPLETE, evt.target.data);
dispatchEvent(evt2);
}
}
}
Code for the call from Flash:
import fl.motion.MotionEvent;
var sql:SQL = new SQL();
sql.addEventListener(SQLEvent.GET_COMPLETE, dataGetResponse);
sql.Get("http://localhost:8888/MAMP/HUGT/getCountriesDP.php");
mc_ddScroll.visible = false;
mc_ddScrollButton.addEventListener(MouseEvent.CLICK, clickScrollButton);
function dataGetResponse(e:SQLEvent):void {
trace("Countries " + e.params);
}
function clickScrollButton(e:MouseEvent):void{
if(mc_ddScroll.visible){
mc_ddScroll.visible = false;
}
else{
mc_ddScroll.visible = true;
}
}
And finally the PHP script:
getCountriesDP.php
<?php
include "connect.php";
$result = mysql_query($conn,"SELECT * FROM C_Countries");
if(mysql_num_rows($result)){
echo '{"countries":[';
$first = true;
$row=mysql_fetch_assoc($result);
while($row=mysql_fetch_row($result)){
// cast results to specific data types
if($first) {
$first = false;
} else {
echo ',';
}
echo json_encode($row);
}
echo ']}';
} else {
echo "[]";
}
mysqli_close($conn);
?>
Connect.php
<?php
$conn = mysql_connect("localhost","root","root");
mysql_select_db("HUGT", $conn);
// disable reporting errors for security reason
error_reporting(0);
// Error checking
if(!$conn) {
die('Could not connect ' . mysql_error());
}
?>
I just changed my php script to this:
<?php
$conn = mysqli_connect("localhost","root","root", "HUGT");
//mysql_select_db("HUGT", $conn);
// disable reporting errors for security reason
error_reporting(0);
// Error checking
if(mysqli_connect_errno()) {
die('Could not connect ' . mysqli_connect_error());
}
?>
and:
<?php
include "connect.php";
$result = mysqli_query($conn,"SELECT * FROM C_Countries");
$rows = array();
while($r = mysqli_fetch_assoc($result)) {
$rows[] = $r;
}
echo json_encode($rows);
mysqli_close($conn);
?>

What is wrong with this AS3 code to communicate with a PHP file?

I am trying to create a user log-in system in Flash but I need to communicate to MySQL through PHP in order to do so. I looked around at a few tutorials, but I have been getting errors.
Here is the interface I have made in flash, which I am trying to communicate with controlpanel.php
http://i.imgur.com/JrTWm.png?1
Here is the code
AS file
package actions
{
import flash.display.MovieClip;
import flash.events.MouseEvent;
import flash.net.URLRequest;
import flash.net.URLVariables;
import flash.net.URLLoader;
import flash.events.Event;
import flash.net.URLLoaderDataFormat;
import flash.net.URLRequestMethod;
import flash.text.TextFieldAutoSize;
public class main extends MovieClip
{
public function main():void
{
submit_button.buttonMode = true;
submit_button.addEventListener(MouseEvent.MOUSE_DOWN, checkLogin)
username.text = "";
password.text = "";
}
public function checkLogin(e:MouseEvent):void
{
if(username.text==""||password.text=="")
{
if (username.text == "")
{
username.text = "Enter your username";
}
if (password.text == "")
{
password.text="Enter your password";
}
}
else
{
processLogin();
}
}
public function processLogin():void
{
var phpVars:URLVariables = new URLVariables();
var phpFileRequest:URLRequest = new URLRequest("http://mathlympics.cu.cc/php/controlpanel.php");
phpFileRequest.method = URLRequestMethod.POST;
phpFileRequest.data = phpVars;
var phpLoader:URLLoader=new URLLoader();
phpLoader.dataFormat = URLLoaderDataFormat.VARIABLES;
phpVars.systemCall = "checkLogin";
phpVars.username = username.text;
phpVars.password = password.text;
phpLoader.load(phpFileRequest);
phpLoader.addEventListener(Event.COMPLETE, showResult);
}
public function showResult(event:Event):void
{
result_text.autoSize = TextFieldAutoSize.LEFT;
result_text.text = ""+ event.target.data.systemResult;
}
}
}
PHP file - connect.php
<?php
$db_username = "censored";
$db_name = "censored";
$db_password = "censored";
$db_host = "mysql2.000webhost.com";
mysql_connect($db_host,$db_username, $db_password, $db_name);
mysql_select_db($db_name) or die (mysql_error());
?>
PHP file - controlpanel.php
<?php
error_reporting(E_ALL);
include_once("connect.php");
$username = "admin";
$password = "password";
$sql = "SELECT * FROM user WHERE username='$username' AND password='$password'";
$query = mysql_query($sql);
$login_counter = mysql_num_rows($query);
if ($login_counter > 0)
{
$data = mysql_fetch_array($query);
$userbio = $data["user_bio"];
echo "systemResult=" . $userbio;
}
else
{
echo "systemResult=Invalid";
}
?>
I do not get any error but when I press the submit button, is says undefined in the result text box, even when I type the right username and password.
<!-- Hosting24 Analytics Code -->
<script type="text/javascript" src="http://stats.hosting24.com/count.php"></script>
<!-- End Of Analytics Code -->
To those of you interested: Here is my website enter link description here
So the problem ended up being you had SELECT * FROM user... when it should have been SELECT * FROM users... =)

Categories