0

I am posting String data from an android app I am developing to an SQL database. (MAMP)-Local server

I am able to 'echo' all of the POST data from the PHP to the android app, so I am fairly confident that the java is solid.

Example in php "echo $username;" I get andrewnguyen22 on my android emulator. It works for all of my php variables, so i know that the android POST is working fine.

When I hardcode the $POST information and refresh the php page, the code works fine... But heres the thing that baffles me...

The sql database will not update when using the android application, instead it echos the username. This means that no rows were affected by the php. Can anyone see my error?

Below I have posted my PHP and my Java.

PHP CODE:

require "conn.php";
$username = $_POST["username"];
$fullName = $_POST["fullName"];
$age =$_POST["age"];
$bio =$_POST["bio"];
$year =$_POST["year"];
$gender =$_POST["gender"];
$location =$_POST["location"];
$sql = "UPDATE user_info SET fullName ='$fullName', bio='$bio',age='$age', gender='$gender', location='$location', year='$year' WHERE username = '$username' ";
$do = mysqli_query($conn, $sql);
if(mysqli_affected_rows($conn) >0){
echo 0;
}
else{
   echo $username;
}  

Android App Code

import android.app.AlertDialog;
import android.content.Context;
import android.os.AsyncTask;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;

/**
* Created by andrewnguyen on 10/23/16.
*/

public class EditProfileBackgroundTask extends AsyncTask {
Context ctx;
AlertDialog alertDialog;
public EditProfileBackgroundTask(Context ctx) {
    this.ctx = ctx;
}
@Override
protected void onPreExecute() {
    alertDialog = new AlertDialog.Builder(ctx).create();

    super.onPreExecute();
}

@Override
protected String doInBackground(String... params) {
    String profile_url = "http://10.0.2.2:8888/profile.php";
    String method = params[0];
    if(method.equals("profile")){
        Global global = new Global();
        String fullName = params[1];
        String age = params[2];
        String bio = params[3];
        String gender = params[4];
        String location = params[5];
        String year = params[6];
        String username = params[7];

        try {
            URL url = new URL(profile_url);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            OutputStream OS = httpURLConnection.getOutputStream();
            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(OS, "UTF-8"));
            String data = URLEncoder.encode("username", "UTF-8") + "=" +URLEncoder.encode(username, "UTF-8") +"&"+
                    URLEncoder.encode("fullName", "UTF-8") + "=" +URLEncoder.encode(fullName, "UTF-8") +"&"+
                    URLEncoder.encode("age", "UTF-8") + "=" +URLEncoder.encode(age, "UTF-8") +"&"+
                    URLEncoder.encode("bio", "UTF-8") + "=" +URLEncoder.encode(bio, "UTF-8") +"&"+
                    URLEncoder.encode("gender", "UTF-8") + "=" +URLEncoder.encode(gender, "UTF-8") +"&"+
                    URLEncoder.encode("year", "UTF-8") + "=" +URLEncoder.encode(year, "UTF-8") +"&"+
                    URLEncoder.encode("location", "UTF-8") + "=" +URLEncoder.encode(location, "UTF-8");

            bufferedWriter.write(data);
            bufferedWriter.flush();
            bufferedWriter.close();
            OS.close();
            InputStream IS = httpURLConnection.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(IS, "iso-8859-1"));
            String response = "";
            String line = "";
            while ((line = bufferedReader.readLine())!=null){
                response+=line;
            }

            bufferedReader.close();
            IS.close();
            httpURLConnection.disconnect();
            return response;
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    return "Create Profile Failure";
}


@Override
protected void onProgressUpdate(Void... values) {
    super.onProgressUpdate(values);
}

@Override
protected void onPostExecute(String result) {
    if (result .equals("0")) {
        super.onPostExecute(result);

        alertDialog.setMessage("YAY");
        alertDialog.show();
    }
    else if (result .equals("1")) {
        alertDialog.setMessage("NO");
        alertDialog.show();

    }
    else{
        alertDialog.setMessage(result);
        alertDialog.show();//THIS IS WHERE I CAN SEE THE RESULT andrewnguyen22(as seen in php echo $username)
    }
  }
}

It displays my username correctly on my android emulator... (through the alert dialog if else on post-execute)

Screenshot of result on emulator

Andrew Nguyen
  • 106
  • 11
  • I "echo" the username for debugging purposes only. – Andrew Nguyen Nov 08 '16 at 15:57
  • [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)*** Learn about [prepared](http://en.wikipedia.org/wiki/Prepared_statement) statements for [MySQLi](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php). Even [escaping the string](http://stackoverflow.com/questions/5741187/sql-injection-that-gets-around-mysql-real-escape-string) is not safe! [Don't believe it?](http://stackoverflow.com/q/38297105/1011527) – Jay Blanchard Nov 08 '16 at 15:58
  • Thank you, I am not worried about security as of now. – Andrew Nguyen Nov 08 '16 at 16:00
  • I might just be me, but I can't find any question or problem in this... well.. "question"? I can only see statements like "it works fine".. What is your actual problem here? – M. Eriksson Nov 08 '16 at 16:01
  • I have updated the question. I am trying to update an sql database using an android app. It updates if I hardcode the php, but for some reason it does not update when calling the async task method. I know the data is being posted correctly. – Andrew Nguyen Nov 08 '16 at 16:10
  • Have you checked the error logs? Are you're post data containing any `'` characters? Since you're not escaping the data at all and simply concatenate your queries, it's quite easy to screw the SQL up, if the post contains any illegal (in MySQL's point of view) characters. If you use prepared statements, that won't be an issue... – M. Eriksson Nov 08 '16 at 16:18
  • ...or _at least_ escape your `$_POST`'s with `mysqli_real_escape_string()` (since you don't care about security). – M. Eriksson Nov 08 '16 at 16:23
  • Thanks for the tip. I was thinking the same thing about the php. However, when I hardcode the $username and other variables, it works fine. – Andrew Nguyen Nov 08 '16 at 16:24
  • Sure, but that doesn't tell you anything about the data you're getting from the android. Two things you should do: 1. Use `mysqli_real_escape_string()` and try again. 2. If 1 doesn't work.. check your error log... – M. Eriksson Nov 08 '16 at 16:28
  • Okay, I'll do that right now. – Andrew Nguyen Nov 08 '16 at 16:28
  • Wow. It worked. So simple. I sincerely appreciate it. I would like to submit your answer as the correct answer, but it is a comment. Is this possible? – Andrew Nguyen Nov 08 '16 at 16:36
  • 1
    I hate when people say *"I'm not that far along..."* or *"This site will not be public..."* or *"It's only for school, so security doesn't matter..."*. If teachers and professors are not talking about security from day one, they're doing it wrong. Challenge them. They're teaching sloppy and dangerous coding practices which students will have to unlearn later. I also hate it when folks say, *"I'll add security later..."* or *"Security isn't important now..."* or *"Ignore the security risk..."*. If you don't have time to do it right the first time, when will you find the time to add it later? – Jay Blanchard Nov 08 '16 at 18:59

1 Answers1

1

Since your not escaping your data, a simple ' in any of the posted fields will mess up your concatenated SQL statement. The same goes if a value ends with \. There are probably even more scenarios...

NOTE: Since you already stated that you don't care about security for this script, I'm not gonna preach about the importance of using Prepared Statements. But if anyone else reads this later, use Prepared Statements instead.

Use mysqli_real_escape_string() to escape the inputs, to be sure that a simple character won't mess your statement up.

$username = mysqli_real_escape_string($conn, $_POST["username"]);
$fullName = mysqli_real_escape_string($conn, $_POST["fullName"]);
$age = mysqli_real_escape_string($conn, $_POST["age"]);
$bio = mysqli_real_escape_string($conn, $_POST["bio"]);
// ...do the same for the rest...
M. Eriksson
  • 13,450
  • 4
  • 29
  • 40