duanlu9557 2015-02-15 11:53
浏览 99

从Android将数据插入MySQL

I am unable to insert data into my MySQL database. And I also have send reply back to Android Module to show if the data is saved or not.

PHP code:

   $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);

And Android code:

    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条回答 默认 最新

  • dongsuishou8039 2015-02-15 12:01
    关注

    First of all modify your php code like:

    $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);
    
    评论

报告相同问题?

悬赏问题

  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题