I've got a SQL table with 100 lines. Each line got a date.
I'd like to retrieve the info for a particular date.
Example :
With Flash, the user select the date 12/11/2014 and the AS3 code will display all the values (each columns of my table) that match this date.
In this example it will display "firstname : As de trefle, tome 1 : 10...etc" as it's the only entry that matches this date.
So far I've managed to select variables, in AS3, from users name, like that :
memberCombo.prompt = "Please select a user";
memberCombo.addItem( {label: "as de trefle" } );
memberCombo.addItem( {label: "kathy" } );
memberCombo.addItem( {label: "peter" } );
memberCombo.addEventListener(Event.CHANGE, checkComplete);
function checkComplete(evt:Event):void {
// Create A new URLVariables instance to store the variable
var myVariables:URLVariables = new URLVariables();
// Create a variable (e.g. candidate) to send
myVariables.username = evt.target.value;
// Create a new URLRequest instance sending data to "ascom01.php"
var myRequest:URLRequest = new URLRequest("http://www.example.com/sql_result.php");
// Send data using the POST method
myRequest.method = URLRequestMethod.POST;
// The data property of the request is set to the
// URLVariables instance (myVariables) to send to the PHP file.
// Note: myVariables stored the variable (e.g. candidate)
myRequest.data = myVariables;
// Create a new instance of the URLLoader class to work with.
// URLLoader.load( ) method should be used when we need the
// sent variables returned back to Flash ActionScript.
var myLoader:URLLoader = new URLLoader;
//specify dataFormat property of the URLLoader to be "VARIABLES"
//This ensure that the variables loaded into Flash with the same variable names
myLoader.dataFormat = URLLoaderDataFormat.VARIABLES;
//Load the PHP file by using URLRequest
myLoader.load(myRequest);
//Listen when the loading of data COMPLETE
//Call the loadComplete function when the loading COMPLETE
myLoader.addEventListener(Event.COMPLETE, loadComplete);
}
// This is the function that display the data returned back from PHP file
function loadComplete(evt:Event):void {
//Display the value with variable name "totalItem"
total_txt.text = evt.target.data.totalItem
//Get the value (string) with variable name "phpConfirm"
var myResult:String = evt.target.data.phpConfirm;
//Split the string into an Array
var myArray:Array = myResult.split("|");
//output_txt.text = "The number of items are: " + myArray.length;
var finalString = "";
var i:int;
for (i = 0; i < myArray.length; i++) {
finalString = finalString + myArray[i] + "<br>";
}
output_txt.htmlText = finalString;
}
And in my sql_result.php:
<?php
$username = $_POST['username'];
// create connection
$connection = mysql_connect("****.perso", "root", "root") or die ("Couldn't connect to the server.");
// select database
$db = mysql_select_db("dbase", $connection) or die ("Couldn't select database.");
// create SQL
$sql = "SELECT domain FROM d_table where username = '$username'";
// execute SQL query and get result
$sql_result = mysql_query($sql, $connection) or die ("Couldn't execute query.");
// get number of rows in $result.
$num = mysql_numrows($sql_result);
$phpConfirm = "";
$counter = 0;
while ($row = mysql_fetch_array($sql_result)) {
$domain = $row["domain"];
if ($counter == 0) {
$phpConfirm .= $domain;
} else {
// Use a item limiter "|" to seperate the records
$phpConfirm .= "|" . $domain;
}
$counter++;
}
echo "phpConfirm=" . $phpConfirm . "&totalItem=" . $num;
// free resources and close connection
mysql_free_result($sql_result);
mysql_close($connection);
?>
How can I retrieve the variables with the date and not the username ?
And, more complex, how can I use both ? (example : I choose the date AND the username "John" and it shows me all the variables of my table where the date and the username matches ?
Thank you for your help,
EDIT
So, I've changed in my AS3 code the labels by these :
memberCombo.prompt = "Please select a date";
memberCombo.addItem( {label: "2015-06-23" } );
memberCombo.addItem( {label: "06/23/2015" } );
memberCombo.addItem( {label: "23-06-2015" } );
and in my php code :
I've changed
$username= $_POST['username'];
by
$date = $_POST['date'];
and
$sql = "SELECT domain FROM d_table where username = '$username'";
by
$sql = "SELECT domain FROM d_table where date = '$date'";
But it seems that my flash app doesn't find any "domain" with this date.
No error. It just doesn't find anything.
Any idea why ?
Related
I wrote a php web service to get all data when coins were greater than 0. Here is the code:
organisationListClient-Copy.php
<?php
require_once("lib/nusoap.php");
// Create the client instance
$client = new nusoap_client("http://localhost/TTrockstars/ws/organisationListWS-copy.php");
//check if there were any instantiation errors, and if so stop execution with an error message:
$error = $client->getError();
echo ($error);
if ($error) {
die("client construction error: {$error}\n");
}
// Call the SOAP method
$result = $client->call("getOrganisationList");
$error = $client->getError();
if ($error) {
print_r($client->response);
print_r($client->getDebug());
die();
}
// Display the result
// echo "<pre>";
print_r($result);
//$fichero = file_get_contents($_SERVER['DOCUMENT_ROOT'].'/images/'.$imgname, FILE_USE_INCLUDE_PATH);
//echo ($_SERVER['DOCUMENT_ROOT'].'/data/');
// echo "</pre>";
?>
organisationListWS-Copy.php
<?php
//****including config file****
include 'config.php';
function getOrganisationList() {
$db = dataBaseConn();
$con = mysqli_connect($db['DB_SERVER'],$db['DB_USER'],$db['DB_PASSWORD'],$db['DB_DATABASE']);
if($con){
mysqli_set_charset($con,"utf8");
/*$orgListRS = mysqli_query($con,"SELECT name FROM prop ");*/
$orgListRS = mysqli_query($con,"SELECT id, name, image, extra_image FROM prop where coins > 0");
$orgList = [];
while($orgListRow = mysqli_fetch_array($orgListRS, MYSQLI_BOTH)){
//id
$usrId = $orgListRow['id'];
$usrId = str_replace(",", ",", $usrId);
$usrId = str_replace(" ", " ", $usrId);
$orgList[] = $usrId;
//name
$usrName = $orgListRow['name'];
$usrName = str_replace("’", "'", $usrName);
$usrName = str_replace(" ", " ", $usrName);
$orgList[] = $usrName;
//image
$usrImage = $orgListRow['image'];
$usrImage = str_replace("", "", $usrImage);
$usrImage = str_replace(" ", " ", $usrImage);
$orgList[] = $usrImage;
//extra image
$usrExtimage = $orgListRow['extra_image'];
$usrExtimage = str_replace(",", ",", $usrExtimage);
$usrExtimage = str_replace(" ", " ", $usrExtimage);
$orgList[] = $usrExtimage;
}
mysqli_free_result($orgListRS);
$replyJson["status"]="SUCCESS";
$replyJson["orgList"]= $orgList;
mysqli_close($con);
return json_encode($replyJson);
}else{
$replyJson["status"]="FAILED";
return json_encode($replyJson);
}
}
require_once("lib/nusoap.php");
$urlPrefix = nameSpaceURL();
$URL = $urlPrefix . "/ws/organisationListWS-copy.php";
$namespace = $URL . '?wsdl';
$server = new soap_server();
$server->configureWSDL("WebServices for getting list of organisations");
$server->register("getOrganisationList",
array(),
// return value(s):
array('return'=>'xsd:string'),
// namespace:
$namespace,
// soapaction: (use default)
false,
// style: rpc or document
'rpc',
// use: encoded or literal
'encoded',
// description: documentation for the method
'Return list of organistaions');
$_HTTP_RAW_POST_DATA = isset($HTTP_RAW_POST_DATA) ? $HTTP_RAW_POST_DATA : "";
$server->service($_HTTP_RAW_POST_DATA);
?>
When I run it in browser, I get all ids, names, images and extra images whose coins are greater than 0. Here is a screen shot:
Here is my table structure:
now I need to change the sql query like this:
if (updated_date=="new_date") {
//Send all data (return ids, names, images, extra images whose coins are greater than 0)
}
else {
//Get ids, names, images and extra images which are added after updated date
}
How can I modify current sql query to achieve that?
Thats fairly simple, you just need to create the new criteria for your query if the condition exists, and add it to the original query. If the condiftion does not exist $extraCriteria will be empty and no chnage will be made to the original query.
$extraCriteria = '';
if ($updated_date !== "new_date") {
//Get ids, names, images and extra images which are added after updated date
$extraCriteria = " AND updated_date > '$updated_date'";
}
$orgListRS = mysqli_query($con,"SELECT id, name, image, extra_image
FROM prop
where coins > 0
$extraCriteria");
I am of course guessing the actual names of your columns and variables but I hope this gives you a basic idea.
am creating my flash project that accepts 4 variables i.e. name, school, score and date. However the connection between FLASH, PHP and MYSQL works fine and i can send data to MySQL database via flash with no problem. Now my problem is that i can't retrieve and view the data back to flash. I created a textfield named highscores for retrieving data in flash. And am sure my php code for retrieving is fine since i can view data in browser. So is there a way to retrieve my data in flash? here is my coding for flash:
str.text = "";
myschool.text = "";
myscore.text = "";
//Here i declared a textfield named highscores
//var text:String = highscores.text;
btn_submit.addEventListener(MouseEvent.CLICK, submitted);
function submitted(e:MouseEvent)
{
if(!str.length) {
status_txt.text = "Please enter your name";
}
else if (!myschool.length) {
status_txt.text = "Please enter your school name";
}
else if (!myscore.length) {
status_txt.text = "Please enter your score";
}
else {
var myrequest:URLRequest = new URLRequest("http://127.0.0.1/Y/sendscore.php");
myrequest.method = URLRequestMethod.POST;
var variables:URLVariables = new URLVariables();
variables.name = str.text;
variables.school = myschool.text;
variables.score = myscore.text;
myrequest.data = variables;
var loader:URLLoader = new URLLoader();
loader.dataFormat = URLLoaderDataFormat.VARIABLES;
loader.addEventListener(Event.COMPLETE, dataOnLoad);
loader.load(myrequest);
}
}
function dataOnLoad(evt:Event)
{
trace("Data submission complete");
var returnVars = evt.target.data;
trace("***********************");
for (var myVars in returnVars) {
trace(myVars + ": " + returnVars[myVars]);
}
trace("***********************");
MC_success.alpha=100;
//status is a custom flag passed from back-end
}
btn_scores.addEventListener(MouseEvent.CLICK, loadScores);
function loadScores(e:MouseEvent):void {
var fileLoader:URLLoader = new URLLoader();
fileLoader.addEventListener(Event.COMPLETE, scoresLoadComplete);
fileLoader.load(new URLRequest("http://127.0.0.1/Y/scores.php"));
}
function scoresLoadComplete(evt:Event):void {
try {
var returnVars = evt.target.data;
highscores.htmlText = returnVars;
trace("Data retrieved successfully");
for (var myVars in returnVars) {
trace(myVars + ": " + returnVars[myVars]);
}
trace("***********************");
//highscores.htmlText = returnVars.scores;
} catch (err:Error) {
trace("Can't parse loaded file: " + err.message);
}
}
HERE IS MY PHP CODE FOR RETRIEVING DATA
<?php
//Include database connection details
require_once('config.php');
//Connect to mysql server
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if(!$link) {
die('Failed to connect to server: ' . mysql_error());
}
//Select database
$db = mysql_select_db(DB_DATABASE);
if(!$db) {
die("Unable to select database");
}
//Create INSERT query
$qry = "SELECT * FROM highscores ORDER BY score DESC LIMIT 5";
$result = #mysql_query($qry);
$num=mysql_numrows($result);
if($num > 10)
{$num = 10;}
//echo "writing=Ok";
echo "<b><center>Best Times:</center></b><br /><table>";
//echo "scores=<b><center>Best Times:</center></b><br /><table>";
$i=0;
$i2=1;
while ($i < $num) {
$name=mysql_result($result,$i,"user");
$school=mysql_result($result,$i,"school");
$score=mysql_result($result,$i,"score");
$date=mysql_result($result,$i,"date");
echo "<tr><td align=left valign=top>$i2.</td><td align=center valign=top><b>$name</b> <b> | $school</b> | $score | $date</td></tr><tr><td colspan=2><hr></td></tr>";
$i2++;
$i++;
}
echo "</table>";
//$urlRefresh = "scores.php";
//header("Refresh: 15; URL=\"" . $urlRefresh . "\"");
exit();
mysql_close();
?>
As I mentioned in my previous answer, a textfield in Flash won't play well with HTML tables.
In your PHP file, you need to replace everything between the first and last echo with the following:
echo "scores=<b>Best Times:</b><br />";
$i = 0;
$i2 = 1;
while ($i < $num) {
$name = mysql_result($result,$i,"user");
$school = mysql_result($result,$i,"school");
$score = mysql_result($result,$i,"score");
$date = mysql_result($result,$i,"date");
echo "$i2. <b>$name</b> | <b>$school</b> | $score | $date <br />";
$i2++;
$i++;
}
Note that I have added back the scores= variable. This shouldn't cause any issues, as long as you're using the following line in AS3:
highscores.htmlText = returnVars.scores;
Separating your variables into name/value pairs means that you can pass other variables from PHP if you need to.
Update:
Having taken a look at your files, the whole thing runs perfectly; it successfully submits to the database and loads data back. However:
I think the issue you're having is with Flash caching your scores.php file.
This is fairly common when doing a URLRequest() on a file you've previously loaded. The most straightforward way to deal with this is to change this line:
fileLoader.load(new URLRequest("http://127.0.0.1/Y/scores.php"));
To this:
fileLoader.load(new URLRequest("http://127.0.0.1/Y/scores.php?rand=" + Math.random() * 999999));
All that does is add a random number to the end of your load as the 'garbage' variable rand. Flash sees this as you loading a different file, and so makes a fresh request rather than pulling it from the cache.
Other than that, everything in your files seems to run exactly as it should.
I have build a website and communicate with actionscript. in actionscript i'm build a function to call php function and post a variables for load data from mysql database.The problem is when i call actionscript function and post variables to php.The php side i call $_POST['action']; for receive a variables from actionscript side but when i want to see this Post $_POST['action']; it error like this
Notice: Undefined index: action in C:\wamp\www\MPA-EM\bin\model.php on line 3
and this is a action script function to call php:
public function SelectData(TBN:String,TYPE:String):void{
var myrequest:URLRequest = new URLRequest("http://localhost/MPA-EM/bin/model.php");
myrequest.method = URLRequestMethod.POST;
var variables:URLVariables = new URLVariables();
variables.tablename = TBN;
variables.action = TYPE;
myrequest.data = variables;
var loader:URLLoader = new URLLoader();
loader.dataFormat = URLLoaderDataFormat.VARIABLES;
loader.addEventListener(Event.COMPLETE, dataOnLoad);
loader.addEventListener(Event.CANCEL, dataError);
try{
loader.load(myrequest);
}catch(e:Error){
Alert.show(e.toString());
}
}
public function dataOnLoad(evt:Event):void
{
Alert.show(evt.target.data.Result);
if(evt.target.data.Result) {
DText.text = 'ok';
} else DText.text = "Error in select submitted data";
//status is a custom flag passed from back-end
}
public function dataError(e:Event) :void{
DText.text = e.target.errormsg;
}
and this is a php function side model.php:
<?php
//test for recive
$actionW = $_POST['action'];//error this line.
echo $actionW;
// end test
if(isset($_POST['action']) && !empty($_POST['action'])) {
$action = $_POST['action'];
echo $action;
switch($action) {
case 'select' :
$tablename = clean($_POST['tablename']);
selectedData($tablename);
break;
case 'blah' : blah();break;
}
}
function selectedData($table){
// create connection
$connection = mysql_connect("localhost", "root", "") or die ("Couldn't connect to the server.");
// select database
$db = mysql_select_db("ideaddcom_maps", $connection) or die ("Couldn't select database.");
// create SQL
$sql = 'SELECT * FROM '.$table;
// execute SQL query and get result
echo $sql;
$sql_result = #mysql_query($sql, $connection) or die ("Couldn't execute query.".mysql_error());
$row = mysql_fetch_object($sql_result);
foreach($row as $cname => $cvalue){
echo "Result=$cvalue";
}
// free resources and close connection
mysql_free_result($sql_result);
mysql_close($connection);
}
//Function to sanitize values received from the form. Prevents SQL injection
function clean($str) {
$str = #trim($str);
if(get_magic_quotes_gpc()) {
$str = stripslashes($str);
}
return mysql_real_escape_string($str);
}
?>
What wrong? Pls any idea for this and Thank.
I do not know if you've found a solution for your problem, but this may help someone else.
1 - Take a look here, It can help you : Submitting scores from AS3 to PHP/SQL - #Error 2101
2 - To avoid PHP Undefined index Notice, you should always verify if your var is set before use it, like what you've done at line 7.
3 - Avoid all outputs that are not used by your AS script in the PHP script because AS will just get the first output.
4 - If you use a for or foreach loop to get data in your PHP script, you should do like this because echo that will send data to AS should be executed once :
$result = '';
$sep = ',';
foreach($row as $cname => $cvalue){
$result .= $cvalue . $sep;
}
echo 'Result='.$result;
I am trying to update my database using ajax, but I cannot seem to understand why the php code does not update the database. The script:
function Insert () {
if (XMLHttpRequestObject) {
XMLHttpRequestObject.open("POST","list_insert.php");
XMLHttpRequestObject.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
XMLHttpRequestObject.onreadystatechange = function() {
if (XMLHttpRequestObject.readyState == 4 && XMLHttpRequestObject.status == 200) {
var returnedData = XMLHttpRequestObject.responseText;
var messageDiv = document.getElementById('messageDiv');
messageDiv.innerHTML = returnedData;
}
}
var item = document.getElementById('items').value;
var desc = document.getElementById('description').value;
var data = item + '|' + desc + '|';
XMLHttpRequestObject.send("data=" + data);
}
return false;
}
This is the php code for list_insert:
<?php
include "function_list.php";
$myData = $_POST['data'];
$datetime = date('Y-m-d H:i:s');
list($items,$description) = explode ('|',$myData);
$statement = "INSERT INTO record ";
$statement .= "(items,description) ";
$statement .= "VALUES (";
$statement .= "'".$items."', '".$description."')";
print $statement;
insert($statement);
print "done";
?>
My php function to insert into the db (function_list):
<?php
$con=mysqli_connect("localhost","shop");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
function insert($statement) {
global $con;
mysqli_query($con,$statement);
}
?>
When I print the statement out, the query is correct (I have verified this by manually copy pasting it in mysql). I think the issue is with my insert function.
Any help is appreciated,
thank you.
Firstly, all mysql statements must end in a semicolon.
Secondly, have you made sure $items and $description are the values you expect them to have? Do they have any unescaped quotes?
Also, typically you would send each of the fields as a separate value like so:
var item = document.getElementById('items').value;
var desc = document.getElementById('description').value;
XMLHttpRequestObject.send("items=" + item + "&desc=" + desc);
$$items = $_POST['items'];
$description = $_POST['desc'];
By default, the username for mysql is root, and the password is blank, even though you aren't prompted for these, they are set by default.
I think this might be the issue
in ur global variable $con letz say you put this
$con = new mysqli("host", "user", "pwd", "dbname");
then
function insert($statement) {
$con->query($statement);
$con->close();
}
I am creating a game which uses the sharedObject to save each players progress locally. It also connects to a central database to create an online scoreboard. When a user inserts a score for the first time a unique ID is sent out of the database to the swf and saved as part of the sharedObject data.
Absolutely everything works and the ID is saved to the sharedObject, however when the swf is restarted the ID does not load (even though the other variables saved in the sharedObject do load).
I think it may be to do with the way it is formatted, perhaps to do with the XML but I'm not sure.
FLASH CODE
function saveGame(currID:Number) {
gameInfo.data["playername"+currID] = playername;
gameInfo.data["playerscore"+currID] = playerscore;
gameInfo.data["playerID"+currID] = playerID;
gameInfo.data["playerLevel"+currID] = playerLevel;
for(i=1; i<6; i++){
gameInfo.data["level"+i+"Score"+currID] = ["level"+i+"Score"];
}
gameInfo.flush();
}
function loadGame(currID:Number) {
playername = gameInfo.data["playername"+currID];
playerscore = gameInfo.data["playerscore"+currID];
playerID = gameInfo.data["playerID"+currID];
playerLevel = gameInfo.data["playerLevel"+currID];
}
function scoreboardSubmit() {
var insertReceive:XML = new XML();
insertReceive.ignoreWhite = true;
insertReceive.onLoad = function() {
playerID = this.firstChild.childNodes[0];
saveGame(currID);
};
insertSend = new LoadVars();
insertSend.playername = playername;
insertSend.playerscore = playerscore;
insertSend.playerID = playerID;
insertSend.sendAndLoad("scoreboardSend.php", insertReceive, "POST");
}
PHP CODE
<?php
$name = strip_tags($_POST['playername']);
$score = $_POST['playerscore'];
$id = $_POST['playerID'];
$con = mysql_connect("localhost","******","******");
mysql_select_db("******", $con);
if ($id == 0)
{
$insert="INSERT INTO scoreboard (Name, Score)
VALUES
('$name','$score')";
mysql_query($insert,$con);
$returnID = mysql_query("SELECT LAST_INSERT_ID()");
$playerID = mysql_result($returnID,0);
echo "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n";
echo "<returnID>" . $playerID . "</returnID>\n";
}
else
{
$update = mysql_query("UPDATE scoreboard SET Name = '$name', Score = '$score'
WHERE id = '$id'",$con);
}
mysql_close($con);
?>
If I m understanding well, you shuld try to replace playerID by currID in your XML receiver object because atm you put the xml reply in a playerID var and the line after you call saveGame with currID as arg which is undefined.
function scoreboardSubmit() {
var insertReceive:XML = new XML();
insertReceive.ignoreWhite = true;
insertReceive.onLoad = function() {
var currID = this.firstChild.childNodes[0];
saveGame(currID);
};
insertSend = new LoadVars();
insertSend.playername = playername;
insertSend.playerscore = playerscore;
insertSend.playerID = playerID;
insertSend.sendAndLoad("scoreboardSend.php", insertReceive, "POST");
}
You should add the correct content type to your php page
header('Content-type: text/xml');
Finally I think it would be better to store your data in a different way (for exemple by using a savedgame object which contains all game related properties for a same currID)
Thanks for the answer but that wasn't the problem.
I think the problem was that when the sharedObject was having problems storing variable as true numbers and was just converting everything to strings, which was fine for the score but not for the Id as that had to be passed on to the PHP.
Solved it by using String('number') to convert the ID to a string to be stored in the sharedObject and then Number('string') to convert it back to a number when pulling it from the sharedObject.