doutang7383
doutang7383
2015-04-20 20:36

将json对象数据发送到android中的远程mysql数据库

I have successfully fetched data from remote database using methods posted on internet.But I'm unable to push (insert) data into the same table. I've added a static counter just to check whether the code reaches the given url, but as expected , it fails.Below is the php file I've saved up in my remote server file manager.

<?php 
$json=$_GET [ 'json']; $json=f ile_get_contents( 'php://input'); 
$obj=json_decode($json);
$conn=mysql_connect( "mydatabasename", "myusername", "mypassword") or die( "error connecting"); 
mysql_select_db( "mydatabasename",$conn)or die("database couldnot connect");
error_reporting(E_ALL);
$tid=$_POST[ 'tid']; 
$name=$_POST[ 'name'];
mysql_query( "insert into mytablename(tid,name) values($tid,$name)");
?>

I took two inputs in the android layout, tid, name and trying to send to remote database. Note : database name and other details have been hidden for security purpose.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

2条回答

  • dongxi2163 dongxi2163 6年前

    if your looking for a clean way ..i suggest you to do something like this : register.php

      <?php
    include('connect.php');
    $response = array();   
    if (isset($_POST['Nom']) && isset($_POST['Prenom']) && isset($_POST['Email'])&& isset($_POST['Mdp'])) { //checking if the required fields are set
    
        $Nom = $_POST['Nom'];//the family name
        $Prenom = $_POST['Prenom']; //last name
        $Email = $db->real_escape_string($_POST['Email']); 
        $Mdp = $db->real_escape_string($_POST['Mdp']);  //the password
    
        if ($res = $db->query("SELECT * FROM `patient` WHERE `Email_p`='$Email' ")) {  
        $row_cnt = $res->num_rows; }
         if($row_cnt>0) {      
            $response["success"] = 0;
            $response["message"] = "Email exists"; }
        if ($row_cnt <1){
        $result = mysqli_query($db,"INSERT INTO `patient`(`Id_p`, `Nom`,  `Prenom`, `Email_p`, `Mdp`) VALUES ('','$Nom','$Prenom','$Email','$Mdp')");
    
        if ($result ) { 
            $response["success"] = 1; // if account created we set success value to 1
            $response["message"] = "account created"; 
        } else {                    
            $response["success"] = 0;
            $response["message"] = "Oops Error"; 
        }}
     }else { 
        $response["success"] = 0;
        $response["message"] = "Fields messing";
    
    
    } 
       echo json_encode($response);
    ?>
    

    in android ... yourActivity.java

      class CreerNouveauCompte extends AsyncTask<String, String, String> {
    
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(inscription.this);
            pDialog.setMessage(getString(R.string.inscriEnCours));
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }
    
        protected String doInBackground(String... args) {
            String nom = edtNom.getText().toString();
            String prenom = edtPrenom.getText().toString();
            String email = edtEmail.getText().toString();
            String mdp = edtMdp.getText().toString();
            JSONObject json;
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("Nom", nom));
            params.add(new BasicNameValuePair("Prenom", prenom));
            params.add(new BasicNameValuePair("Email", email));
            params.add(new BasicNameValuePair("Mdp", mdp));
    
                json= jsonParser.makeHttpRequest(url_register (your url),
                        "POST", params);
            } 
            try {if(json != null && !json.isNull("success")){
                int success = json.getInt("success");
                s2=json.getString("message");
                if (success == 1) { //the acount created
                    Intent intent;
                    SharedPreferences settings = getSharedPreferences("compte", 0);
                    SharedPreferences.Editor editor = settings.edit();
                    editor.putString("nom",edtNom.getText().toString() );
                    editor.putString("prenom",edtPrenom.getText().toString() );
                    editor.putString("email",edtEmail.getText().toString());
                    editor.putString("mdp",edtMdp.getText().toString());
    
                    editor.apply(); 
                        intent = new Intent(inscription.this,MainActivity.class); 
    
                    }
                    startActivity(intent);
                    finish();
                } else {
                }}
            } catch (JSONException e) {
                e.printStackTrace();
            }
    
            return null;
        }
    
        protected void onPostExecute(String file_url) {
            pDialog.dismiss(); 
                 }
    
    }
    
    call it like this
    new CreerNouveauCompte().execute();
    

    the connect.php

     <?php  
    $db = new mysqli('localhost', 'root', '', 'rechmed');  
    mysqli_set_charset($db,'utf8');
    ?>
    //note i use mysqli ..in your case use mysql
    
    点赞 评论 复制链接分享
  • douyi7283 douyi7283 6年前

    Use the code below if you are trying to decode a JSONObject with this format {"tid":"myTidValue", "name":"myNameValue"}

    <?php 
    
    $json=stripslashes($_GET['json']); 
    $obj=json_decode($json, true);
    $conn=mysql_connect( "mydatabasename", "myusername", "mypassword") or die( "error connecting"); 
    mysql_select_db( "mydatabasename",$conn)or die("database couldnot connect");
    error_reporting(E_ALL);
    $tid=$json['tid']; 
    $name=$json['name'];
    mysql_query("insert into mytablename(tid,name) values('$tid','$name')");
    
    ?>
    

    and to decode a JSONArray with this format [{"tid":"myTidValue1", "name":"myNameValue1"}, {"tid":"myTidValue2", "name":"myNameValue2"}] you can use below code

    <?php 
    
    $json=stripslashes($_GET['json']); 
    $obj=json_decode($json, true);
    $conn=mysql_connect( "mydatabasename", "myusername", "mypassword") or die( "error connecting"); 
    mysql_select_db( "mydatabasename",$conn)or die("database couldnot connect");
    error_reporting(E_ALL);
    
    foreach ($json as $data){
        $tid=$data['tid']; 
        $name=$data['name'];
        mysql_query("insert into mytablename(tid,name) values('$tid','$name')");
    }
    ?>
    

    if neither works, post your codes for android

    点赞 评论 复制链接分享