3

I am developing an android application that uses the PHP/MySQL to send data from app to server in order to register/login users. I already wrote the Javascript and PHP files to send and receive JSON data an insert it into MySQL database. The problem I have is how to handle different responses from PHP.

Exemple:

<?php

   //decode json object
   $json = file_get_contents('php://input');
   $obj = json_decode($json);

   //variables
   $user_firstname = $obj->{'user_firstname'};
   $user_lastname = $obj->{'user_lastname'};
   $user_email = $obj->{'user_email'};
   $user_password = $obj->{'user_password'};

   if([variables] != null){
      //check for an existing email in db
      mysql_query("Check if email exists");

      if(email exist){
         //pass a response to java file
         return user_exists;
         die();
      }else{
         //success
         return success;
      }
   }

?>

All I want is to handle those different return values in order to interact with the user inside the android app.

vascowhite
  • 18,120
  • 9
  • 61
  • 77
Andrei Stalbe
  • 1,511
  • 6
  • 26
  • 44

2 Answers2

2

I think you should user HTTP response codes for this. For example, your php script will return HTTP 200 - OK when user successfully created and HTTP 409 Conflict when user already exists. This is how RESTfull APIs usually works this. On Android you'll have to check the status code and decide what to do.

DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httpget = new HttpPost("http://www.google.com/");

HttpResponse response = httpclient.execute(httpget);
int statusCode = response.getStatusLine().getStatusCode();
AlexV
  • 3,836
  • 7
  • 31
  • 37
1

You can craft a json response by creating an associative array and passing it to json_encode() which will return a string that you can echo to the java client. Don't forget to set the appropriate Content-Type header using the header() function. It's also a good idea to set the HTTP response code appropriately. I'm picturing something like this:

$responseArray = array('response' => 'success'); // or 'user_exists'
$responseJson = json_encode($responseArray);
header('HTTP/1.1 200 OK'); // or 4xx FAIL_TEXT on failure
header('Content-Type: application/json');
echo $responseJson;

You'll then have to parse this response on the java client.

Community
  • 1
  • 1
Asaph
  • 159,146
  • 25
  • 197
  • 199