无法从php脚本中的android中获取发布数据

时间:2016-04-02 20:08:08

标签: php android sql

我正在尝试从androidphp

获取一些用户字段

正在正确填充$mobile_num,但$user_name$latitude$longitude等其他变量仍为空。

<?php

include('ConnectDB.php');
$user_name=$_POST['userName'];
$mobile_num=$_POST['mobileNo'];
$latitude=$_POST['latitude'];
$longitude=$_POST['longitude'];
$status=1;

echo $mobile_num;

$sql = "INSERT INTO user (username,mobileNo,latitude,longitude,status ) VALUES (?,?,?,?,?)";
$stmt = $con->prepare($sql);
$stmt>bind_param("sssss",$user_name,$mobile_num,$latitude,$longitude,$status);$result=$stmt->execute(); 


if($result)
    echo "inserted ". $result ." row/rows";
else
    die('Could not connect: ' . $con->error);

mysqli_close($con);

?>

在对值进行硬编码时,代码会正确插入数据,但post方法无法捕获用户名,纬度,经度值。

这是我的android代码:

 @Override
  protected String doInBackground(String... params) {

    try {

        data= URLEncoder.encode("mobileNo","UTF-8")
                 + "="+URLEncoder.encode(mUser.getMobileNo(),"UTF-8");

        data+= URLEncoder.encode("userName","UTF-8")
                + "="+URLEncoder.encode(mUser.getUsername(),"UTF-8");

        data+= URLEncoder.encode("latitude","UTF-8")
                + "="+URLEncoder.encode(String.valueOf(mUser.getLatitude()),"UTF-8");

        data+= URLEncoder.encode("longitude","UTF-8")
                + "="+URLEncoder.encode(String.valueOf(mUser.getLongitude()),"UTF-8");

    } catch (Exception e)
    {
        Toast.makeText(activityContext, "ERROR: "+e, Toast.LENGTH_LONG).show();
    }

    return insertUserData(data);
}


private String insertUserData(String data)
{
    try
    {
        conn = DBConnection.createConnnection(php_file);
        OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
        writer.write(data);
        writer.flush();

        BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        response = reader.readLine();

    } catch (IOException e) {
        e.printStackTrace();
    }

    return response;
}

我该怎么做才能解决这个问题?

1 个答案:

答案 0 :(得分:0)

当您创建数据字符串时,您需要添加&#39;&amp;&#39;在每个属性之间。不要对“&#39;&amp;&#39;。

进行网址编码。”
 data= URLEncoder.encode("mobileNo","UTF-8")
             + "="+URLEncoder.encode(mUser.getMobileNo(),"UTF-8");

    data+= "&" + URLEncoder.encode("userName","UTF-8")
            + "="+URLEncoder.encode(mUser.getUsername(),"UTF-8");

    data+= "&" + URLEncoder.encode("latitude","UTF-8")

            + "="+URLEncoder.encode(String.valueOf(mUser.getLatitude()),"UTF-8");

    data+= "&" + URLEncoder.encode("longitude","UTF-8")
            + "="+URLEncoder.encode(String.valueOf(mUser.getLongitude()),"UTF-8");