-1

I am trying to insert a row into my msql database through wamp server. The database is on the localhost.

I am using android stuido as the ide and don't get any errors or warnings in the log. I couldn't find what's wrong with my code. I'm guessing that the problem is whether with httpclient or php files because new username and password is successfully passed on to NewProductActivty.java. How to fix this issue?

Here is my java and php code:

functions.php:

<?php
$DB_HOST = "localhost";
$DB_DATABASENAME = "kimnerede";
$DB_USERNAME = "root";
$DB_PASS = "";
define("BASARISIZ", "-1");
define("BASARILI", "1");
define("ARKADAS_BULUNAMADI_ERROR", "-2");
define("ARKADAS_ZATEN_MEVCUT_ERROR", "-3");
define("PROFIL_BULUNAMADI_ERROR", "-4");

function dbConnect() {

    $db = mysqli_connect(DB_HOST, DB_DATABASENAME, DB_PASS, DB_USERNAME);

    if (!$db)
        return null;

    mysqli_query($db, 'SET NAMES utf8');

    return $db;

    }

Other functions:

function arkadasEkle($db, $name, $pass) {

    $sorgu = "INSERT INTO deneme123 (name, pass) VALUES ('$name', '$pass')";

    if(!mysqli_query($db, $sorgu))
        return false;

    return true;

}
?>

addclient.php:

<?php

//require_once('functions.php'); 

include('functions.php');
if((!isset($_POST['name']) || empty($_POST['name'])) &&
   (!isset($_POST['pass']) || empty($_POST['pass'])))
    die(BASARISIZ);

$name= $_POST['name'];
$pass= $_POST['pass'];

$db = dbConnect();

if(arkadasEkle($db, $name, $pass))
    die(BASARILI);

die(BASARISIZ);

?>

These php files are in C:\wamp\www\kimnerededirectory.

This is the class where the connection and the insertion is made:

public class NewProductActivity extends AsyncTask<String,Void,String>{

    public static final String KIM_NEREDE_BASE_URL = "http://10.0.2.2/kimnerede/";
    public static final String KIM_NEREDE_PROFIL_KAYDET_URL = KIM_NEREDE_BASE_URL + "addclient.php";
    private static final String TAG = "NetworkManager";

    private Context context;

    public NewProductActivity(Context context)
    {
        this.context = context;
    }

    public static String Ekle(String p_name, String p_pass)
    {
        BufferedReader in = null;

        try {

            HttpClient client = new DefaultHttpClient();
            HttpPost request = new HttpPost(KIM_NEREDE_PROFIL_KAYDET_URL);

            List<NameValuePair> parametreList = new ArrayList<NameValuePair>();
            parametreList.add(new BasicNameValuePair("name", p_name));
            parametreList.add(new BasicNameValuePair("pass", p_pass));

            HttpResponse response = client.execute(request);

            in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));


            return in.readLine();
        } catch (Exception e) {
            Log.d(TAG, "Profil kaydedilirken hata olustu", e);
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        return null;

    }

    @Override
    protected String doInBackground(String... params) {

        Ekle(params[0],params[1]);

        return null;
    }
}

This class is called by creating an object in LoginActivity.java:

public void SignUpClicked(View view) {

        new NewProductActivity(this).execute(UserName.getText().toString(),Password.getText().toString());

    }
peterh
  • 9,698
  • 15
  • 68
  • 87
  • 2
    You are vulnerable to [sql injection attacks](http://bobby-tables.com) – Marc B Jun 14 '16 at 20:14
  • You should definitely consider [using PDO](https://phpdelusions.net/pdo) to access your database instead which should help prevent injections – James Shewey Jun 14 '16 at 20:16
  • Try Postman extension in Chrome to check if your PHP is running. – Ozgur Jun 14 '16 at 20:20
  • 2
    **Never store plain text passwords!** Please use PHP's [built-in functions](http://jayblanchard.net/proper_password_hashing_with_PHP.html) to handle password security. If you're using a PHP version less than 5.5 you can use the `password_hash()` [compatibility pack](https://github.com/ircmaxell/password_compat). Make sure that you [don't escape passwords](http://stackoverflow.com/q/36628418/1011527) or use any other cleansing mechanism on them before hashing. Doing so *changes* the password and causes unnecessary additional coding. – Jay Blanchard Jun 14 '16 at 20:25

2 Answers2

0

If you aren't getting any errors, you should make sure that in your php.ini file you have it set to actually display errors:

display_errors = on

Also make sure you have set:

error_reporting = E_ALL & ~E_NOTICE
Community
  • 1
  • 1
James Shewey
  • 222
  • 2
  • 18
0

connection.php

<?php
$connection = mysqli_connect("localhost", "root", "", "kimnerede") or die("unable to connect to the database");
?>

insertData.php

<?php
$name = $_REQUEST['name'];
$pass = $_REQUEST['pass'];

include_once("connection.php");

$query = "INSERT INTO deneme123 (name, pass) VALUES ('$name', '$pass')";
mysqli_query($connection, $query) or die("unable to execute the query");
?>

DBOperations.java

public class DBOperations {
public boolean addDataToDB(String name, String pass){
        try{
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);
            try {
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost("http://www.sample.com/phpfilelocation/insertData.php");
                List<NameValuePair> nameValuePairs = new ArrayList<>();
                nameValuePairs.add(new BasicNameValuePair("name", name));
                nameValuePairs.add(new BasicNameValuePair("pass", pass));
                httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                httpclient.execute(httpPost);
                return true;
            }
            catch (Exception ex) {
               ex.printStackTrace();
               return false;
            }
        }
        catch(Exception e){
            e.printStackTrace();
            return false;
        }
    }
}

Your AsyncTask

public class NewProductActivity extends AsyncTask<String, Void, Boolean>{
String name, pass;
ProgressDialog progressDialog;
DBOperations dbo = new DBOperations():

        public NewProductActivity(String name, String pass){
            this.name = name;
        this.pass = pass;
        }

        @Override
        protected void onPreExecute() {
            progressDialog = ProgressDialog.show(context, "Please wait", "Sending data...", true);
        }

        @Override
        protected Boolean doInBackground(String... params) {
            try{
            boolean added = dbo.addDataToDB(name, pass);
            return added;
        }
        catch(Exception e){
            e.printStackTrace();
            return false;
        }
        }

      @Override
        protected void onPostExecute(Boolean result) {
        if(result){
            Toast.makeText(context, "successfully added.", Toast.LENGTH_SHORT).show();
        }
        else{
            Toast.makeText(context, "failed to add data.", Toast.LENGTH_SHORT).show();
        }

        progressDialog.dismiss();
    }   
}

To run the AsyncTask,

new NewProductActivity("name", "pass").execute();

Add this line to your Manifest file

<uses-permission android:name="android.permission.INTERNET" />
  • Can you tell me in asynctask where the context value is declared and why it is used?Which value is passed on to onPostExecute as parameter?Why AsyncTask take parameters? And in InsertData.php why did you use $_REQUEST instead of $_POST? Thank you for your help by the way! – Nusret Özateş Jun 15 '16 at 13:20
  • context is declared in Activity. context = getApplicationContext(); It is used to show the progress dialog & Toast(context is a compulsory parameter in Toast and ProgressDialog) boolean value is the parameter which is used in onPostExecute. if adding data operation was completed, true will return in doInBackground. otherwise, return false. in onPostExecute, check that boolean value if it is true or false. – Sumudu Sahan Weerasuriya Jun 15 '16 at 15:54
  • AsyncTask 1). Params, the type of the parameters sent to the task upon execution. 2). Progress, the type of the progress units published during the background computation. 3). Result, the type of the result of the background computation. refer this:- https://developer.android.com/reference/android/os/AsyncTask.html $_REQUEST is the old one. that can get data via GET or POST – Sumudu Sahan Weerasuriya Jun 15 '16 at 15:54