CoolJ Coolie
CoolJ Coolie

Reputation: 107

Need to store the latitude and longitude values generated from android app into mySQL database using PHP

I have made an tracking app in android which successfully generates latitude and longitude

but I need to store lat and long in my external mySQL database using PHP.

I am using value type "decimal(10,7)" for lat and long in DB.

Any ideas how to store lat and long generated from android into my external mySQL database using PHP?

My PHP CODE

<?php 
        $lat = $_GET['lat'];
        $lng = $_GET['lng'];
        $sender=$_POST['sender'];

 $hostname = 'localhost';
 $username = 'xxxx';
 $password = 'xxxxxxx';

   $conn =  mysql_connect($hostname,$username,$password) or die('Error Please Try Again.'); 

if ($conn) { 

    mysql_select_db("android track", $conn); 


   $query2 = "INSERT INTO coor VALUES(NULL,'$sender','$lat','$lng')"; 

    if (mysql_query($query2, $conn)) 
        echo "Data Insertion Successful"; 
    else 
        echo "Oops".  mysql_error() ; 

  } 

 mysql_close();   
 ?>

Upvotes: 0

Views: 2619

Answers (2)

hd1
hd1

Reputation: 34657

Ok, few things before I rewrite your code...

  1. You are opening yourself up to SQL Injection attacks, because you aren't using prepared statements.
  2. The mysql PHP interface is deprecated and mysqli or PDO ought to be used instead.
  3. I'm assuming you're passing the NULL for a primary key on the coordinates table. Don't do that, instead, mark it as auto increment and specify your columns explicitly in SQL.
  4. What is the create table statement for the coordinates table? Paste the results of SHOW CREATE TABLE coordinates into your question. I suspect you're passing a value of null in a column that's a primary key and can never be null.

Upvotes: 1

Nick
Nick

Reputation: 3494

You can submit the mLatand mLongvariables to the server using the code below:

String storeURL = "http://www.yourdomain.com/yourscript.php?lat=" + mLat + "&long=" + mLong;

URL getURL;
getURL = new URL(storeURL);

URLConnection connection = getURL.openConnection();
connection.connect();

InputStream input = new BufferedInputStream(getURL.openStream());
OutputStream output = new ByteArrayOutputStream();          
byte data[] = new byte[1024];

while ((count = input.read(data)) != -1) {
 output.write(data, 0, count);
}

output.flush();
output.close();
input.close();

String downloadResult = output.toString();
Log.i("LOG", downloadResult); //Your php-script can, for example, "echo("OK");" if the storing was successful

You still need to take care of error-handling (no network connection, etc.), of course.

Upvotes: 1

Related Questions