I am using the following code to post data from an android app to a PHP script:
public class Upload extends Activity implements OnClickListener {
EditText joke;
Button upload = (Button) findViewById(R.id.bUpload);
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.upload);
upload.setOnClickListener(this);
}
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.bUpload:
uploadJoke();
break;
}
}
private void uploadJoke() {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://xxxx/telejoke.php");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("username", "test"));
nameValuePairs.add(new BasicNameValuePair("joke", joke.getText().toString()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
}
This code sends data to a PHP script, which then sends it on to an SQL database. This data shows up in the SQL database, but if I try something like echo $username it doesn’t show the username when I go to http://xxxx/telejoke.php.
PHP script:
<?php
include 'DBConnect.php';
include 'JokeValidate.php';
$username = $_POST['username'];
$joke = $_POST['joke'];
$dbname = 'Telejoke';
mysql_select_db($dbname);
echo $username. " " . $joke;
if (validate()){
$query = "INSERT INTO jokes (username, joke) VALUES ('$username','$joke')";
mysql_query($query) or die('Error, insert query failed');
}
mysql_close($conn);
?>
Please help. I want to do things to the posted data with PHP besides just send it on to database.
I guess register_globals is off (which is fine)!!!
You have to address username via $_POST[‘username’] (of course in telepost.php).
OKAY (after you posted your php-script I think I got it).
You said “after going to http://xxx/telejoke.php i cannot see my username, but the data is uploaded correctly”.
–> Yeah, that behaviour is correct.
You do not pass any POST parameters to your php script, so $_POST[‘username’] is empty.
–> But if you call the script via your application you pass the required POST paramters (username, joke, etc) to your script. So it can write your data correctly in your database.
In addition you should optimize your SQL/script to prevent SQL injection.
A bad user may cause damage to your website (e.g. deleting all jokes, etc…)