-2

I almost tryed everything to solve this problem, but nothing helped me. Here's my code. It returns success : 0 all the time because UPDATE doesn't work somehow. Where is the problem?

PHP File

<?php
include('config.php');

$username = $_POST['username'];
$email = $_POST['email'];

$con = mysqli_connect($host, $username, $password, $database);
$result = mysqli_query($con, "UPDATE `users` SET Username = '$username', PirmasPaleidimas = 0 WHERE Email = '$email'");

if($result) {
    $json['success'] = 1;
} else {
    $json['success'] = 0;
}

mysqli_close($con);
echo json_encode($json);
?>

Android Function :

private class AsyncDataClass extends AsyncTask<String, Void, String> {

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

            HttpParams httpParameters = new BasicHttpParams();
            HttpConnectionParams.setConnectionTimeout(httpParameters, 10000);
            HttpConnectionParams.setSoTimeout(httpParameters, 10000);

            HttpClient httpClient = new DefaultHttpClient(httpParameters);
            HttpPost httpPost = new HttpPost(params[0]);

            String jsonResult = "";
            try {
                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
                nameValuePairs.add(new BasicNameValuePair("username", params[1]));
                nameValuePairs.add(new BasicNameValuePair("email", params[2]));
                httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

                HttpResponse response = httpClient.execute(httpPost);
                jsonResult = inputStreamToString(response.getEntity().getContent()).toString();

            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return jsonResult;
        }
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }
        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            System.out.println("Resulted Value: " + result);
            if(result.equals("")){
                AsyncDataClass asyncRequestObject = new AsyncDataClass();
                asyncRequestObject.execute(serverUrlUsername, username, email);
                return;
            }
            int jsonResult = returnSucces(result);
            if(jsonResult == 0){
                AsyncDataClass asyncRequestObject = new AsyncDataClass();
                asyncRequestObject.execute(serverUrlUsername, username, email);
                System.out.println(username + "      " + email);
                return;
            }
            if(jsonResult == 1) {
                SharedPreferences sharedPreferences = getSharedPreferences("SharedPref", MODE_PRIVATE);
                SharedPreferences.Editor editor = sharedPreferences.edit();
                editor.putString("Username", username);
                editor.putBoolean("Prisijungta", true);
                editor.apply();

                Intent intent = new Intent(PirmasPaleidimas.this, MainActivity.class);
                startActivity(intent);
                finish();
            }

        }
        private StringBuilder inputStreamToString(InputStream is) {
            String rLine = "";
            StringBuilder answer = new StringBuilder();
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            try {
                while ((rLine = br.readLine()) != null) {
                    answer.append(rLine);
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return answer;
        }
    }
    private int returnSucces(String result){
        JSONObject resultObject = null;
        int returnedResult = 0;
        try {
            resultObject = new JSONObject(result);
            returnedResult = resultObject.getInt("success");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return returnedResult;
    }

I call AsyncTask with this

submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                email = getIntent().getStringExtra("Email");
                username = username_text.getText().toString();
                AsyncDataClass asyncRequestObject = new AsyncDataClass();
                asyncRequestObject.execute(serverUrlUsername, username, email);
                System.out.println(username + "      " + email);
            }
        });

Have in mind that System.out.println(); Prints details correctly and Android Monitor doesn't throw any error at all. Everything seems to work properly but my UPDATE function doesn't do what I want to do.

Neimantas Jocius
  • 99
  • 1
  • 1
  • 7
  • Your script is at risk of [SQL Injection Attack](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) Even [if you are escaping inputs, its not safe!](http://stackoverflow.com/questions/5741187/sql-injection-that-gets-around-mysql-real-escape-string) Use [prepared parameterized statements](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php) – RiggsFolly Jul 31 '17 at 10:32
  • Add `ini_set('display_errors', 1); ini_set('log_errors',1); error_reporting(E_ALL); mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);` to the top of your script. This will force any `mysqli_` errors to generate an Exception that you can see on the browser and other errors will also be visible on your browser. – RiggsFolly Jul 31 '17 at 10:33
  • Get your actual error messages by logging [`mysqli_error()`](http://php.net/manual/en/mysqli.error.php). – Qirel Jul 31 '17 at 10:33
  • `} else { $json['success'] = mysqli_error($con); }` – RiggsFolly Jul 31 '17 at 10:34
  • My bad. I called same variable $username before connection and I couldn't connect to mysqli. That was the problem – Neimantas Jocius Jul 31 '17 at 11:08

1 Answers1

-1

Run this code , if there any error let me know - just added concat sql string with single quotes, displayerrors and added mysqli_error so that we can find out the issue.

<?php
ini_set('display_errors',1);
include('config.php');

$username = $_POST['username'];
$email = $_POST['email'];

$json = array();
$con = mysqli_connect($host, $username, $password, $database);
$result = mysqli_query($con, "UPDATE users SET Username = '".$username."', PirmasPaleidimas = 0 WHERE Email = '".$email."'") or die(mysqli_error($con));

if($result) {
    $json['success'] = 1;
} else {
    $json['success'] = 0;
}

mysqli_close($con);
echo json_encode($json);
?>
Farsay
  • 312
  • 1
  • 9
  • Please look up PHP's variable expansion inside a double quoted string literal. There is nothing wrong with the string as the OP had it. – RiggsFolly Jul 31 '17 at 10:39
  • Yes theres nothing wrong . But one should do this in a standard way. The way it is define . – Farsay Jul 31 '17 at 10:44
  • This code is a LONG WAY from secure !!! See my first comment under the question. Your change adds absolutely no security to the script or the query – RiggsFolly Jul 31 '17 at 10:45
  • yes i know that very well, the purpose of my code - is just to know the error so that he could find out issue. so that next time when he post the issue we could find out the solution. Thanks, – Farsay Jul 31 '17 at 10:47
  • If you just want to know the error, see my last comment under the question – RiggsFolly Jul 31 '17 at 10:57
  • My bad. I called same variable $username before connection and I couldn't connect to mysqli. That was the problem – Neimantas Jocius Jul 31 '17 at 11:08