我想從基於id的mysql表中刪除一行。應該是相當直接的,這可能很簡單,我做錯了。服務器使用xampp在本地託管。從MySql數據庫刪除用戶使用android
這裏是java異步任務代碼:
private class DeleteUserTask extends AsyncTask<ApiConnector,Long,Boolean> {
@Override
protected Boolean doInBackground(ApiConnector... params) {
// it is executed on Background thread
return params[0].DeleteUser(userId);
}
@Override
protected void onPostExecute(Boolean deleted) {
if (deleted){
AlertDialog.Builder dlgAlert = new AlertDialog.Builder(ViewUsers.this);
dlgAlert.setMessage("User Deleted");
dlgAlert.setTitle("Success");
dlgAlert.setPositiveButton("OK", null);
dlgAlert.setCancelable(true);
dlgAlert.create().show();
}else{
AlertDialog.Builder dlgAlert = new AlertDialog.Builder(ViewUsers.this);
dlgAlert.setMessage("User Not Deleted");
dlgAlert.setTitle("Failed");
dlgAlert.setPositiveButton("OK", null);
dlgAlert.setCancelable(true);
dlgAlert.create().show();
}
}
}
創建並執行的AsyncTask:
final DeleteUserTask asyncDeleteUser = new DeleteUserTask();
asyncDeleteUser.execute(new ApiConnector());
的ApiConnector方法:
public Boolean DeleteUser(int userId){
// URL for getting all customers
String url = "http://192.168.20.107/webservice/deleteUser.php?userId="+userId;
// Get HttpResponse Object from url.
// Get HttpEntity from Http Response Object
HttpEntity httpEntity = null;
try
{
DefaultHttpClient httpClient = new DefaultHttpClient(); // Default HttpClient
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
httpEntity = httpResponse.getEntity();
return true;
} catch (ClientProtocolException e) {
// Signals error in http protocol
e.printStackTrace();
//Log Errors Here
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
並主辦了deleteUser.php文件在服務器上:
<?php
$connection = mysqli_connect("localhost","root","","webservice") or die("Error " . mysqli_error($connection));
$userId =$_REQUEST['userId'];
$sql = "DELETE FROM users WHERE id = '$userId'";
mysqli_query($connection, $sql) or die("Error in Selecting " . mysqli_error($connection));
mysqli_close($connection);
?>
我可以確認java代碼中的userId變量確實保存了正確的int值。
當運行該應用程序,我試圖刪除一個用戶它會得到「成功,用戶刪除」alertdialog但用戶仍然在數據庫中。
兩件事情:第一,你確定你確實需要在''$ userId''那些單引號?其次,您應該真正考慮一些輸入驗證以避免SQL注入。 – deez4h
@bearzed我改變了查詢沒有單引號,但它沒有任何區別。還添加了'$ userId = mysqli_real_escape_string($ connection,$ userId);'將任何特殊字符視爲文字字符。你是這個意思嗎? – mgrantnz