从应用程序插入MySQL数据库

时间:2016-10-11 19:24:34

标签: android mysql connection

我在一个项目上工作,将值插入MySQL数据库。数据库已创建,insert正在使用phpMyAdmin。 我的Android代码如下所示:

private void insertToDatabase(final String name, final String duration){
    class SendPostReqAsyncTask extends AsyncTask<String, Void, String> {
       @Override
     protected String doInBackground(String... params) {
             String paramUsername = params[0];
             String paramAddress = params[1];


             List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
             nameValuePairs.add(new BasicNameValuePair("name", name));
             nameValuePairs.add(new BasicNameValuePair("duration", duration));

             try {
                  HttpClient httpClient = new DefaultHttpClient();
                  HttpPost httpPost = new HttpPost(
                             "http://x.x.x.x/insertToDB.php");
                  httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                  HttpResponse response = httpClient.execute(httpPost);

                  HttpEntity entity = response.getEntity();

                 } catch (ClientProtocolException e) {

                 } catch (IOException e) {

                 }
             return "success";
                }

                    @Override
            protected void onPostExecute(String result) {
             super.onPostExecute(result);

             Toast.makeText(getActivity().getApplicationContext(), result, Toast.LENGTH_LONG).show();

             textViewResult.setText("Inserted");
                }
           }
       SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask();
       sendPostReqAsyncTask.execute(name, duration);
     }

我使用上面的PHP代码连接到数据库并运行查询以在其中插入值。我在PMA中测试了查询,它运行正常。

<?php
  define('HOST','y.y.y.y');
  define('USER','root');
  define('PASS','password');
  define('DB','db');
  $con = mysqli_connect(HOST,USER,PASS,DB);

  $name = $_POST['name'];
  $duration = $_POST['duration'];

  $sql = "insert into class (name,duration) values ('$name','$duration')";
  if(mysqli_query($con,$sql)){
    echo 'success';
  }
  else{
    echo 'failure';
  }
  mysqli_close($con);
?>

Android应用程序中的函数返回“成功”消息,但在数据库表中没有更改。

System.out: [socket][1] connection /x.x.x.x:80;LocalPort=40809(0)
System.out: [CDS]connect[/x.x.x.x:80] tm:90
System.out: [socket][2:40809] exception
System.out: [CDS]close[40809]
System.out: close [socket][/0.0.0.0:40809]

0 个答案:

没有答案