PHP can't receive a param from ActionScript3 - php

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;

Related

select values of a particuliar date from a SQL table to Flash

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 ?

FLASH, PHP, MySQL connection

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.

Php code does not send query to database

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();
}

mysqli connection not working inside function? [duplicate]

This question already has answers here:
Executing mysqli_query inside a function
(2 answers)
Closed 7 years ago.
I'm having some problems performing a mysql query inside a php function. The error I am getting is
Notice: Undefined variable: link in C:\path\api\inc\restFunctions.php on line 16
There are several files calling each other so I will attempt to outline the necessary information.
URL Accessed:
localhost/serverList/api/rest.php?action=allServers
serverList/api/rest.php
<?php
include 'inc/restFunctions.php';
$possibleCalls = array('allServers','allEnvs','allTypes','false');
if(isset($_GET['action'])){
$action = $_GET['action'];
}
else{
$action = 'false';
}
if(in_array($action,$possibleCalls)){
switch ($action){
case 'allServers':
$return = allServers();
break;
case 'allEnvs':
$return = allEnvs();
break;
case 'allTypes':
$return = allTypes();
break;
case 'false':
$return = falseReturn();
break;
}
}
serverList/api/inc/restFunctions.php
<?php
include ('inc/config.php');
function allServers(){
$serverInfoQuery = "SELECT * FROM servers"
$allServerResults = $link->query($serverInfoQuery);
$json = array();
while($row = $allServerResults->fetch_assoc()){
$json[]['serverID'] = $row['serverID'];
$json[]['environment'] = $row['environment'];
$json[]['type'] = $row['type'];
$json[]['serverIP'] = $row['serverIP'];
$json[]['serverDescription'] = $row['serverDescription'];
$json[]['serverCreatedBy'] = $row['serverCreatedBy'];
$json[]['serverCreatedDtTm'] = $row['serverCreatedDtTm'];
$json[]['serverUpdatedBy'] = $row['serverUpdatedBy'];
$json[]['serverUpdatedDtTm'] = $row['serverUpdatedDtTm'];
}
$jsonResults = json_encode($json);
return $jsonResults;
}
?>
serverList/api/inc/config.php
<?php
$host = 'localhost';
$user = 'userName';
$password = 'password';
$database = 'database';
$link = new mysqli($host, $user, $password, $database);
if (mysqli_connect_errno()) {
exit('Connect failed: '. mysqli_connect_error());
}
?>
I have verified that the query being called works. I also verified that the connection info (masked above) works by using a different page of this software that queries the db.
I'm assuming I must have missed a quote or paren somewhere, but I'm baffled as to where it might be.
The problem is with PHP variable scoping. Add this line inside of allServers() function before you refer to the $link variable for the first time:
global $link;
See more here:
http://php.net/manual/en/language.variables.scope.php
In my opinion using global variables is not a good solution. You might override $link ($link is rather usual name for a variable you may be using for another purposes) variable in some scope by accident, resulting in lot's of confusion and difficult debugging.
Just pass it as a function parameter - much cleaner and easier to read:
function AllServers($link) {
$serverInfoQuery = "SELECT * FROM servers";
$allServerResults = $link->query($serverInfoQuery);
//More PHP code
}
if(in_array($action,$possibleCalls)){
switch ($action){
case 'allServers':
$return = allServers($link);
break;
}
}
To be honest, even better solution would be using some generic classes/functions to establish your mysql connection like so:
class DB {
private static $link = null;
public static function getConnectionResource() {
//In that way we "cache" our $link variable so that creating new connection
//for each function call won't be necessary
if (self::$link === null) {
//Define your connection parameter here
self::$link = new mysqli($host, $user, $password, $database);
}
return self::$link;
}
}
function getAllServers() {
$link = DB::getConnectionResource();
//Preform your query and return results
}
Use global variable
function allServers(){
global $link
...
...
...
... your code follows

php output json

I'm trying to make it easy for me to request json output using jquery from php/mysql. Right now I'm using the below. Can anyone recommend a better way??
/do.php?username=bob
<?php
$str = $_SERVER['QUERY_STRING'];
if($str != ''){
if(preg_match("/username/",$str)){
parse_str($str);
$json = json_encode(checkUserName($username));
echo $json;
}
}
function checkUserName($v){
$db = new DB();
$db->connectDB();
$findUsername = mysql_query("SELECT COUNT(*) FROM user WHERE username = '$v'");
$countUser = mysql_fetch_row($findUsername);
if($countUser[0] < 1){
return array('username' => 'false');
}else{
return array('username' => 'true');
}
$db->disconnectDB();
}
?>
I get back a clean {'username':'false'} or {'username':'true'} which works for what I need; but is there a better way in PHP to do this?
Wow - amazing answers! I dumped my old db class and replaced it with:
<?php
function db_connect(){
$dbh = new PDO("mysql:host=localhost;dbname=thisdb", "dbuser", "dbpass");
return ($dbh);
}
?>
Then in my do.php script I made this change:
<?php
if(isset($_GET['username'])){
header('content-type: application/json; charset=UTF-8');
echo json_encode(checkUserName($_GET['username']));
}
function checkUserName($v){
$dbh = db_connect();
$sql = sprintf("SELECT COUNT(*) FROM user WHERE username = '%s'", addslashes($v));
if($count = $dbh->query($sql)){
if($count->fetchColumn() > 0){
return array('username'=>true);
}else{
return array('username'=>false);
}
}
}
?>
and my jquery is:
function checkUserName(str){
$.getJSON('actions/do.php?username=' + str, function(data){
var json = data;
if(json.username == true){
// allowed to save username
}else{
// not allowed to save username
}
});
}
$str = $_SERVER['QUERY_STRING'];
if($str != ''){
if(preg_match("/username/",$str)){
parse_str($str);
$json = json_encode(checkUserName($username));
echo $json;
}
}
This can be written so much easier by using $_GET superglobal:
if (isset($_GET['username'])) {
echo json_encode(checkUserName($_GET['username']));
}
Inside checkUserName():
$findUsername = mysql_query("SELECT COUNT(*) FROM user WHERE username = '$v'");
You should escape $v properly:
$sql = sprintf("SELECT COUNT(*) FROM user WHERE username = '%s'", mysql_real_escape_string($v));
$findUsername = mysql_query($sql);
Better yet, learn PDO / mysqli and use prepared statements.
$db->disconnectDB();
Unless you're using persistent connections, you don't need this statements. If you do, you should keep the return value inside a variable first and only return after the disconnect.
I don't know what's your DB class, but this looks prettier.
<?php
function checkUserName($v){
$db = new DB();
$db->connectDB();
$findUsername = mysql_query("SELECT COUNT(*) FROM user WHERE username = '$v'");
$countUser = mysql_fetch_row($findUsername);
$db->disconnectDB(); // no code after "return" will do effect
return ($countUser[0] != 0); // returning a BOOL true is better than a string "true"
}
// use addslashes to prevent sql injection, and use isset to handle $_GET variables.
$username = isset($_GET['username']) ? addslashes($_GET['username']) : '';
// the above line is equal to:
// if(isset($_GET['username'])){
// $username = addslashes($_GET['username']);
// }else{
// $username = '';
// }
echo json_encode(checkUserName($username));
?>
By your way, If you want to process the json data in jquery you can do like this
$.ajax({
type:"POST",
data:'username=bob',
url: "do.php",
success: function(jsonData){
var jsonArray = eval('(' + jsonData + ')');
if(jsonArray.username == 'true'){
// some action here
}else if((jsonArray.username == 'false')){
// someother action hera
}
}
},"json");
If you want a fix just replace your checkUsername function with this one:
function checkUserName($v){
$db = new DB();
$db->connectDB();
$findUsername = mysql_query("SELECT username FROM user WHERE username = '$v' LIMIT 1");
if(mysql_num_rows($findUsername))
return array('username' => mysql_result($findUsername,0));
else
return array('username' => 'false');
}
Or a simplier way:
if(isset($_GET['username'])){
$db = new DB();
$db->connectDB();
$query = mysql_query(sprintf("SELECT username FROM user
WHERE username='%s'",
mysql_real_escape_string($_GET['username'])
);
if(mysql_num_rows($query))
$json = array('username'=>mysql_result($query,0));
else
$json = array('username'=>false);
header('content-type:application/json');
echo json_encode($json);
}

Categories