我在将数据从Android应用程序发送到php页面时遇到问题...我在android端有一个按钮,可以带我参加这个活动:
public class Post extends Activity {
public void postData(View v){
//Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.168.1.67/phptester/insertdata.php");
List<BasicNameValuePair> nameValuePairs = new ArrayList<BasicNameValuePair>(4);
try {
// Add your data
nameValuePairs.add(new BasicNameValuePair("id", "1"));
nameValuePairs.add(new BasicNameValuePair("descr", "Fire"));
nameValuePairs.add(new BasicNameValuePair("lat", "1.333"));
nameValuePairs.add(new BasicNameValuePair("lng", "1.333"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
Log.i("postData", response.getStatusLine().toString());
} catch (IOException e) {
Log.e("log_tag", "Error in http connection "+e.toString());
}
}
}
这是我的PHP代码:
<?php
$conn = mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("locationdb", $conn);
if (isset($_POST["id"]) && isset($_POST['descr']) && isset($_POST['lat']) && isset($_POST['lng']))
{
$id = $_POST["id"];
$descr = $_POST["descr"];
$lat = $_POST["lat"];
$lon = $_POST["lon"];
$query = mysql_query("INSERT INTO location (ID, Description, lat, lng) VALUES('6', '$descr', '1.666', '1.666')");
echo "data inserted";
mysql_query($query);
}
else {
echo "Not data was intered ".mysql_error() ;
}
?>
杀死我的问题是该数据库中没有存储数据,我不知道为什么!!!!似乎php无法从Android应用程序获取数据....任何帮助都表示赞赏,并提前感谢..
答案 0 :(得分:1)
这不是一个解决方案,但可以帮助您查看服务器发送回您应用的数据,从而帮助您调试问题。
String response = httpclient.execute(httppost, new BasicResponseHandler());
Log.i("myapp", "Reply from server: " + response);
现在,您从PHP脚本返回echo
的内容将在Android日志中打印出来,这样可以更容易地计算出正在发生的事情。
答案 1 :(得分:0)
尝试一些故障排除(确保logfile
可写):
file_put_contents('logfile', print_r($_POST, true)."\n\n", FILE_APPEND);
还记录数据库中的错误:
$query = 'INSERT INTO ...';
mysql_query($query) or
file_put_contents('logfile', 'DB error: '.mysql_error()."\nQuery: ".$query."\n\n", FILE_APPEND);