當我收到來自PHP頁面的響應時,將其存儲在Java中的字符串變量中,並嘗試將它與相同的字符串進行比較鍵入,它由於某種原因返回false。從PHP響應接收到一個字符串時,兩個相同的字符串返回false
我想做一個登錄類,驗證只是如果用戶的詳細信息存儲在MySQL上。
即使響應包含相同的內容,該if("User Found".equals(response))
語句也會返回false。
這裏是Java和PHP代碼:
void login(){
try{
httpclient=new DefaultHttpClient();
httppost= new HttpPost("http://192.200.10.100:8080/login.php"); // make sure the url is correct.
//add your data
nameValuePairs = new ArrayList<NameValuePair>(2);
// Always use the same variable name for posting i.e the android side variable name and php side variable name should be similar,
nameValuePairs.add(new BasicNameValuePair("Name",loginInputs[0])); // $Edittext_value = $_POST['Edittext_value'];
nameValuePairs.add(new BasicNameValuePair("Password",loginInputs[1]));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
//Execute HTTP Post Request
httpresponse=httpclient.execute(httppost);
// edited by James from coderzheaven.. from here....
ResponseHandler<String> responseHandler = new BasicResponseHandler();
response = httpclient.execute(httppost, responseHandler);
System.out.println("Response : " + response);
runOnUiThread(new Runnable() {
public void run() {
tv.setText("Response from PHP : " + response);
dialog.dismiss();
}
});
if("User Found".equals(response)){
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(login.this,"Login Success", Toast.LENGTH_SHORT).show();
}
});
startActivity(new Intent(login.this, MainActivity.class));
}else{
showAlert();
}
}catch(Exception e){
dialog.dismiss();
System.out.println("Exception : " + e.getMessage());
}
}
public void showAlert(){
login.this.runOnUiThread(new Runnable() {
public void run() {
AlertDialog.Builder builder = new AlertDialog.Builder(login.this);
builder.setTitle("Login Error.");
builder.setMessage("User not Found.")
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
AlertDialog alert = builder.create();
alert.show();
}
});
}
的PHP代碼:
<?php
if (isset($_POST['Name']) && isset($_POST['Password'])) {
$name = $_POST['Name'];
$Password = $_POST['Password'];
// include db connect class
require_once __DIR__ . '/connect.php';
// connecting to db
$db = new DB_CONNECT();
$result = mysql_query("SELECT * FROM `userinfo` WHERE Name='$name' AND Password='$Password'");
if (mysql_num_rows($result)>0)
{
echo "User Found";
}
else {
echo "Not Found";
}
}
?>
我讀了很多的建議,並試圖改變很多事情,但未能成功。無論如何,我認爲這是由不匹配的字符串編碼類型引起的問題,但不知道如何解決它。
* PSA:*'mysql_ *'函數[在PHP 5.5中不推薦](http://php.net/manual/en/faq.databases.php#faq.databases.mysql.deprecated)。不建議您編寫新的代碼,因爲這會阻止您將來升級。相反,請使用[MySQLi](http://php.net/manual/en/book.mysqli.php)或[PDO](http://php.net/manual/en/book.pdo.php)和[是一個更好的PHP開發人員](http://jason.pureconcepts.net/2012/08/better-php-developer/)。 –
你好。我在你的文章中修正了代碼格式和個案錯誤。只是你知道,Stack Overflow往往被視爲不是作爲聊天室或論壇;這裏的帖子是爲了後人,所以讀者傾向於讚賞正確使用資金和標點符號。它不一定是完美的,但有時候會鼓勵人們回答':)'。 – halfer
您確定文件末尾/開頭沒有換行符/空格嗎?你可以刪除它或嘗試'response = response.trim();' – Sietse