简体   繁体   中英

Not getting all of data from Json object into database through PHP

I am trying to get all the Json data into my Mysql database through php, I have all my phone contacts details in this json object, But It only insert just one last phone contact detail to my database, please help as I have already posted a question but did not find a satisfactory answers. I debugged the application and it contains all of my contact detail in params of makehttprequest(.....)function, but Insert only last contact detail into database.

My php code is given below:

$response = array();

// check for required fields

if (isset($_POST['name']) && isset($_POST['id']) && isset($_POST['phone'])&& isset($_POST['email'])) {

    $id = $_POST['id'];
    $name = $_POST['name'];
    $phone = $_POST['phone'];
    $email = $_POST['email'];

    // include db connect class
    require_once __DIR__ . '/db_connect.php';

    // connecting to db
    $db = new DB_CONNECT();

    // mysql inserting a new row
    $result = mysql_query("INSERT INTO crm(id, name, phone, email) VALUES('$id', '$name', '$phone', '$email')");

    // check if row inserted or not
    if ($result) {
        // successfully inserted into database
        $response["success"] = 1;
        $response["message"] = "Product successfully created.";

        // echoing JSON response
        echo json_encode($response);
    } else {
        // failed to insert row
        $response["success"] = 0;
        $response["message"] = "Oops! An error occurred.";

        // echoing JSON response
        echo json_encode($response);
    }
} else {
    // required field is missing
    $response["success"] = 0;
    $response["message"] = "Required field(s) is missing";

    // echoing JSON response
    echo json_encode($response);
}
?>

My json object Which I copied during debugging the application is:

[id=85, name= , phone= , email=2, id=106, name= , phone= , email=2, id=93, name= , phone= , email=2, id=62, name=., phone=*100#, email=2, id=104, name=00, phone=00, email=2, id=90, name=03005103877, phone=03005103877, email=2, id=26, name=03005580234, phone=03005580234, email=2, id=154, name=Wajaht, phone=+923336124178, email=2, id=230, name=Yasir Altaf, phone=03215169284, email=2, id=55, name=Zafar Abbas, phone=03016775189, email=2 ]

But It it inserted the last contact detail which is name=Zafar Abbas, phone=03016775189, email=2 But I want insert all the detail in one go, please help me Thanks

AYsync task Class:

public  class LoadSavingInDatabase extends AsyncTask<ArrayList<SavingContacts>,String,String>{

      private static final String TAG_SUCCESS = "success";
      private static final String URL = "http://amiranzur.com/android_connect/create_product.php";

      JSONObject jsonObject= null;

      @Override
      protected String doInBackground(ArrayList<SavingContacts>... param) {


          ArrayList<SavingContacts> contactArray = param[0];
          List<NameValuePair> params = new ArrayList<NameValuePair>();
          for(int i = 0; i < contactArray.size(); i++){
              SavingContacts contact = contactArray.get(i);
          params.add(new BasicNameValuePair("id", contact.id));
          params.add(new BasicNameValuePair("name", contact.name));
          params.add(new BasicNameValuePair("phone", contact.phone));
        params.add(new BasicNameValuePair("email" , contact.email ));
          }        
          JSONObject jsonObject= new JSONParser().makeHttpRequest(URL, "POST", params);

      if(jsonObject != null){
          try {
              int success = jsonObject.getInt(TAG_SUCCESS);

              if (success == 1) {

                 Log.d("create","ok2");

                 bool = true;
                Log.d("insert","true" + bool); 
              } else {

              }
          } catch (JSONException e) {
              Log.d("exception","exc "+e);
              Log.d("create","lpc");
          }

      }
      else if(jsonObject == null){
          Log.d("null", "null1");
          bool = false;
      }


          return null;
      }
  }
      protected void onPostExecute(boolean bool){
          if(bool == false)
          Log.d("Insertion failed", "ID already inserted");


      }

Json P arser Class:

    public JSONParser() {

    }

    // function get json from url
    // by making HTTP POST or GET mehtod
    public JSONObject makeHttpRequest(String url, String method,
            List<NameValuePair> params) {

        // Making HTTP request
        try {

            // check for request method
            if(method == "POST"){
                // request method is POST
                // defaultHttpClient
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(url);
                httpPost.setEntity(new UrlEncodedFormEntity(params));

                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();

            }else if(method == "GET"){
                // request method is GET
                DefaultHttpClient httpClient = new DefaultHttpClient();
                String paramString = URLEncodedUtils.format(params, "utf-8");
                Log.d("Hope","Hope 1");
                url += "?" + paramString;
                Log.d("Hope","Hope 2");
                HttpGet httpGet = new HttpGet(url);
                Log.d("Hope","Hope 3");

                HttpResponse httpResponse = httpClient.execute(httpGet);
                Log.d("Hope","Hope 4");
                HttpEntity httpEntity = httpResponse.getEntity();
                Log.d("Hope","Hope 5");
                is = httpEntity.getContent();
            }           

        } catch (UnsupportedEncodingException e) {
            Log.d("ex1","ex1 "+e);
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            Log.d("ex1","ex2 "+e);
            e.printStackTrace();
        } catch (IOException e) {
            Log.d("ex1","ex3 "+e);
            e.printStackTrace();
        }

        try {
            Log.d("Hope","Hope 6");
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            Log.d("Hope","Hope 7");
            sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            Log.d("Hope","Hope 8");
            is.close();
            json = sb.toString();
            Log.d("eee","json"+ json);
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + json);
        }

        //char[] chars = json.toCharArray();
        // try parse the string to a JSON object
        //if(chars[0] != 'D'){
            try {
                jObj = new JSONObject(json);
            } catch (Exception e) {
                Log.e("JSON Parser", "Error parsing data " + e.toString());
            }
        //}
        //else {
        //      Log.d("null","null");
        //  }

    return jObj;


    }
}

The problem is here:

for(int i = 0; i < contactArray.size(); i++){
    SavingContacts contact = contactArray.get(i);
    params.add(new BasicNameValuePair("id", contact.id));
    params.add(new BasicNameValuePair("name", contact.name));
    params.add(new BasicNameValuePair("phone", contact.phone));
    params.add(new BasicNameValuePair("email" , contact.email ));
}        
JSONObject jsonObject= new JSONParser().makeHttpRequest(URL, "POST", params);

You make the request only after the loop,that will explain why you only INSERT the last value.

Move the request inside the loop so that you perform an insert at each iteration:

bool isSuccessful;
for(int i = 0; i < contactArray.size(); i++){
    SavingContacts contact = contactArray.get(i);
    params.add(new BasicNameValuePair("id", contact.id));
    params.add(new BasicNameValuePair("name", contact.name));
    params.add(new BasicNameValuePair("phone", contact.phone));
    params.add(new BasicNameValuePair("email" , contact.email ));
    //INSERT at each iteration
    JSONObject jsonObject= new JSONParser().makeHttpRequest(URL, "POST", params);
    if(jsonObject != null){
        try {
            int success = jsonObject.getInt(TAG_SUCCESS);
            if (success == 1) {
                Log.d("debug", "Contact Id# " + contact.id +" Inserted");
            } else {
                Log.d("debug", "Contact Id# " + contact.id +" FAILED");
            }
            isSuccessful = true;
        } catch (JSONException e) {
            Log.d("exception","exc "+e);
            Log.d("create","lpc");
            isSuccessful = false;
        }
    }else{
        Log.d("debug", "json is null");
        isSuccessful = false;
    }
}        
return isSuccessful;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM