0

I am creating an activity that will update the table "patients" in my database.

When I tried removing the conditions with $_POST method in php and tried putting temporary content on the variables, the result was successful. But when I put the $_POST method again, and run my android app, the result was unsuccessful. Please help me figure it out. Thank you.

This is the code, I'm creating a security questions activity:

import android.os.AsyncTask; import
android.support.v7.app.ActionBarActivity; import android.os.Bundle;
import android.util.Log; import android.view.Menu; import
android.view.MenuItem; import android.widget.ArrayAdapter; import
android.widget.Spinner; import android.widget.EditText; import
android.widget.Button; import android.view.View; import
android.content.Intent; import android.widget.Toast;

import org.json.JSONException; import org.json.JSONObject;

import java.util.HashMap;


public class Securityquestion_Activity extends ActionBarActivity {

    Spinner question;
    EditText answer;
    Button submit;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_securityquestion_);

        question = (Spinner)findViewById(R.id.securityQuestion);
        answer = (EditText)findViewById(R.id.securityAnswer);
        submit = (Button)findViewById(R.id.submit);

        String[] questions = {
                "What's the name of your first pet?",
                "Where's your place of birth?",
                "What's the sum of your birth date and month?",
                "What's your father's middle name?",
                "What's the surname of your third grade teacher?",
                "Who's your first boyfriend/girlfriend?",
                "Who's your first kiss?",
        };
        ArrayAdapter<String> stringArrayAdapter=
                new ArrayAdapter<String>(this,
                        android.R.layout.simple_spinner_dropdown_item,
                        questions);
        question.setAdapter(stringArrayAdapter);
    }

    public void submit(View v){
        String secquestion = question.getSelectedItem().toString();
        String secanswer = answer.getText().toString();
        Bundle extras = getIntent().getExtras();
        String secID;
        if(extras!=null){
            secID = extras.getString("sec_id");
            String[] args = {secquestion, secanswer, secID};
            SaveSecurity saveSecurity = new SaveSecurity();
            saveSecurity.execute(args);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_securityquestion_, menu);
        return true;

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }


    class SaveSecurity extends AsyncTask<String, String, JSONObject>{

        JSONParser jsonParser = new JSONParser();
        private static final String LOGIN_URL = "http://192.168.56.1/dc/security.php";

        private static final String TAG_SUCCESS = "success";
        private static final String TAG_MESSAGE = "message";

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

        @Override
        protected JSONObject doInBackground(String... args) {

            try {

                HashMap<String, String> params = new HashMap<>();
                params.put("secquestion", args[0]);
                params.put("secanswer", args[1]);
                params.put("secID", args[2]);

                Log.d("request", "starting");

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

                if (json != null) {
                    Log.d("JSON result", json.toString());

                    return json;
                }

            }catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(JSONObject json) {

            int success = 0;
            String message = "";

            if (json != null) {
                Toast.makeText(Securityquestion_Activity.this, json.toString(),
                        Toast.LENGTH_LONG).show();

                try {
                    success = json.getInt(TAG_SUCCESS);
                    message = json.getString(TAG_MESSAGE);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            if (success == 1) {
                Log.d("Success!", message);
                Intent go = new Intent(Securityquestion_Activity.this, Home_Activity.class);
                go.putExtra("all_ID","secID");
                finish();
                startActivity(go);

            }
            else if (success == 0) {
                Log.d("Failure", message);
            }
            else{
                Log.d("Failure", message);
            }



        }
    } 
}

This is the php code:

        <?php

    require_once 'connection.php';
    header('Content-Type: application/json');

    //This method here was the one I mentioned above  
    if(isset($_POST["secquestion"])&& isset($_POST["secanswer"])&& isset($_POST["secID"])){
        //These are the variables I tried temporarily changing it's content when I tested the php
        $ptnt_d = $_POST["secID"];
        $scrty_qstn = $_POST["secquestion"];
        $scrty_nswr = $_POST["secanswer"];

        if(!empty($ptnt_d)&&!empty($scrty_qstn)&&!empty($scrty_nswr)){

            $query = "Update patients Set patientsecurity='$scrty_qstn' and patientanswer='$scrty_nswr' WHERE patientid='$ptnt_d'";
            $result = $db->query($query);

            if($result){
                $json['success']=1;
                $json['message']="Security question and answer successfully saved.";
                echo json_encode($json);
            }
            else{
                $json['success']=0;
                $json['message']="Oops! An error occurred.";
                echo json_encode($json);
            }
        }
        else{
            $json['message']="You must complete all required fields.";
            echo json_encode($json);
        }
    }
?>
guipivoto
  • 18,327
  • 9
  • 60
  • 75
Elle
  • 15
  • 6
  • 1
    What does var_dump($_POST); give you? – Tdelang Mar 01 '16 at 15:10
  • Hi, when you're sending the http request from your activity, the value that comes in the $_POST variable is empty? or isn't even send? I'd reccomend you using some [snippet](http://stackoverflow.com/a/33146764/1403997) to send the request and test that isn't something of the server-side. – 4gus71n Mar 01 '16 at 15:11
  • @4gus71n Hi. I've tried the same method in my previous activity and it went well. The json['message'] is responding, only, the respond is unsuccessful, so I thought it would mean that process has undergone the query and if statement, but failed then automatically went to else condition. By the way, I am using JSONParser. – Elle Mar 01 '16 at 15:16
  • @Elle which else the one of "Oops! An error occurred." or the one of "You must complete all required fields."? BTW did you try to log the $query variable content? – 4gus71n Mar 01 '16 at 15:20
  • What do you mean by unsuccessful? PHP returned "Oops! An error occurred"? PHP returned "You must complete all required fields"? Try `$json['message'] = $query;` and verify that your syntax is correct. Is `connection.php` using `mysql_*` functions or PDO? There could be some DB error. My bet is that your Android code is not POSTing to the PHP script. – MonkeyZeus Mar 01 '16 at 15:21
  • @MonkeyZeus Yes, it's returning "Oops! An error occurred" and I've tried doing what you suggested. It displayed the query and the value that's supposed to be in it, meaning, the $_POST method isn't the problem here. And the database connection is okay. – Elle Mar 01 '16 at 15:29
  • Can we see the complete query with real values? Maybe there's a " that's causing the problem – 4gus71n Mar 01 '16 at 15:32
  • 1
    What dbms do you use? Is the `and` really allowed there? – simon Mar 01 '16 at 15:33
  • I find it hard to believe that the DB stuff is "okay" since it's clearly the part giving you issues. Once again; are you using `mysql_*` functions or PDO? And which DBMS are you using? – MonkeyZeus Mar 01 '16 at 15:33
  • I don't use any mysql_* or PDO. @MonkeyZeus – Elle Mar 01 '16 at 15:41
  • Are you even sure your android is hitting the server? Can you check your web server access log and error.log file and confirm http://192.168.56.1/dc/security.php is being hit. Make sure not to confuse hits from your desktop tests with the hits from your Android. –  Mar 01 '16 at 15:44
  • {"message":"Update patients Set patientsecurity='What's the name of your first pet?' and patientanswer='Bachoy' WHERE patientid='007-7992'","success":0} @4gus71n I can't printscreen the log, but that's exactly what it contains. – Elle Mar 01 '16 at 15:45
  • @fiprojects there's nothing in it when I opened it. But I have used this method in my Login Activity and it went well. I think it's not the server. – Elle Mar 01 '16 at 15:47
  • Your issue is the apostrophe in `What's`. Please read up on even the most basic form of escaping SQL syntax or better yet, go for prepared SQL statements; yes, PHP does support such mystical things. – MonkeyZeus Mar 01 '16 at 15:49
  • It's working now. Thanks a lot for your help :D @MonkeyZeus. – Elle Mar 01 '16 at 15:58

1 Answers1

0

You aren't sanitizing your sql query properly:

Update patients Set patientsecurity='What's the name of your first pet?' and patientanswer='Bachoy' WHERE patientid='007-7992'"

Try doing something like $field = mysql_real_scape($_POST['field']);

4gus71n
  • 3,717
  • 3
  • 39
  • 66