Using php to write to another php page....need opinions on best method for pulling data back to device
Hello again everybody on here :)
So we just finally got gps data to go from an android device to a database using php to pass the array into the table. Awesome.
Now I need to pull the data out of the table and do one of two things that I can think of.
I can modify my existing php page using fwrite() to write the incoming data to another php page which would act like a db table itself.....which is kind of defeating the purpose of having things stored in the db.
I can create a php page that I have the device hit when it wants to pull all the gps marks from the db. This Im not sure how to do at the moment.
My problem is for the first method Im a little unsure of how efficient space wise this would be vs. just pulling stuff from the db and also Im not to sure how to set up the variables in so that fwrite() actually writes them in the json format I need
In order to use fwrite() and get things to write to the new page correctly would I use it like this?
$myFile = "testFile.php";
$fh = fopen($myFile, 'w') or die("can't open file");
$stringData = " "lat": ", $lat, " \n";
fwrite($fh, $stringData);
$stringData = " "long": ", $long, " \n";
fwrite($fh, $stringData);
fclose($fh);
For the second method Im not sure really where to start. I have the gps info stored in a t开发者_如何学编程able within a mysql database so I would need a php script that returns the all the gps marks in the table to the user so they appear on the device. Also very soon well be moving to a postgresql database so help on doing that too would be great.
Once again any help would be much appreciated :)
Out of your two options, option 2 is the simplest, and the best. The PHP is dead simple:
<?php
mysql_connect("localhost","USERNAME","PASSWORD");
mysql_select_db("yourdb");
$sql = " select location_name, location_lat, location_lon from locations ";
$res = mysql_query($sql);
$locations = array();
for ($i = 0; $i < mysql_num_rows($res); $i++){
$row = mysql_fetch_assoc($res);
$locations[] = (object) $row;
}
echo json_encode($locations);
?>
So you want a PHP script that takes GPS data from database and outputs it in JSON, for Android app to consume?
The high level steps and corresponding sub-questions you'll need to find answers to:
- querying database
- "How to write SQL queries?"
- "How to execute SQL query against MySQL and PostgreSQL using PHP?"
- formatting query results as JSON
- "How to serialize data to JSON using PHP?"
精彩评论