1

I am a beginner in android. I have below php code which creates the api for registration process

<?php
include_once("../includes/connect.php");
define('USE_AUTHENTICATION', 1);
define('USERNAME', 'user');
define('PASSWORD', '123');
error_reporting (E_ALL ^ E_NOTICE);
ini_set( "display_errors", 0);
error_reporting(E_ERROR | E_PARSE);

if ( USE_AUTHENTICATION == 1 ) 
{
    $jsoncnt="";
    $jsoncnt = file_get_contents('php://input');
    if($jsoncnt!="")
    {
        $json_obj_str = stripslashes($jsoncnt);
        $json_obj = json_decode($json_obj_str, true); 
        $name=$json_obj['name'];
        $mobile_no=$json_obj['mobile_no'];
        $gender=$json_obj['gender'];
        $db_check_email=mysql_query("SELECT * FROM `tbl_register` WHERE `name`='".$name."'");
        $count_check_email=mysql_num_rows($db_check_email);
        if($count_check_email>0)
        {
            $jsn['sTATUS']="ERROR";
            $jsn['mSG']="Name already Exist";
        }
        else
        {


            $db_insert=mysql_query("INSERT INTO `tbl_register`(`name`, `mobile`, `gender`) VALUES ('".$name."','".$mobile_no."','".$gender."')");
            $customer_id=mysql_insert_id();
            if(mysql_affected_rows()==1) 
            {
                $jsn['sTATUS']="SUCCESS";
                $jsn['mSG']="Successfully register";
                $jsn['customer_id']="".$customer_id;

            }
        }        
    }
    else
    {
        $jsn['sTATUS']="ERROR";
        $jsn['mSG']="Server Error - data not set properly";
        $jsn['dATA']['customer_id']="";
    }
    $output= json_encode($jsn);
    echo $output;
 } 
 ?>

And below image shows my database table

database table model

I am unable to insert my data to database using above php code. I am stucked in this section. I tried http with namevalue pair and also volley. The data is passing null value.

  • 1
    ***Please [stop using `mysql_*` functions](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php).*** [These extensions](http://php.net/manual/en/migration70.removed-exts-sapis.php) have been removed in PHP 7. Learn about [prepared](http://en.wikipedia.org/wiki/Prepared_statement) statements for [PDO](http://php.net/manual/en/pdo.prepared-statements.php) and [MySQLi](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php) and consider using PDO, [it's really pretty easy](http://jayblanchard.net/demystifying_php_pdo.html). – Jay Blanchard Mar 15 '17 at 17:06
  • 1
    [Little Bobby](http://bobby-tables.com/) says ***[your script is at risk for SQL Injection Attacks.](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php)***. Even [escaping the string](http://stackoverflow.com/questions/5741187/sql-injection-that-gets-around-mysql-real-escape-string) is not safe! – Jay Blanchard Mar 15 '17 at 17:06
  • Can you show us how you make your calls from the android side? – Maxime Claude Mar 15 '17 at 20:21

1 Answers1

0

Thank you for you responses finally i got the answer.

If we are using httpClient. The code will be like

import android.app.Activity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.Toast;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
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.ArrayList;
import java.util.List;

/**
 * Created by ARJUN on 12/15/2016.
 */

public class MainActivity extends Activity implements OnClickListener {
EditText e1,e2,e3,e4;
String name,mobile_no,gender;
ImageView im;
Button b1;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
    this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    setContentView(R.layout.activity_main);
    b1=(Button)findViewById(R.id.submit);
    b1.setOnClickListener(this);

}
@Override
public void onClick(View arg0) {
    // TODO Auto-generated method stub
    name="arjun";
    mobile_no="8891834226";
    gender="male";
    login lo=new login();
    lo.execute();
}
class login extends AsyncTask<Void, Void, Void>
{
    @Override
    protected Void doInBackground(Void... params) {
        // TODO Auto-generated method stub
        InputStream inputStream = null;
        String result = "";
        String url = "http://192.168.137.113/insert/register_api.php";

        try {
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            String json1 = "";
            JSONObject jsonObject = new JSONObject();
            jsonObject.accumulate("name", name);
            jsonObject.accumulate("mobile_no",mobile_no);
            jsonObject.accumulate("gender",gender);
            json1 = jsonObject.toString();
            StringEntity se = new StringEntity(json1);
            httpPost.setEntity(se);
            httpPost.setHeader("Accept", "application/json");
            httpPost.setHeader("Content-type", "application/json");
            HttpResponse httpResponse = httpclient.execute(httpPost);
            inputStream = httpResponse.getEntity().getContent();

            // 10. convert inputstream to string
            if (inputStream != null) {
                result = convertInputStreamToString(inputStream);
                String myJSON = result;
                Toast.makeText(getBaseContext(),myJSON, Toast.LENGTH_SHORT).show();

            } else {
                result = "Did not work!";
            }
        } catch (Exception e) {
            Log.d("InputStream", e.getLocalizedMessage());
        }

        return null;
    }
    @Override
    protected void onPostExecute(Void result) {
        // TODO Auto-generated method stub
        super.onPostExecute(result);
        //Toast.makeText(getBaseContext(),response, Toast.LENGTH_SHORT).show();
    }
}

private static String convertInputStreamToString(InputStream inputStream) throws IOException {
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
    String line = "";
    String result3 = "";
    while ((line = bufferedReader.readLine()) != null)
        result3 += line;

    inputStream.close();
    return result3;
}
}

and if we use volley the code will be like below

/**
  * Created by Arjun on 3/16/2017.
*/

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
import static com.android.volley.VolleyLog.*;

public class VolleyInsert extends AppCompatActivity implements     View.OnClickListener {

private static final String INSERT_URI = "http://192.168.137.113/insert/register_api.php";

public static final String KEY_NAME = "name";
public static final String KEY_MOBILE = "mobile_no";
public static final String KEY_GENDER = "gender";

private Button buttonInsert;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    buttonInsert = (Button) findViewById(R.id.submit);

    buttonInsert.setOnClickListener(this);
}

private void registerUser(){
    RequestQueue rq= Volley.newRequestQueue(this);
    JSONObject jsonBody;
    try {
        jsonBody = new JSONObject();
        jsonBody.put(KEY_NAME, "Arjun");
        jsonBody.put(KEY_MOBILE, "8891834226");
        jsonBody.put(KEY_GENDER, "male");
        final String mRequestBody = jsonBody.toString();

        StringRequest stringRequest = new StringRequest(Request.Method.POST, INSERT_URI, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                Toast.makeText(getBaseContext(),response, Toast.LENGTH_SHORT).show();
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(getBaseContext(),error.toString(), Toast.LENGTH_SHORT).show();
            }
        }) {
            @Override
            public String getBodyContentType() {
                return "application/json; charset=utf-8";
            }

            @Override
            public byte[] getBody() throws AuthFailureError {
                try {
                    return mRequestBody == null ? null : mRequestBody.getBytes("utf-8");
                } catch (UnsupportedEncodingException uee) {
                    wtf("Unsupported Encoding while trying to get the bytes of %s using %s",
                            mRequestBody, "utf-8");
                    return null;
                }
            }
        };
        rq.add(stringRequest);
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

@Override
public void onClick(View v) {
    if(v == buttonInsert){
        registerUser();
    }
}
}