【发布时间】:2014-02-23 11:35:41
【问题描述】:
我正在尝试通过 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, 电话=+923336124178, email=2, id=230, name=Yasir Altaf, phone=03215169284, email=2, id=55, name=Zafar Abbas, phone=03016775189, email=2]
但它插入了最后一个联系方式 name=Zafar Abbas, phone=03016775189, email=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 解析器类:
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;
}
}
【问题讨论】:
-
你能举例说明输入是什么吗?例如,
$_POST['name']或$_POST['id']的典型值可能是什么? -
我编辑了我提到我的 json 对象的问题,该对象必须插入到数据库中,但我只插入最后一个细节
-
我看到了您的 JSON 对象,但我不明白您如何通过
$_POST变量传递整个 JSON 对象。当您的表单实际提交时,例如$_POST['name']的值是多少?很有可能...Zafar Abbas。单个字符串。这就是为什么您的 PHP 代码(基于来自$_POST的 4 个字符串输入插入单个记录的代码)看起来不错的原因。更重要的问题是您在$_POST请求中传递了什么。如果要插入多条记录,则应将 json 对象作为字符串作为单个$_POSTvar 传递。 -
这就是我想知道的先生,因为我对 php 编码一无所知,我只想一次性插入所有记录,请给我一个方法,以便我可以做到,请看我添加了有问题的 json 解析器类和异步任务
-
您的问题(目前)不在您的 PHP 代码中。首先,您需要让表单将整个 JSON 对象作为字符串传递到变量中,例如
$_POST['records']。然后,您可以开始编写 PHP 代码来处理该 JSON 对象一次一条记录以进行插入。如果您的问题至少可以从那个起点开始,那么您应该能够在 PHP 方面获得一些帮助。