0

I'm trying to develop a simple Android application where I store a User's information onto a server. So I've developed the front end of my app, and I've created a MySql database on my server. I've written the PHP scripts required to update the database, and I've written a parser in my Android code to Parse and send data to the server.

The problem is, I'm unable to send parameters from my Android code to my PHP code. I've read numerous questions and answers on SO and many other forums, but nothing seems to work for me. Please help.

I've created an ASync Task that performs the task of sending the data to the server. Here's the code for the Async Task.

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

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    // Creating user
    protected String doInBackground(String... args) {
        String name = user.getName();
        String firstname = user.getFirstName();
        String lastname = user.getLastName();
        String number = user.getNumber();
        String email = user.getEmail();
        String status = user.getStatus();
        String dob = user.getDob();

        // Building Parameters
        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("name", name));
        params.add(new BasicNameValuePair("firstname", firstname));
        params.add(new BasicNameValuePair("number", number));
        params.add(new BasicNameValuePair("lastname", lastname));
        params.add(new BasicNameValuePair("email", email));
        params.add(new BasicNameValuePair("status", status));
        params.add(new BasicNameValuePair("dob", dob));

        JSONObject json = jsonParser.makeHttpRequest(url_create_product,
                "POST", params);

        try {
            int success = json.getInt(TAG_SUCCESS);

            if (success == 1) {
            } else {
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }
    protected void onPostExecute(String file_url) {
    }
}

The 'url_create_product' in the above code is the URL to my server's PHP Create User file, which I'll also include later.

Next is my JSONParser file.

package com.osahub.rachit.osachatting.server;

import android.util.Log;

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.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;

/**
 * Created by Rachit on 13-06-2015.
 */
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> params) {

        // Making HTTP request
        try {

            // check for request method
            if (method == "POST") {
                // request method is POST
                // defaultHttpClient
                DefaultHttpClient httpClient = new DefaultHttpClient();
                /*HttpParams httpParams = httpClient.getParams();
                HttpConnectionParams.setConnectionTimeout(httpParams, 10000);
                HttpConnectionParams.setSoTimeout(httpParams, 10000);*/
                HttpPost httpPost = new HttpPost(url);
                UrlEncodedFormEntity urlEncoded = new UrlEncodedFormEntity(params, "UTF-8");
                httpPost.setEntity(urlEncoded);

                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity entity = httpResponse.getEntity();
                is = entity.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);
                is = httpResponse.getEntity().getContent();
            }

        } 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.substring(json.indexOf("{"), json.lastIndexOf("}") + 1));
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;

    }
}

Lastly, my create_user.php file is below.

create_user.php
<?php


$response = array();

// check for required fields
if (isset($_POST['number'])) {

    $name = $_POST['name'];
    $first_name = $_POST['first_name'];
    $number = $_POST['number'];
    $last_name = $_POST['last_name'];
    $email = $_POST['email'];
    $status = $_POST['status'];
    $dob = $_POST['dob'];

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

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

    // mysql inserting a new row
    $result = mysql_query("INSERT INTO user_info(name, first_name, last_name, number, email, status, dob) VALUES('$name', '$first_name', '$last_name', '$number', '$email', '$status', '$dob')");

    // check if row inserted or not
    if ($result) {
        // successfully inserted into database
        $response["success"] = 1;
        $response["message"] = "User 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);
}
?>

Below is a snapshot of the database structure in the MySQL Database. This is a snapshot of the database structure in the MySQL Database.

The problem with this code is that when I debug it, the query never successfully runs, it always gets the following output "Required field(s) is missing". This means that the number field is missing, but for the sake of the experiment, I've even hard-coded the number in the user object. I really can't understand for the life of me why the params are not getting picked up by the code. Please help.

I tried executing this query directly from my browser to test my php file. http://115.118.217.53:8068/osachat_connect/create_user.php?name=Rayzone&firstname=Ray&number=97179&lastname=zone&email=a@b&status=hoqdy&dob=3/7/89

Even here I got the response

create_user.php {"success":0,"message":"Required field(s) is missing"}
Rachit
  • 3,173
  • 3
  • 28
  • 45
  • 1
    [Your script is at risk for SQL Injection.](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) – Jay Blanchard Jun 17 '15 at 18:23
  • 1
    If you can, you should [stop using `mysql_*` functions](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php). They are no longer maintained and are [officially deprecated](https://wiki.php.net/rfc/mysql_deprecation). Learn about [prepared](http://en.wikipedia.org/wiki/Prepared_statement) [statements](http://php.net/manual/en/pdo.prepared-statements.php) instead, and consider using PDO, [it's really not hard](http://jayblanchard.net/demystifying_php_pdo.html). – Jay Blanchard Jun 17 '15 at 18:23
  • I understand the risk. This is just for educational purposes. I'm trying to figure out why my code isn't working the way it should (considering all risks) – Rachit Jun 17 '15 at 18:25
  • `new UrlEncodedFormEntity(params, "UTF-8");` Try without the utf parameter. – greenapps Jun 17 '15 at 19:55
  • I have, makes no difference. – Rachit Jun 17 '15 at 19:58

1 Answers1

1

Obviously you need better debugging skills, if you get Required field(s) is missing means that the condition following is not met:

if (isset($_POST['number'])) {...}

So you should find out why android is not setting that parameter.

params.add(new BasicNameValuePair("number", number));

log it:

Log.d("mylog", "number = " + number);

Debug in PHP

error_log('**********************DEBUG************************');
ob_start();
var_dump($_POST);
$postBack = ob_get_contents();
ob_end_clean();
error_log($postBack);
error_log('**********************DEBUG************************');

Try my function:

public static String apiCaller(List<NameValuePair> params, url){

    HttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(url);

    String jsonString = null;

    try {
        httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
        HttpResponse response = httpClient.execute(httpPost);
        HttpEntity respEntity = response.getEntity();

        if (respEntity != null) {
            InputStream inputStream =  respEntity.getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    inputStream, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            inputStream.close();

            jsonString = sb.toString();
            Log.d(LOG_TAG, jsonString);

        }
    } catch (UnsupportedEncodingException e) {
        // writing error to Log
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        // writing exception to log
        e.printStackTrace();
    } catch (IOException e) {
        // writing exception to log
        e.printStackTrace();
    }

    return jsonString;
}
meda
  • 45,103
  • 14
  • 92
  • 122
  • I've logged it, I've even tried hard-coding the number. The number is reaching the JSONParser. However, it's not going beyond that. – Rachit Jun 17 '15 at 18:27
  • @user3286614 I just gave you one more tips, see my edit – meda Jun 17 '15 at 18:30
  • I have the feeling that `new UrlEncodedFormEntity(params, "UTF-8");` seems to not be doing it's job. Because I've logged the being received by this statement, and they are exactly as they should be.. – Rachit Jun 17 '15 at 18:31
  • @user3286614 that should not matter isnt it just a number? try my edit suggestion – meda Jun 17 '15 at 18:33
  • `**********************DEBUG************************ [17-Jun-2015 20:34:48 Europe/Berlin] array(0) { } [17-Jun-2015 20:34:48 Europe/Berlin] **********************DEBUG************************` I get this error-log. – Rachit Jun 17 '15 at 18:35
  • wtf? try with `$_REQUEST` instead of `$_POST` – meda Jun 17 '15 at 18:36
  • anything else I can try? I'm pretty desperate, since I've been stuck with this for almost an entire day now. – Rachit Jun 17 '15 at 18:42
  • @user3286614 I dont have time to try your code, try my function see edit – meda Jun 17 '15 at 18:43
  • I've tried using StringEntity as well, didn't work with that either. But I'll still give your function a go. I appreciate the response man. Thank you. :) – Rachit Jun 17 '15 at 18:45
  • One question though, how are you sending your params as a JSONObject? – Rachit Jun 17 '15 at 18:48
  • sorry it was the wrong one, check this one but you have to store the return value to a string then build the json, JSONObject json = new JSONObject(jsonString); – meda Jun 17 '15 at 18:50
  • This is exactly the same code that I'm using right now. – Rachit Jun 17 '15 at 18:51
  • Nope, no difference. Same response. – Rachit Jun 17 '15 at 18:53
  • What are you printing/logging to see the response? json = sb.toString();? – greenapps Jun 17 '15 at 19:01
  • `ob_get_contents`. It does not make sense to put those ob_... statements in that script. Only var_dump($_POST); would do. – greenapps Jun 17 '15 at 19:03
  • It does because how do u log a dump, anyway thats not the issu – meda Jun 17 '15 at 19:04
  • With a php script with only var_dump($_POST); in it. Please explain why you put the ob_... statements in. – greenapps Jun 17 '15 at 19:07
  • thats okay if you view in the browser, but for a network request data to be logged, var_dump only would not be logged, you need to turn output buffering on – meda Jun 17 '15 at 19:11
  • @Meda, I think I figured out the problem. For starters, the variable names in my PHP were incorrect (There shouldn't have been _ in variable names). Also, I used $_GET instead of $_POST. I'm just testing it now. – Rachit Jun 17 '15 at 19:24
  • no luck. Works with the URL but not from within the code. – Rachit Jun 17 '15 at 19:30
  • @greenapps, I was debugging my application with checkpoints. But yes, I was logging json earlier. I probably removed that code while trying to debug random things. – Rachit Jun 17 '15 at 19:35
  • `but for a network request data to be logged, ` ?? Why should it be logged? And where? Sorry i had never seen those ob_ statements before but use var_dump all the time. Just use that statement as only one in a php file and the client will get it as returned page. In the example you will see it logging `json` after json = sb.toString(); – greenapps Jun 17 '15 at 19:35
  • He means using browser and url – meda Jun 17 '15 at 19:47
  • I tried running this URL `http://osachat.ddns.net:8068/osachat_connect/create_user.php?name=Rayzone&firstname=Ray&number=9717043901&lastname=zone&email=a@b&status=hoqdy&dob=3/7/89` and a database entry was made (after I changed my PHP from `$_POST` to `$_GET`). But the query still doesn't get executed when run my android app. – Rachit Jun 17 '15 at 19:48
  • At the moment executing the query is for later. You first should be sure that you receive your parameters in $_POST or $_GET array. – greenapps Jun 17 '15 at 19:53