Http帖子请求数据未通过

时间:2016-01-26 05:22:08

标签: php android mysql

我正在尝试将一个简单的post方法插入到数据库中.Below是指出我的错误的代码。

这是发送帖子请求的android代码。我不知道什么是错的,但是没有传递需要插入的参数,并且在数据库中插入了一个空字符串。

的java

 String add = "myName";
 BufferedReader reader = null;
 String text = "";
 Log.d("K2NK", "Connecting....");
 URL url;
 String response = "";
 try {
        url = new URL("http://10.13.210.114/myDatabase/insert.php");
        URLConnection conn =  url.openConnection();

        conn.setDoOutput(true);

        OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());

        wr.write(add);
        wr.flush();

        //get the server response
        reader = new BufferedReader((new InputStreamReader(conn.getInputStream())));
        StringBuilder sb = new StringBuilder();
        String line = null;

        //read server response
        while ((line = reader.readLine()) != null) {
            //append server response in string
            sb.append(line + "\n");
        }
        text = sb.toString();
        Log.d("K2NK", text);

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

            if(reader!=null){
            reader.close();}
        } catch (IOException e) {
            e.printStackTrace();
        }
      }

PHP脚本如下所示将数据插入数据库

PHP

<?php

$name = ($_POST['name']);
$con = new mysqli("localhost", "root", "","syncadapter");

if($con->connect_error){
   die("Connection failed: ".$con->connect_error);
 }

//sql to delete record
$sql="INSERT INTO table_student (name) values ('$name')";

if($con->query($sql)===TRUE){
        echo json_encode("insert successful: name:".$name);
 } else {
        echo json_encode("insert failed");
 }
?>

1 个答案:

答案 0 :(得分:2)

您传递的字符串应为:

String add = "name=myname";

它正在尝试按姓名名称找到一个不存在的Post变量。