Sriram
Sriram

Reputation: 10558

PHP script to take form data from Android app

I am trying to build a basic form on my Android app that takes in name, number and email address from a user and sends it to my website. I have a basic php script on the server side to store those details into a simple csv file. The Android code to send the details to the server:

private void sendCredentials(String name, String number, String emailID) {

//code to send to server should begin here.
        HttpClient hc = new DefaultHttpClient();
        HttpPost hp = new HttpPost("http://www.mywebsite.com/takeDetails.php");

        try {
            // Add your data
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
            nameValuePairs.add(new BasicNameValuePair("name", name));
            nameValuePairs.add(new BasicNameValuePair("number", number));
            nameValuePairs.add(new BasicNameValuePair("email", emailID));
            hp.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            // Execute HTTP Post Request
            HttpResponse response = hc.execute(hp);
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
        } catch (IOException e) {
            // TODO Auto-generated catch block
        }
}

On the server side, the php script:

<?php

 $filename="userCredentials.txt";
 $name = $_POST['name'];
 $number = $_POST['number'];
 $email = $_POST['emailID'];
 $fp = fopen($filename, "a");
 $str = "new," . $name . "," . $number . "," $email . "n";
 fwrite($fp, $str);
 fclose($fp);
 $msg = "<h1> Your data has been saved. </h1>";
 echo $msg; ?>  

My problem:
On the file manager of my website, there is no file called userCredentials.txt that gets created.

My question:
1. Why is userCredentials.txt not created?
2. I have never done any work in PHP before, so is the above code snippet the correct way to go about it?

Upvotes: 0

Views: 1603

Answers (1)

BlitZ
BlitZ

Reputation: 12168

You've forgotten a . (dot) before $email variable, when concatenating. It propaply caused a PARSE_ERROR. So script was skipped.

Change:

$str = "new," . $name . "," . $number . "," $email . "n";

To:

$str = "new," . $name . "," . $number . "," . $email . "n";

If you want to add \n new line character in the end of the line, then you should use PHP_EOL instead of "n" in the end of the $str.

Upvotes: 1

Related Questions