I have been successful in creating an authentication using httppost from java Android code through php to mysql. I’m having issues create a new user however. I’ve checked multiple posts from other users, and I think it looks good. Also, I’ve created a simple html form to test the php creation of new user, and that works too.
Any thoughts would be appreciated. Here is my java code and PHP below that. Thanks!
try {
// create new array list
nameValuePairs = new ArrayList<NameValuePair>();
// place them in an array list
nameValuePairs.add(new BasicNameValuePair("username", user));
nameValuePairs.add(new BasicNameValuePair("password", pass));
// add array list to http post
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// assign executed form container to response
response = httpclient.execute(httppost);
// check status code,
if (response.getStatusLine().getStatusCode() == 200) {
// assign response entity to htpp entitiy
entity = response.getEntity();
// chekc if entity is not null
if (entity != null) {
Log.i("RESPONSE",EntityUtils.toString(entity));
Intent intent = new Intent(CreateAccount.this,
MainActivity.class);
startActivity(intent);
// }
// display a taost saying login was a success
Toast.makeText(CreateAccount.this, user,
Toast.LENGTH_SHORT).show();
// }
}
}
} catch (Exception e) {
e.printStackTrace();
// display toast when there is a connection error
Toast.makeText(getBaseContext(), "ConnectionError",
Toast.LENGTH_SHORT).show();
}
PHP Code:
//get form data
$user = mysql_real_escape_string($_POST['user']);
$pass = mysql_real_escape_string($_POST['pass']);
echo "INSERT INTO androidlogin (user, pass) VALUES ('$user','$pass')";
//insert data
$insert = mysql_query("INSERT INTO androidlogin (user, pass) VALUES ('$user','$pass')");
if($insert){
$arr2 = array("user" => $user, "pass" => $pass);
echo json_encode($arr2);
}
When posting values are called “username” and “password” whereas server checks for “user” & “pass”. You have to use the same keys.