没有通过PHP从Json对象获取所有数据到数据库

时间:2014-02-23 11:35:42

标签: php mysql json

我试图通过php将所有Json数据放入我的Mysql数据库中,我在这个json对象中有我所有的手机联系人详细信息,但它只在我的数据库中插入最后一个电话联系人详细信息,请帮助我,因为我有已经发布了一个问题,但没有找到满意的答案。我调试了应用程序,它包含了makehttprequest(.....)函数参数中的所有联系人详细信息,但只将最后一个联系人详细信息插入到数据库中。

我的php代码如下:

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

我在调试应用程序时复制的json对象是:

[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 ]

但它插入了最后一个联系人详细信息,名称= Zafar Abbas,电话= 03016775189,电子邮件= 2但是我想一次性插入所有细节,请帮助我谢谢

AYsync任务类:

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;


    }
}

1 个答案:

答案 0 :(得分:0)

问题在于:

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

您只在循环之后发出请求,这将解释为什么您只有INSERT最后一个值。

在循环中移动请求,以便在每次迭代时执行插入:

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;