Populate an array in flash with data from php - php

Hi so I need to populate an array in flash with information from php. My php code is :
<?php
$db = mysql_connect("localhost","root","");
if (!$db) {
die("Database connection failed miserably: " . mysql_error());
}
$db_select = mysql_select_db("profileofperson",$db);
if (!$db_select) {
die("Database selection also failed miserably: " . mysql_error());
}
?>
<html>
<head>
<title>mySQLtestfile</title>
</head>
<body>
 
<?php
//Step4
$result = mysql_query("SELECT * FROM catalogue", $db);
if (!$result) {
die("Database query failed: " . mysql_error());
}
while ($row = mysql_fetch_array($result)) {
echo $row[" Name"]." ".$row["age"]." ".$row["Allergies"]." ".$row["height"]." ".$row["weight"]."<br />";
}
?>
</body>
</html>
which at present is displaying information from a database. How do i get flash to populate into an array?

Make your document xml, not html, start the document like this:
<?php
header("Content-type: text/xml");
echo chr(60).chr(63).'xml version="1.0" encoding="utf-8" '.chr(63).chr(62);
This just adds a header tag so the browser/flash recognises the document as XML (similar to !DOCTYPE with HTML) : <?xml version="1.0" encoding="UTF-8"?>
Then, query as you are doing, but echo the results in a valid XML format:
echo "<people>";//Create the parent node
while ($row = mysql_fetch_array($result)) {
echo "<person>";//Open child node, add values:
echo "<name>".$row[" Name"]."</name>";
echo "<age>".$row["age"]."</age>";
echo "<allergies>".$row["Allergies"]."</allergies>";
echo "<height>".$row["height"]."</height>";
echo "<weight>".$row["weight"]."</weight>";
echo "</person>";//Close child node
};
echo "</people>";//Close the parent node
?>
I've just written this out off the top of my head so may not be perfect, but it should be easy enough for you to check that it's generating a valid XML document (just load the page in a browser, get an XML viewer plugin to find out more if it's going wrong) and adjust if not, there are millions of tutorials on generating XML pages from PHP.
Then, use the URLLoader class in your flash application to access it:
var loader:URLLoader = new URLLoader();
//The loader class
var urlRQ:URLRequest = new URLRequest('yoursite/yourpage');
//The URL request
loader.dataFormat = URLLoaderDataFormat.TEXT;
//Use this for xml
urlRQ.method = URLRequestMethod.POST;
//Set method type (normally post)
loader.load(urlRQ);
loader.addEventListener(Event.COMPLETE,loadedData);
Then, have loadedData parse the XML:
function loadedData(e:Event):void {
var people:XML = XML(e.target.data);//Cast this var as XML to access
//people should represent top-level ie <people>;
for each(var person:XML in people.person){//Iterate over member nodes called 'person';
trace(person.age);//XML object node names can be referenced
//directly with dot notation!
trace(person.name);//etc...
}
}
One last thing, the mysql_ functions are deprecated in PHP, I found this out recently, use SQLi or PDO instead in future!
Hope this helps, as I say I've written it off the top of my head and it's better that you experiment with it, but if you do get stuck leave a comment and I'll have a look!

Related

PHP/JQUERY- Can't return data from a query

I'm doing a project for an exam. I'm stuck with that and I hope someone of you could help me (I'm italian, so sorry for my bad english!).
I have to query an existing database stored in phpmyadmin with a PHP script. Then, the query result need to be parsed with a jquery script and printed to an HTML page.
Here is the PHP script:
<?php
$con = mysql_connect('localhost', 'root', '');
if (!$con) {
die('Errore di connessione: ' . mysql_error());
}
mysql_select_db("progetto_lpw", $con);
$sql="SELECT denominazione FROM farmacia";
$result = mysql_query($sql) or die(mysql_error());
$num=mysql_numrows($result);
while($row = mysql_fetch_array($result)){
print json_encode($row['denominazione']);
print "<br />";
}
?>
I've already tested the PHP script calling it via browser and it works.
Then, I parse the result with this jquery script (the use of this combination is a requirement of the project):
$("#button").click(function(){
$.getJSON('json.php', function(data) {
$.each(data, function(index,value){
$("#xx").append("<p>"+value+"</p>")
})
})
})
Here is the problem: when I open the HTML page and I click the button on firefox, consolle says "no element found" referring to PHP script.
"xx" is the id of the div in which elements are printed.
Where is the error?
Thanks to everyone.
Replace below code
while ($row = mysql_fetch_array($result)) {
print json_encode($row['denominazione']);
print "<br />";
}
With below code and try
$rows = array();
while ($row = mysql_fetch_array($result)) {
$rows[] = $row['denominazione'];
}
header('Content-type: application/json');
echo json_encode($rows);
HTML
<button id="button">Fetch JSON</button>
<div id="xx"></div>
JS
$("#button").click(function() {
$.getJSON('json.php', function(data) {
$.each(data, function(index, value) {
$("#xx").append("<p>" + value + "</p>")
});
});
});
Response from json.php should be in below format
["AGGERI","ALCHEMICA 1961"]
The reason your code isn't working is that it's producing output like this:
"foo"<br />
"bar"<br />
That's not valid JSON. To be valid, you have to not have the HTML <br /> in there (this is JSON, not HTML), and you have to have commas between the elements you want to return.
json_encode will handle formatting the array correctly for you.
jsFiddle Demo with post request to send and get json output
'print' works differently then 'echo'. At least i am sending JSON packages with echo from php.
Can you replace it ?
// in php
echo json_encode($row['denominazione']);
// in jquery script, best to place "<br />" tag here
$("#xx").append("<p>"+value+"</p><br />")

php code in a HTML page

I have phpbb forum and I wanted to add a field in the registration page...the modification was to enable the user to choose their role .. for example to be a moderator .. or to be a normal member or .. I am actually making the forum a bit private and I am grouping users in groups so they have a restricted access to some forums. Anyways I have the html template file and I want to get the dropdown menu list from a php file code
here is my code of the php
<?php
include '/blah/config.php';
$con = mysql_connect($dbhost, $dbuser, $dbpasswd);
if(!$con)
{
die("Couldn't Connect: ".mysql.error());
}
mysql_select_db($dbname, $con);
$result = mysql_query("SELECT group_name FROM phpbb_groups");
$array = array();
while($row = mysql_fetch_array($result))
{
$array[] = $row[0];
}
mysql_close($con);
foreach( $array as $group_name)
{
echo $group_name."</br>"; // I want to put this value in the dropdown list in the html file
}
?>
here is the part of the html code that I want to edit
<dt><label>GroupID:</label></dt>
<dd><select name="group_id" id="group_id"" tabindex="7" class="autowidth">I want to get the data from php in here</select></dd>
PS: the template file is HTML file and can't be renamed to php
Okay, sorry about the last answer, didnt read your PS there...
Here's a jQuery solution, uses JSON as an output from your PHP file then an asynchronous request to fill in the dropdown.
PHP Code
// The rest of your code, then output your $array this way
header("Content-type: application/json");
$array = array("banana", "apple", "eggroll");
echo json_encode($array);
die;
Your HTML (example)
Make sure you add jquery into your HEAD if you dont already have it.
<dt><label>GroupID:</label></dt>
<dd><select name="group_id" id="group_id"" tabindex="7" class="autowidth"></select></dd>
<script>
$(document).ready(function() {
$.get('sefesf.php', {"q":"1"}, function(data) {
if(data.length > 0)
{
for(var i = 0; i < data.length; i ++)
{
$('select#group_id').append('<option>' + data[i] + '</option>');
}
}
});
});
</script>
Be sure to change sefesf.php to your php file with the json output and {"q":"1"} to {} if you dont need any GET parameters sent.

XML(in php) parsing on iPhone

I am developing an iPhone app and I want to put some datas to UITableView.
I got an app showing several xml parser run from here.
and then, I'd separated GDataXMLParser from this project and made it run but
I have an odd problem that I can't figure out.
This is the code putting php file.
- (void)start {
self.startTimeReference = [NSDate timeIntervalSinceReferenceDate];
[[NSURLCache sharedURLCache] removeAllCachedResponses];
self.parsedSongs = [NSMutableArray array];
NSURL *url = [NSURL URLWithString:#"http://mydomain.blabla/phpxmltest.php"];
[NSThread detachNewThreadSelector:#selector(downloadAndParse:) toTarget:self withObject:url];
}
When I make a php to xml with echo directly, like this way,
......
echo "<entry><title>this is the TEST</title><item>TEST</item></entry>";
......
iPhone app does parse this code like XML.
But when I make a php to xml with mySQL query (cause I want to make a xml items from DB), like this way,
<?php
echo '<?xml version="1.0" encoding="UTF-8"?>';
$result = mysql_connect("localhost", "my ID", "my Password");
mysql_select_db("my DB");
$q = "select name, price, age, likeit, keyword from Table where category=101";
$result = mysql_query($q);
$num_rows = mysql_num_rows($result);
echo "<entry>\n";
for ($i=1; $i<=$num_rows; $i++) {
$row = mysql_fetch_assoc($result);
echo "<item>\n";
echo "<title>" . $row["name"] . "</title>\n";
echo "<category>" . $row["price"] . "</category>\n";
echo "<artist>" . $row["age"] . "</artist>\n";
echo "<album>" . $row["likeit"] . "</album>\n";
echo "<releasedate>" . $row["keyword"] . "</releasedate>\n";
echo "</item>\n";
}
echo "</entry>";
?>
iPhone app doesn't parse this code. It tells me there's no item in XML.
What is the most strange to me, is the results on Web Browser are same exactly.
When I put the url in browser, the output itself and the source(with viewing source function of browser) are exactly same. This is the source view in web browser.(Plz don't mind some encoding problem)
<?xml version="1.0" encoding="UTF-8"?>
<entry>
<item>
<title>������ ���ĺ� ������</title>
<category>11000</category>
<artist>3</artist>
<album>0</album>
<releasedate>���ĺ� ���߱�</releasedate>
</item>
<item>
<title>���ĺ� ��������</title>
<category>18000</category>
<artist>3</artist>
<album>0</album>
<releasedate>���ĺ� ����</releasedate>
</item>
…..
I've tried hard to make it work but it's too difficult for me. I am a starter in iOS and Web Programming. Please let me know what is the problem and solution.
Thank u in advance!:D
(Plz don't mind some encoding problem)Maybe we don't mind but the xml parser probably does.
You should
set the mimetype in the http response header
set the charset in the http response header (though it's already in the xml declaration)
set mysql's client encondig to utf8 in order to receive the data utf-8 encoded
treat all the data from the database with an appropriate escape function
or even better use something like XMLWriter
and you should also print error messages as a somewhat valid xml document since you told the client that it will receive xml.
E.g. (tested only by php -l):
<?php
if ( headers_sent() ) {
die("can't set mimetype and/or charset after output has been sent to the client");
}
ini_set('default_charset', 'utf-8');
ini_set('default_mimetype', 'text/xml');
// ini_set('default_mimetype', 'application/xml');
echo '<?xml version="1.0" encoding="UTF-8"?>';
$mysql = mysql_connect("localhost", "my ID", "my Password");
if ( !$mysql ) {
die('<error>database connection failed</error>');
}
if ( !mysql_select_db("my DB", $mysql) ) {
die('<error>database selection failed</error>');
}
if ( !mysql_set_charset('utf8', $mysql) ) {
die('<error>setting database selectiocharset failed</error>');
}
$q = 'SELECT name, price, age, likeit, keyword FROM Table WHERE category=101';
$result = mysql_query($q, $mysql);
if ( !$result ) {
die('<error>database query failed</error>');
}
echo "<entry>\n";
while( false!=($row=mysql_fetch_assoc($result)) ) {
echo '
<item>
<title>', htmlspecialchars($row["name"], 'utf-8'), '</title>
<category>', htmlspecialchars($row["price"], 'utf-8'), '</category>
<artist>', htmlspecialchars($row["age"], 'utf-8'), '</artist>
<album>', htmlspecialchars($row["likeit"], 'utf-8'), '"</album>
<releasedate>', htmlspecialchars($row["keyword"], 'utf-8'), '</releasedate>
</item>';
}
echo "</entry>";
?>

Load images to a TileList from Mysql using PHP and XML on Flash CS5

I have a mysql database with a table containing PATH's to images.
I want to load al the images to a TileList. Now i have this in PHP:
<?PHP
mysql_connect("localhost", "root", "root");
mysql_select_db("prototipo");
$result = mysql_query("select entretenimiento_id, e_nombre, e_imagen from entretenimiento");
echo "<?xml version=\"1.0\" ?><entretenimiento>";
while($row = mysql_fetch_assoc($result))
{
echo "<e_nombre>" . $row["e_nombre"] . "</e_nombre>";
echo "<e_imagen>" . $row["e_imagen"] . "</e_imagen>";
}
echo "</entretenimiento>";
?>
This is supposed to fetch me the PATH of the image, the name so it goes on the label of the tile that displays the image, and brings me also the id so i can launch another query when that image is clicked on.
All this is set into a dynamically created XML.
Now my question.... How do i load this??? What to do o AS3?? I already have the AS3 for the tilelist, i only need to load this dynamically created XML from PHP to it.
Thanks in advance. And sorry if i messed up on english, its not my main language. Im South American.
I have a partial answer:
var path:String = "http://localhost/entretenimiento.php";
xmlLoader:URLLoader = new URLLoader();
xmlLoader.addEventListener(Event.COMPLETE, onLoadComplete);
xmlLoader.load(new URLRequest(path));
function onLoadComplete(e:Event):void {
var xmlData:XML = new XML(e.target.data);
//trace(xmlData);
for (var i:int=0; i<xmlData.*.length(); i++)
{
myTileList.addItem({label:xmlData.e_nombre[i], source:xmlData.e_imagen[i]});
//trace(xmlData.e_nombre[i]);
}
}
Althought this shows me the images and the titles on the tiles, i also get two more tiles that are empty, and in the trace they are shown as "undefined". Any thoughts to why is this?
Here is a sample code that should works :
var xmlLoader:URLLoader = new URLLoader();
xmlLoader.addEventListener(Event.COMPLETE, showXML);
// change the path of your php file
xmlLoader.load(new URLRequest("your-file.php"));
function showXML(e:Event):void
{
var entretenimiento:XML = new XML(e.target.data);
// for each row :
for (var x:XML in entretenimiento.loc)
{
// Change the name of your tilelist
myTileList.addItem({label:x.e_nombre, source:x.e_imagen});
}
}

FLASH as3 not able to identify localhost php web address

I am trying to retrieve mysql data using php(products.php) and return the data in xml format to ADobe flash as3; but i am getting following error.
Error opening URL 'http://localhost/Flash/player/products.php'
Error #2044: Unhandled ioError:. text=Error #2032: Stream Error. URL: http://localhost/Flash/player/products.php at php_mysql3_as3_fla::MainTimeline/frame1()
Please any suggestion or help why flash is not identifying the http://localhost/Flash/player/products.php addres. i have WAMP installed; which works fine as i have many other php projects working here.
Thanks in advance for help and suggestion.
THe following is my php code
<?php
$link = mysql_connect("localhost","root","");
mysql_select_db("test");
$query = "select * from products";
$results = mysql_query($query);
echo '<?xml version="1.0" encoding="utf-8" ?>'." \n";
echo"<GALLERY>\n";
$cnt=0;
while($line=mysql_fetch_assoc($results))
{
echo '<IMAGE TITLE="'.$cnt.'">'.$line['product'].'</IMAGE>'." \n";
$cnt++;
}
echo "</GALLERY>\n";
mysql_close($link);
?>
the php file is located at c:\wamp\www\Flash\player\products.php
below is my AS3 flash code
var myXML:XML;
var myLoader:URLLoader = new URLLoader();
myLoader.dataFormat = URLLoaderDataFormat.VARIABLES;
//myLoader.load(new URLRequest("c:\\wamp\\www\\Flash\\player\\products2.xml"));
myLoader.load(new URLRequest("http://localhost/Flash/player/products.php"));
myLoader.addEventListener(Event.COMPLETE, processXML);
function processXML(evt:Event):void {
myXML = new XML(evt.target.data);
for (var i:int = 0; i<myXML.*.length(); i++){
trace("My image number is " + (i+1) + ", it's title is " + myXML.IMAGE[i].#TITLE + " and it's URL is " + myXML.IMAGE[i]);
};
//trace("data: " + myLoader.data);;
}
In chat it turned out the problem was a firewall.
Here is another related question:
Testing movie with Flash IDE fails to load file from localhost
This might be possible:
Your movie runs in the local realm, and you are trying to load a network resource (i guess this will be the case). In that case you need to add the compile flag: -use-network=true
The php file does not exist.
You always need to catch the URLLoader events:
dispatcher.addEventListener(HTTPStatusEvent.HTTP_STATUS, httpStatusHandler);
dispatcher.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
to see what happened!
See these event handlers in action: http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/net/URLLoader.html#includeExamplesSummary

Categories