Android利用html post傳值給php儲存mysql
Android利用html post傳值給php儲存mysql
資料來源:http://charleslin74.pixnet.net/blog/post/435116312
Android程式碼部分
package com.example.user.myapplication;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;
import android.os.Looper;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Thread(new Runnable(){
@Override
public void run() {
Looper.prepare();
// TODO Auto-generated method stub
HttpClient client = new DefaultHttpClient();
HttpPost myPost = new HttpPost("http://你的主機IP/login2.php");
try {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("lat","25.123123"));
params.add(new BasicNameValuePair("lng","140.567567"));
myPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
HttpResponse response = new DefaultHttpClient().execute(myPost);
} catch (Exception e) {
e.printStackTrace();
}
Looper.loop();
}}).start();
}
}
PHP程式碼部分
<?php
$postlat = $_POST['lat'];
$postlng = $_POST['lng'];
echo $getval;
$link=mysql_connect("localhost","test123","test123");
mysql_query("SET NAMES utf8");
mysql_select_db("lightdb",$link);
$sql=mysql_query("insert into latlng(lat,lng) values('$postlat','$postlng')",$link);
mysql_close();
?>