【发布时间】:2016-02-27 16:54:47
【问题描述】:
我正在尝试根据 id 从 mysql 表中删除一行。应该相当直截了当,我做错了可能很简单。服务器使用 xampp 在本地托管。
这里是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();
}
}
}
创建和执行异步任务:
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 值。
运行应用程序时,我尝试删除一个用户,它会显示“成功,用户已删除”警报对话框,但该用户仍在数据库中。
【问题讨论】:
-
两件事:第一,你确定你真的需要
'$userId'上的那些单引号吗?其次,您应该真正考虑一些输入验证以避免 SQL 注入。 -
@bearzed 我已将查询更改为不带单引号,但没有任何区别。还添加了
$userId = mysqli_real_escape_string($connection, $userId);以将任何特殊字符视为文字字符。这是你的意思吗?