当我在网络浏览器中测试我的PHP文件时,我收到消息... {"success":0,"message":"required field(s) is missing"}
。我正在尝试将我的Android应用程序中的数据添加到本地主机上的数据库中,并且不知道缺少的必需字段是什么。
我的完整php是:
<?php
$response = array();
$con=mysql_connect("localhost", "root");
mysql_select_db("independentretailers",$con);
if (isset($_POST['Retail Name']) && isset($_POST['Type of Business']) && isset($_POST['Location'])&& isset($_POST['GPS'])&& isset($_POST['Phone Number'])&& isset($_POST['Email'])&& isset($_POST['Password'])) {
$RetailName = $_POST['Retail Name'];
$TypeofBusiness = $_POST['Type of Business'];
$Location = $_POST['Location'];
$GPS = $_POST['GPS'];
$PhoneNumber = $_POST['Phone Number'];
$Email = $_POST['Email'];
$Password = $_POST['Password'];
$result = mysql_query("INSERT INTO retailer(Retail Name, Type of Business, Location, GPS, Phone Number, Email, Password) VALUES('$RetailName','$TypeofBusiness','$Location','$GPS','$PhoneNumber','$Email ','$Password')");
// check if row inserted or not
if ($result) {
// successfully inserted into database
$response["success"] = 1;
$response["message"] = "Retailer 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 Parse类是: package com.example.independentretailers;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> nameValuePairs) {
// 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(nameValuePairs));
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(nameValuePairs, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// // try parse the string to a JSON object
// try {
// jObj = new JSONObject(json);
// } catch (JSONException e) {
// Log.e("JSON Parser", "Error parsing data " + e.toString());
// }
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
我调用我的php文件的类是:
package com.example.independentretailers;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import com.example.independentretailers.R;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class retailersignup extends Activity {
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
EditText etRetailName, etTypeofBusiness, etLocation, etGPS, etPhoneNumber, etEmail, etPassword;
Button bSave;
private static String url_create_reatiler = "http://10/0.2.2/tutorial2.php";
private static final String TAG_SUCCESS = "success";
// @SuppressLint("NewApi")
@Override
public void onCreate (Bundle savedInstanceState){
super.onCreate(savedInstanceState);
//setup strict mode policy
//StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
//StrictMode.setThreadPolicy(policy);
setContentView(R.layout.retailersignup);
//for Retail name
etRetailName = (EditText) findViewById(R.id.editText1);
//for type of business
etTypeofBusiness = (EditText) findViewById(R.id.editText2);
//for Location
etLocation = (EditText) findViewById(R.id.editText3);
//for GPS
etGPS = (EditText) findViewById(R.id.editText4);
//for Phone Number
etPhoneNumber = (EditText) findViewById(R.id.editText5);
//for email
etEmail = (EditText) findViewById(R.id.editText6);
//for password
etPassword = (EditText) findViewById(R.id.editText7);
//setting up ID for the button
bSave = (Button) findViewById(R.id.button1);
//setting up onclick listener
bSave.setOnClickListener(new View.OnClickListener(){
InputStream is = null;
@Override
public void onClick(View arg0){
new CreateNewRetailer().execute();
}
});
}
class CreateNewRetailer extends AsyncTask<String, String, String>{
protected String doInBackground(String...args){
//storing values inside edit texts inside strings
String RetailName = etRetailName.getText().toString();
String TypeofBusiness = etTypeofBusiness.getText().toString();
String Location = etLocation.getText().toString();
String GPS = etGPS.getText().toString();
String PhoneNumber = etPhoneNumber.getText().toString();
String Email = etEmail.getText().toString();
String Password = etPassword.getText().toString();
//setting name pair values
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
//adding string values inside the name value pairs
nameValuePairs.add(new BasicNameValuePair("Retail Name", RetailName));
nameValuePairs.add(new BasicNameValuePair("Type of Business", TypeofBusiness));
nameValuePairs.add(new BasicNameValuePair("Location", Location));
nameValuePairs.add(new BasicNameValuePair("GPS", GPS));
nameValuePairs.add(new BasicNameValuePair("Phone Number", PhoneNumber));
nameValuePairs.add(new BasicNameValuePair("Email", Email));
nameValuePairs.add(new BasicNameValuePair("Password", Password));
JSONObject json = jsonParser.makeHttpRequest (url_create_reatiler, "POST", nameValuePairs);
//setting up the connection inside the try catch
// check log cat fro response
Log.d("Create Response", json.toString());
try{
//setting up the default client
int success = json.getInt(TAG_SUCCESS);
}
catch(JSONException e){
e.printStackTrace();
}
return null;
}
protected void onPostExcute(String file_url){
pDialog.dismiss();
}
}
}
我已经坚持这个问题几天了,任何帮助都会非常感激。
答案 0 :(得分:0)
在浏览器中测试时,是否在路径中添加了任何参数?如果没有,该文件的输出是正确的。如果你确实添加了参数,这是你得到的输出,你必须看看你添加的参数是否与脚本期望获得的参数一致。
另外,你正在使用那些空间让自己变得更难。请参阅此部分(在代码中依此类推):
if (isset($_POST['Retail Name']) && isset($_POST['Type of Business']) ...
为了便于访问(因此您不必跟踪所有这些空格和标签),您应该使用下划线:
if (isset($_POST['Retail_Name']) && isset($_POST['Type_of_Business']) ...
虽然这是我个人的偏好(我不太确定如何使用空格)。无论如何,您可以像这样添加链接参数:
yourfile.php?零售名称=测试名称和业务类型=测试业务......