1

I am working on a simple app where I sign up new users. - I am using SLIM PHP framework with MySQL on apache local host - I have a MySQL database with table called tbl_user. I have tested my SLIM implementation using CURL - On Client side, I have three EditView fields named fname, email and password and a sign up button - Its simple, when user click sign up button, the db connection should be made and new user should be added in database. Registration is simple w/o any checks. That I am going to implement once I resolve this issue.

Please help. I have searched a lot and could not resolve the errors.

I am getting following errors:

ERROR

This is my actual error now
01-27 08:42:14.981: D/URL read(6739): Slim Application Errorbody{margin:0;padding:30px;font:12px/1.5 Helvetica,Arial,Verdana,sans-serif;}h1{margin:0;font-size:48px;font-weight:normal;line-height:48px;}strong{display:inline-block;width:65px;}

Slim Application Error

The application could not run because of the following error:

Details:

Message: error_log(/var/tmp/php.log) [function.error-log]: failed to open stream: No such file or directory
File: C:\xampp\htdocs\api\index.php
Line: 105

Stack Trace:

#0 [internal function]: Slim::handleErrors(2, 'error_log(/var/...', 'C:\xampp\htdocs...', 105, Array)
01-27 08:42:14.981: D/URL read(6739): #1 C:\xampp\htdocs\api\index.php(105): error_log('SQLSTATE[23000]...', 3, '/var/tmp/php.lo...')
01-27 08:42:14.981: D/URL read(6739): #2 [internal function]: register()
01-27 08:42:14.981: D/URL read(6739): #3 C:\xampp\htdocs\api\Slim\Route.php(392): call_user_func_array('register', Array)
01-27 08:42:14.981: D/URL read(6739): #4 C:\xampp\htdocs\api\Slim\Slim.php(1052): Slim_Route->dispatch()
01-27 08:42:14.981: D/URL read(6739): #5 C:\xampp\htdocs\api\index.php(26): Slim->run()
01-27 08:42:14.981: D/URL read(6739): #6 {main}

RegisterActivity.java(partial)

          class CreateNewUser extends AsyncTask<String, String, String> {

    /**
     * Before starting background thread Show Progress Dialog
     * */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(RegisterActivity.this);
        pDialog.setMessage("Signing Up..");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);

        pDialog.show();
    }

    /**
     * Creating User
     * */
    protected String doInBackground(String... args) {
        String fname = mUsername.getText().toString();
        String email = mEmail.getText().toString();
        String password = mPassword.getText().toString();

        // Building Parameters
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("email", email));
        params.add(new BasicNameValuePair("password", password));
        params.add(new BasicNameValuePair("fname", fname));


        // getting JSON Object
        // Note that create user url accepts POST method
        JSONObject json = jsonParser.makeHttpRequest(url_create_product,
                "POST", params);

        // check log cat from response
        //Log.d("Create Response", json.toString());

        // check for success tag
        try {
            int success = json.getInt(TAG_SUCCESS);

            if (success == 1) {
                // successfully created USER
                Intent i = new Intent(getApplicationContext(), UserHome.class);
                startActivity(i);

                // closing this screen
               // finish();
            } else {
                // failed to create USER
                 // Log.d("No Sign Up.", json.toString());
            }
        } catch(JSONException e){
           // Log.e("log_tag", "Error parsing data "+e.toString());
           // Log.e("log_tag", "Failed data was:\n" + TAG_SUCCESS);
        }

        return null;
    }

    /**
     * After completing background task Dismiss the progress dialog
     * **/
    protected void onPostExecute(String file_url) {
        // dismiss the dialog once done
        pDialog.dismiss();
    }

}

jsonParser.java(partial)

       public JSONObject makeHttpRequest(String url, String method,
        List<NameValuePair> params) {

    // Making HTTP request
    try {

        // check for request method
        if(method == "POST"){
            // request method is POST
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(new UrlEncodedFormEntity(params));

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();

        }else if(method == "GET"){
            // request method is GET
            DefaultHttpClient httpClient = new DefaultHttpClient();
            String paramString = URLEncodedUtils.format(params, "utf-8");
            url += "?" + paramString;
            HttpGet httpGet = new HttpGet(url);

            HttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();
        }           

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        json = sb.toString();
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }

    // try parse the string to a JSON object
    try {
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    // return JSON String
    return jObj;

}

SLIM :index.php

<?php

session_start(); 
require 'Slim/Slim.php';

$app = new Slim();


$app->post('/login', 'login');

$app->post('/register', 'register');

$app->response()->header('Content-Type', 'application/json');

$app->get('/users', 'getUsers');
$app->get('/users/:id', 'getUser');
$app->get('/users/search/:query', 'findByName');
$app->post('/users', 'addUser');
$app->put('/users/:id', 'updateUser');
$app->delete('/users/:id',  'deleteUser');


$app->get('/gametype', 'getgameType');



$app->run();




// AUTHENTICATION START


function login() {
    $request = Slim::getInstance()->request();
    $user = json_decode($request->getBody());
    $email= $user->email;
    $password= $user->password;
    // echo $email;
//   echo $password;
if(!empty($email)&&!empty($password))
    {
        $sql="SELECT email, fname, role FROM tbl_user WHERE email='$email' and password='$password'";
        $db = getConnection();


    try {
        $result=$db->query($sql); 

                if (!$result) { // add this check.
                      die('Invalid query: ' . mysql_error());
                }
        $row["user"]= $result->fetchAll(PDO::FETCH_OBJ);
        $db=null;
        echo json_encode($row);

    } catch(PDOException $e) {
        error_log($e->getMessage(), 3, '/var/tmp/php.log');
        echo '{"error":{"text":'. $e->getMessage() .'}}'; 
    }

    }

} 

// AUTHENTICATION END

//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$



// Register START


function register() {

    $request = Slim::getInstance()->request();
    $user = json_decode($request->getBody());
    $sql = "INSERT INTO tbl_user (email, password, fname) VALUES (:email, :password, :fname)";
    try {
        $db = getConnection();
        $stmt = $db->prepare($sql);  
        $stmt->bindParam("fname", $user->fname);
        $stmt->bindParam("password", $user->password);
        $stmt->bindParam("email", $user->email);
        $stmt->execute();
        $user->id = $db->lastInsertId();
        $db = null;


        print('{"success":1}');

    } catch(PDOException $e) {
        error_log($e->getMessage(), 3, '/var/tmp/php.log');
        echo '{"error":{"text":'. $e->getMessage() .'}}'; 
    }
}

    // Register END

Behavior of APP: After clickng signup buttom...app gets stuck here and crashes as "Unfortunately, yourapp has stopped."..

AppSCREEN

vikas sharma
  • 161
  • 4
  • 13
  • Don't compare strings with `==` . Do if `(method.equals("GET"))` and if `(method.equals("POST"))` instead. – A--C Jan 26 '13 at 03:56
  • A--C, Thanks....I modified my code but the errors..did not go way. Do you know a way to check if I made the connection to remote server successfully or not? – vikas sharma Jan 26 '13 at 04:07
  • I didn't say the issue would be resolved, I was just pointing out one fixable aspect. As for checking, I think your server would be the best indicator of a successful connection (provided the server works properly). – A--C Jan 26 '13 at 04:12
  • Yes got it..thanks for suggesting the improvement...how can I check on the server side? – vikas sharma Jan 26 '13 at 04:27
  • Maybe `echo` on sucess? I don't know PHP, so I can't be of much help. You should also break your code up into parts, start with the basic stuff (such as making the connection) then build up, adding the UI elements, etc. – A--C Jan 26 '13 at 04:37
  • I can connect to my localhost from my emulator' browser – vikas sharma Jan 26 '13 at 05:16
  • @Android_Surfer : you are getting problem in json parsing because json String contain html tags . so u will need to remove all html tags from string before converting it to json. plz edit full String which u are getting in response from server in question to get more help – ρяσѕρєя K Jan 26 '13 at 06:45
  • @ ρяσѕρєя K: Thanks for the reply. Any suggestions on how can I remove html tags. I have tried numerous things on server side but nothing worked. Please advice few suggestions on both java and server side. My json response from server using curl is {"success":1}.. I do not see any html tags. – vikas sharma Jan 26 '13 at 08:02
  • I have narrowed it down to SLIM sending text/html content type. I am trying to figure out how to convert it to application/json – vikas sharma Jan 26 '13 at 21:09
  • I have narrowed my issue to this..I am not sending post variables as json. How can I convert my editview values to post json string? – vikas sharma Jan 27 '13 at 04:15

2 Answers2

0

When the Slim response object is first created, it sets a content type of "text/html".

Maybe in your register() method, you should do something like:

function register()
{
    $request = Slim::getInstance()->request();
    $response = Slim::getInstance()->response();
    $response['Content-Type'] = 'application/json; charset=utf-8';

    /* rest of your function here*/
}
slugster
  • 49,403
  • 14
  • 95
  • 145
  • @slugster: Thanks!!! This has solved the partial problem on server->client communications. Now the issue is client-> server post json. – vikas sharma Jan 27 '13 at 04:17
  • @slugster: I have updated my error. Can you please let me know what is it? – vikas sharma Jan 27 '13 at 08:46
  • The problem is in $stmt->execute(); statement. – vikas sharma Jan 27 '13 at 09:21
  • $request->getBody(); is getting data in this form email=ga&password=ga&fname=ga – vikas sharma Jan 27 '13 at 10:41
  • The error is occurring on line 105 of index.php. The SQLSTATE error seems to be happening around there too. But you have reproduced only the first 35-40 lines here and have provided too little information for anyone to suggest anything. – user1871938 Jan 27 '13 at 13:51
  • I have updated the index.php to show full code. Please take a look. My understanding of the issue is that server is getting POST in the form of **email=xyz@yahoo.com&password=asd&fname=xyz** but it expects in the form of **"{\"fname\":\"xyz\",\"email\":\"xyz@yahoo.com\",\"password\":\"asd\"}"**. But I could be wrong. – vikas sharma Jan 27 '13 at 22:28
  • I can do the same operation by using curl with no problem **curl -v -H "Content-Type:application/json" -X POST http://localhost/api/register -d "{\"email\":\"xyz@yahoo.com\",\"password\":\"asd\",\"fname\":\"xyz\"}"** – vikas sharma Jan 27 '13 at 22:42
  • I have resolved this by modifying my android code to send json to server – vikas sharma Jan 29 '13 at 06:37
0

You error is you dont have this file to write the error error_log(/var/tmp/php.log) [function.error-log]: failed to open stream: No such file or directory create using touch /var/tmp/php.log or via ftp