Java 无法使用PHP将行从Android插入MySQL

Java 无法使用PHP将行从Android插入MySQL,java,php,android,mysql,json,Java,Php,Android,Mysql,Json,我试图将数据从android插入MySQL,但它在logcat中没有显示任何错误,而是在应用程序中显示json消息 这是我的PHP脚本 <?php /* * Following code will create a new product row * All product details are read from HTTP Post Request */ require("config.inc.php"); // array for JSON response $respon

我试图将数据从android插入MySQL,但它在logcat中没有显示任何错误,而是在应用程序中显示json消息

这是我的PHP脚本

<?php

/*
 * Following code will create a new product row
 * All product details are read from HTTP Post Request
 */
 require("config.inc.php");
// array for JSON response
$response = array();

// check for required fields
if (isset($_POST['userName']) && isset($_POST['userContact']) && isset($_POST['userAddress']) && isset($_POST['userStore']) && isset($_POST['userRequest'])) {

    $userName = $_POST['userName'];
    $userContact = $_POST['userContact'];
    $userAddress = $_POST['userAddress'];
    $userStore = $_POST['userStore'];
    $userRequest = $_POST['userRequest'];


    // mysql inserting a new row
    $result = mysql_query("INSERT INTO userrequests(userName, contactNumber, userAddress, storeList, requestBody) VALUES('$userName', '$userContact', '$userAddress', '$userStore', '$userRequest')");

    // 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"] = "IsitdispllayingthusOops! 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);
}
?>

我找不到新行无法插入MySQL的原因。

外部应用程序无法使用POST。您必须改用GET。

在这一行中,我已将POST改为GET,JSONObject json=jsonParser.makeHttpRequest LOGIN\u URL,GET,params;但是它给了我这个json消息$response[message]=缺少必需字段;对不起,我对Android开发还不太了解,所以我对API的使用情况一无所知。但是这个改变无论如何都是行不通的,你必须改变一切来使用GET而不是POST。对于PHP部分,只需将$\u POST替换为$\u GET,在Android/Java部分,您必须查阅手册;
public class JSONParser {

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    // constructor
    public JSONParser() {

    }


    public JSONObject getJSONFromUrl(final String url) {

        // Making HTTP request
        try {
            // Construct the client and the HTTP request.
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);

            // Execute the POST request and store the response locally.
            HttpResponse httpResponse = httpClient.execute(httpPost);
            // Extract data from the response.
            HttpEntity httpEntity = httpResponse.getEntity();
            // Open an inputStream with the data content.
            is = httpEntity.getContent();

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            // Create a BufferedReader to parse through the inputStream.
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "utf-8"), 8);

            // Declare a string builder to help with the parsing.
            StringBuilder sb = new StringBuilder();
            // Declare a string to store the JSON object data in string form.
            String line = null;

            // Build the string until null.
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
                Log.i("log_tag","Line reads: " + line);
            }

            // Close the input stream.
            is.close();
            // Convert the string builder data to an actual string.
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // Try to parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // Return the JSON Object.
        return jObj;

    }


    // 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");
                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, "utf-8"), 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());
        }

        // return JSON String
        return jObj;

    }
public class MainActivity extends ActionBarActivity implements View.OnClickListener {

    private EditText userName, userContact, userAddress, userRequest;
    private Spinner userStore;
    private Button mRegister;

    // Progress Dialog
    private ProgressDialog pDialog;

    // JSON parser class
    JSONParser jsonParser = new JSONParser();

    //php login script

    //localhost :
    //testing on your device
    //put your local ip instead,  on windows, run CMD > ipconfig
    //or in mac's terminal type ifconfig and look for the ip under en0 or en1
    // private static final String LOGIN_URL = "http://xxx.xxx.x.x:1234/webservice/register.php";

    //testing on Emulator:
    private static final String LOGIN_URL = "http://10.0.2.2/callarocket/register.php";

    //testing from a real server:
    //private static final String LOGIN_URL = "http://www.yourdomain.com/webservice/register.php";

    //ids
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_MESSAGE = "message";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Spinner dropdown = (Spinner)findViewById(R.id.StoreSpinner);
        String[] items = new String[]{"NZ Mamak", "Indo Shop", "NZ Supermarket"};
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, items);
        dropdown.setAdapter(adapter);

        userName = (EditText)findViewById(R.id.EditName);
        userContact = (EditText)findViewById(R.id.EditContact);
        userAddress = (EditText)findViewById(R.id.EditAddress);
        userStore = (Spinner)findViewById(R.id.StoreSpinner);
        userRequest = (EditText)findViewById(R.id.EditRequest);

        mRegister = (Button)findViewById(R.id.SubmitButton);
        mRegister.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub

        new CreateUser().execute();

    }

    class CreateUser extends AsyncTask<String, String, String> {

        /**
         * Before starting background thread Show Progress Dialog
         * */
        boolean failure = false;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(MainActivity.this);
            pDialog.setMessage("Creating Request...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }

        @Override
        protected String doInBackground(String... args) {
            // TODO Auto-generated method stub
            // Check for success tag
            int success;
            String username = userName.getText().toString();
            String usercontact = userContact.getText().toString();
            String useraddress = userAddress.getText().toString();
            String userstore = userStore.getSelectedItem().toString();
            String userrequest = userRequest.getText().toString();
            try {
                // Building Parameters
                List<NameValuePair> params = new ArrayList<NameValuePair>();
                params.add(new BasicNameValuePair("userName", username));
                params.add(new BasicNameValuePair("userContact", usercontact));
                params.add(new BasicNameValuePair("userAddress", useraddress));
                params.add(new BasicNameValuePair("userStore", userstore));
                params.add(new BasicNameValuePair("userRequest", userrequest));

                Log.d("request!", "starting");

                //Posting user data to script
                JSONObject json = jsonParser.makeHttpRequest(
                        LOGIN_URL, "POST", params);

                // full json response
                Log.d("Login attempt", json.toString());


                // json success element
                success = json.getInt(TAG_SUCCESS);
                if (success == 1) {
                    Log.d("User Created!", json.toString());
                    finish();
                    return json.getString(TAG_MESSAGE);
                }else{
                    Log.d("Login Failure!", json.getString(TAG_MESSAGE));
                    return json.getString(TAG_MESSAGE);

                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return null;

        }
        /**
         * After completing background task Dismiss the progress dialog
         * **/
        protected void onPostExecute(String file_url) {
            // dismiss the dialog once product deleted
            pDialog.dismiss();
            if (file_url != null){
                Toast.makeText(MainActivity.this, file_url, Toast.LENGTH_LONG).show();
            }

        }

    }

}
$response["message"] = "IsitdispllayingthusOops! An error occurred.";