我已经成功地使用 httppost 从 java Android 代码通过 php 到 mysql 创建了身份验证。但是,我在创建新用户时遇到问题。我检查了其他用户的多个帖子,我认为它看起来不错。另外,我创建了一个简单的 html 表单来测试新用户的 php 创建,这也有效。
任何想法将不胜感激。这是我的java代码和下面的PHP。谢谢!
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代码:
//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);
}