从Android将数据插入MySQL

时间:2015-02-15 11:53:44

标签: php android mysql

我无法将数据插入MySQL数据库。我还发送了回复Android模块的回复,以显示数据是否已保存。

PHP代码:

   $id = $_POST['Id'];
        $name = $_POST['Name'];
        $email = $_POST['Email'];

        $con = new PDO("mysql:host=localhost;dbname=test", "root", "");

        $query = "Insert into record values ('$id','$name','$email')";
        //$query = "Select * from record";
        $result = $con->query($query);

Android代码:

    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_add_new);

    final EditText Id = (EditText) findViewById(R.id.editText);
    final String id = Id.getText().toString();
    final EditText Name = (EditText) findViewById(R.id.editText2);
    final String name = Name.getText().toString();
    final EditText Email = (EditText) findViewById(R.id.editText3);
    final String email = Id.getText().toString();

    Button SavePush = (Button) findViewById(R.id.button3);
    SavePush.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            DefaultHttpClient httpclient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost("http://10.0.3.2:8080/insert.php");

            try{

                ArrayList NameValuePairs = new ArrayList<NameValuePair>(3);
                NameValuePairs.add(new BasicNameValuePair("Id",id));
                NameValuePairs.add(new BasicNameValuePair("Name", name));
                NameValuePairs.add(new BasicNameValuePair("Email", email));

                httpPost.setEntity(new UrlEncodedFormEntity(NameValuePairs));
                HttpResponse response = httpclient.execute(httpPost);
            }catch (Exception e){e.printStackTrace();}
        }
    });
}

2 个答案:

答案 0 :(得分:0)

将api调用移动到asynctask或thread。你不能在主ui线程中使用它们。

答案 1 :(得分:-1)

首先修改你的php代码,如:

$id = htmlentities($_POST['Id']);
$name = htmlentities($_POST['Name']);
$email = htmlentities($_POST['Email']);
try{
    $con = new PDO("mysql:host=localhost;dbname=test", "root", "");
    $con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}catch(Exception $e){
    echo $e->getMessage();
    die();
}
$query = "INSERT INTO record VALUES('?','?','?')";
$result = $con->prepare($query);
$result =  bindParam(?, $id);
$result =  bindParam(?, $name);
$result =  bindParam(?, $email);
$finalresult = $con->execute($result);