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.
Related
Im gettin this error using as3 votingpoll.
I dont understand what is wrong, since i only know basic coding.
I really would need to get this working for a school project.
Hope any one can help me out !
Thanks alot
TypeError: Error #2007: Parameter text must be non-null.
at flash.text::TextField/set text()
at Onlinepoll_fla::WholePoll_1/completeHandler()
at flash.events::EventDispatcher/dispatchEventFunction()
at flash.events::EventDispatcher/dispatchEvent()
at flash.net::URLLoader/onComplete()
AS3 code request:
stop(); // Stop the timeline since it does not need to travel for this to run
// Assign a variable name for our URLVariables object
var variables1: URLVariables = new URLVariables();
// Build the varSend variable
var varSend1: URLRequest = new URLRequest("parse_my_poll.php");
varSend1.method = URLRequestMethod.POST;
varSend1.data = variables1;
// Build the varLoader variable
var varLoader1: URLLoader = new URLLoader;
varLoader1.dataFormat = URLLoaderDataFormat.VARIABLES;
varLoader1.addEventListener(Event.COMPLETE, completeHandler1);
// Set variable to send to PHP here for the varloader below
variables1.myRequest = "load_numbers";
// Send data to php file now, and wait for response using the COMPLETE event
varLoader1.load(varSend1);
function completeHandler1(event: Event): void {
count1_txt.text = "" + event.target.data.choice1Count;
count2_txt.text = "" + event.target.data.choice2Count;
count3_txt.text = "" + event.target.data.choice3Count;
}
**as3 Send code**
// hide the little processing movieclip
processing_mc.visible = false;
// Initialize the choiceNum variable that we will use below
var choiceNum:Number = 0;
// Set text formatting colors for errors and success messages
var errorsFormat:TextFormat = new TextFormat();
errorsFormat.color = 0xFF0000; // bright red
var successFormat:TextFormat = new TextFormat();
successFormat.color = 0x00FF00; // bright green
/////////////////////////////////////////////////////////////
// Button Click Functions
function btn1Click(event:MouseEvent):void{
choiceNum = 1;
choice_txt.text = choice1_txt.text;
}
function btn2Click(event:MouseEvent):void{
choiceNum = 2;
choice_txt.text = choice2_txt.text;
}
function btn3Click(event:MouseEvent):void{
choiceNum = 3;
choice_txt.text = choice3_txt.text;
}
// Button Click Listeners
btn1.addEventListener(MouseEvent.CLICK, btn1Click);
btn2.addEventListener(MouseEvent.CLICK, btn2Click);
btn3.addEventListener(MouseEvent.CLICK, btn3Click);
//////////////////////////////////////////////////////////////
// Assign a variable name for our URLVariables object
var variables:URLVariables = new URLVariables();
// Build the varSend variable
var varSend:URLRequest = new URLRequest("parse_my_poll.php");
varSend.method = URLRequestMethod.POST;
varSend.data = variables;
// Build the varLoader variable
var varLoader:URLLoader = new URLLoader;
varLoader.dataFormat = URLLoaderDataFormat.VARIABLES;
varLoader.addEventListener(Event.COMPLETE, completeHandler);
// Handler for PHP script completion and return
function completeHandler(event:Event):void{
// remove processing movieclip
processing_mc.visible = false;
// Clear the form fields
choice_txt.text = choice1_txt.text;
choiceNum = 0;
// Load the response from the PHP file
status_txt.text = event.target.data.return_msg;
status_txt.setTextFormat(errorsFormat);
if (event.target.data.return_msg == "Thanks for voting!") {
// Reload new values into the count texts only if we get a proper response and new values
status_txt.setTextFormat(successFormat);
count1_txt.text = "" + event.target.data.choice1Count;
count2_txt.text = "" + event.target.data.choice2Count;
count3_txt.text = "" + event.target.data.choice3Count;
}
}
// Add an event listener for the submit button and what function to run
vote_btn.addEventListener(MouseEvent.CLICK, ValidateAndSend);
// Validate form fields and send the variables when submit button is clicked
function ValidateAndSend(event:MouseEvent):void {
//validate form fields
if(!choice_txt.length) {
// if they forgot to choose before pressing the vote button
status_txt.text = "Please choose before you press vote.";
status_txt.setTextFormat(errorsFormat);
} else {
status_txt.text = "Sending...";
processing_mc.visible = true;
// Ready the variables for sending
variables.userChoice = choiceNum;
variables.myRequest = "store_choice";
// Send the data to the php file
varLoader.load(varSend);
} // close else after form validation
} // Close ValidateAndSend function ////////////////////////
PHP code:
<?php
/*
::::::::::Script Written By: Adam Khoury # www.developphp.com:::::::::::::
:::::::::If you find www.developphp.com tutorials helpful or handy:::::::::::::
:::::::::::please link to it wherever possible to help others find it::::::::::::::::
*/
// ---------------------------------------- Section 1 -----------------------------------------------
// IMPORTANT!!!! Connect to MySQL database here(put your connection data here)
mysql_connect("localhost","root","") or die (mysql_error());
mysql_select_db("data") or die (mysql_error());
// When Flash requests the totals initially we run this code
if ($_POST['myRequest'] == "load_numbers") {
// Query the totals from the database
$sql1 = mysql_query("SELECT id FROM votingPoll WHERE choice='1'");
$choice1Count = mysql_num_rows($sql1);
$sql2 = mysql_query("SELECT id FROM votingPoll WHERE choice='2'");
$choice2Count = mysql_num_rows($sql2);
$sql3 = mysql_query("SELECT id FROM votingPoll WHERE choice='3'");
$choice3Count = mysql_num_rows($sql3);
echo "choice1Count=$choice1Count";
echo "&choice2Count=$choice2Count";
echo "&choice3Count=$choice3Count";
}
// ---------------------------------------- Section 2 -----------------------------------------------
// IF POSTING A USER'S CHOICE
if ($_POST['myRequest'] == "store_choice") {
//Obtain user IP address
$ip = $_SERVER['REMOTE_ADDR'];
// Create local variable from the Flash ActionScript posted variable
$userChoice = $_POST['userChoice'];
$sql = mysql_query("SELECT id FROM votingPoll WHERE ipaddress='$ip'");
$rowCount = mysql_num_rows($sql);
if ($rowCount == 1) {
$my_msg = "You have already voted in this poll.";
print "return_msg=$my_msg";
} else {
$sql_insert = mysql_query("INSERT INTO votingPoll (choice, ipaddress) VALUES('$userChoice','$ip')") or die (mysql_error());
$sql1 = mysql_query("SELECT * FROM votingPoll WHERE choice='1'");
$choice1Count = mysql_num_rows($sql1);
$sql2 = mysql_query("SELECT * FROM votingPoll WHERE choice='2'");
$choice2Count = mysql_num_rows($sql2);
$sql3 = mysql_query("SELECT * FROM votingPoll WHERE choice='3'");
$choice3Count = mysql_num_rows($sql3);
$my_msg = "Thanks for voting!";
echo "return_msg=$my_msg";
echo "&choice1Count=$choice1Count";
echo "&choice2Count=$choice2Count";
echo "&choice3Count=$choice3Count";
}
}
?>
Apparently, your event.target.data.return_msg or event.target.data.choice1Count etc variables are empty (null).
First check if your PHP script is echoing a correct response ($my_msg or $choice1Count might be null there as well). If the PHP script is fine, try to trace these values in your completeHandler method:
trace("message : " + event.target.data.return_msg);
trace("choice1Count : " + event.target.data.choice1Count);
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...
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.";
}
I have a actionscript game that send data to a php with POST.
But I don't know how to make it working, first to get the data in php then to insert in database.
Here is the ActionScript, a part from game that send the post to php.
public function post()
{
var _loc_1:* = new ByteArray();
_loc_1.writeUnsignedInt(1);
_loc_1.writeUnsignedInt(this.Args.u);
_loc_1.writeUnsignedInt(this.Args.r);
_loc_1.writeUnsignedInt(this.Args.t);
_loc_1.writeUnsignedInt(this.Args.p);
_loc_1.writeUnsignedInt(this.apples);
_loc_1.writeUnsignedInt(this.calories);
_loc_1.writeUnsignedInt(this.StartTime);
var _loc_2:* = 0;
while (_loc_2 < this.moves.length)
{
_loc_1.writeShort(this.moves[_loc_2]);
_loc_2 = _loc_2 + 1;
}
var _loc_3:* = new URLRequestHeader("Content-type", "application/octet-stream");
var _loc_4:* = new URLRequest("http://mywebsite.com/Game.php");
_loc_4.requestHeaders.push(_loc_3);
_loc_4.method = URLRequestMethod.POST;
_loc_4.data = _loc_1;
var _loc_5:* = new URLLoader();
_loc_5.load(_loc_4);
_loc_5.addEventListener(Event.COMPLETE, this.PostCallback);
return;
}// end function
public function PostCallback(param1)
{
this.tf.text = "PHP:" + param1.currentTarget.data;
return;
}// end function
Somewhere is the this.post();(is used when game is finished and win)
This is the data what i want to get in php, is like a scores:
var _loc_1:* = new ByteArray();
_loc_1.writeUnsignedInt(1);
_loc_1.writeUnsignedInt(this.Args.u);
_loc_1.writeUnsignedInt(this.Args.r);
_loc_1.writeUnsignedInt(this.Args.t);
_loc_1.writeUnsignedInt(this.Args.p);
_loc_1.writeUnsignedInt(this.apples);
_loc_1.writeUnsignedInt(this.calories);
_loc_1.writeUnsignedInt(this.StartTime);
Page Game.php
<?php
$dbhost = 'localhost';
$dbname = 'dbname';
$dbuser = 'root';
$dbbg = 'pass';
mysql_connect($dbhost, $dbuser, $dbbg)or error("Could not connect: ".mysql_error());
mysql_select_db($dbname) or error(mysql_error());
if(isset($HTTP_RAW_POST_DATA))
{
mysql_query("INSERT INTO game (gameinfo) VALUES ('".$HTTP_RAW_POST_DATA."');");
}
?>
It insert me in database a text like with nonsense characters.. 'YPDèU"ˆ†U"~µIk€†œ«¹ãV„–' I am appreciate any hand of help.
i'm still novice in AS3 Programming i was trying to get a login screen to work on my AIR Application, but i got error #2101 The String passed to URLVariables.decode() must be a URL-encoded query string containing name/value pairs.
here's the code for processLogin
public function processLogin():void {
if(username.text != "" && password.text != "")
{
var checkName = username.text
var checkPass = password.text
var resulttext = result_text.text
var request:URLRequest = new URLRequest("http://localhost/caservers/aksessistemlogin.php")
var loader:URLLoader = new URLLoader()
var variables:URLVariables = new URLVariables()
variables.username = checkName
variables.password = checkPass
variables.systemResult = resulttext
loader.dataFormat = URLLoaderDataFormat.VARIABLES
request.data = variables
request.method = URLRequestMethod.POST
loader.addEventListener(Event.COMPLETE, logincheck)
loader.load(request)
}
function logincheck (event:Event):void {
if (username.text == checkName && password.text == checkPass){
gotoAndPlay(2);
}else{
result_text.text = resulttext ;
}
}
}
and this one is the code for PHP
<?php
include_once "connect.php";
$username = $_POST['username'];
$password = $_POST['password'];
if ($_POST['systemCall'] == "checkLogin") {
$sql = "SELECT * FROM users WHERE username='$username' AND password='$password'";
$query = mysqli_query($sql);
$login_counter = mysqli_num_rows($query);
if ($login_counter > 0) {
while ($data = mysqli_fetch_array($query)) {
}
} else {
$systemResult = "The login details don't match our records";
}
}
?>
what i'm intend to do is to check if the username and password is match with the one in the database, i followed some tutorials but it ended up advancing to next frame even without typing anything in the text input (just by clicking submit).
any help will be very very appreciated! thanks in advance..
When you have this line in AS3:
loader.dataFormat = URLLoaderDataFormat.VARIABLES;
You are telling flash to decode the response from the loader as URL encoded variables. Your response however must not be that, because you get an error when it tries to decode the output of your PHP page as URL variables.
Flash will automatically know that you are sending URL encoded data when you assign a URLVariables object to the data property.