我试图修改我的数据库(MySQL
)的值。对于这个问题,我在我的Android
应用程序上使用HttPut
, Slim framework
作为PHP的微框架,XAMPP
用于管理数据库。
问题是它不修改我的数据库,但当我使用response.getStatusLine().getStatusCode()
时,它给了我状态200。
如果我没有理解它,当你收到一个状态200,这是因为请求已经成功。如下所示:status 200 OK
请求成功。
我错过了什么吗?我理解错了吗?为什么数据库没有改变?
注:如果你需要我提供一些代码,请在评论中告诉我。
EDIT:这是我的put
方法在我的PHP script
。
$app->put("/cars/",function() use($app)
{
$name = $app->request->put("name");
$description = $app->request->put("description");
$idCar = $app->request->put("idCar");
try{
$connection = getConnection();
$dbh = $connection->prepare("UPDATE cars SET name = ?, description = ? WHERE idCar = ?");
$dbh->bindParam(1,$name);
$dbh->bindParam(2,$description);
$dbh->bindParam(3,$idCar);
$dbh->execute();
$connection = null;
header("HTTP/1.1 200");
header("Content-Type:application/json; charset=utf-8");
echo json_encode(array('status' => true),JSON_UNESCAPED_UNICODE );
}catch(PDOException $e)
{
echo "Error: " . $e->getMessage();
}
});
编辑2:这是我使用HttpPut
的代码。
class EditCar extends AsyncTask<Void, Integer, Void> {
private Car editCar;
EditCar(Car editCar) {
this.editCar = editCar;
}
protected void onPreExecute() {
}
protected Void doInBackground(Void... params) {
try {
String url = "http://IP of my computer/project/cars/";
HttpClient httpClient = new DefaultHttpClient();
HttpPut method = new HttpPut(url);
List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
nameValuePairList.add(new BasicNameValuePair("name", editCar.getName()));
nameValuePairList.add(new BasicNameValuePair("description", editCar.getDescription()));
nameValuePairList.add(new BasicNameValuePair("idCar", Integer.toString(editCar.getIdCar())));
method.setEntity(new UrlEncodedFormEntity(nameValuePairList));
HttpResponse response = httpClient.execute(method);
} catch (Exception ex) {
Log.e("Error", ex.toString());
}
return null;
}
protected void onProgressUpdate() {
}
protected void onPostExecute() {
}
}
200状态说明不了你的更新。
- 是否选择了正确的数据库连接?
- 您的查询看起来正常,但我看不到参数值。您确定它们包含正确的值吗?
- 可以通过bindParam方法指定数据类型
- 你做'update',所以lastInsertId是'insert'
但是,你可以这样做:
print_r([$name,$description,$idCar]); // temporaly line for debugging!
$dbh = $connection->prepare("UPDATE cars SET name = ?, description = ? WHERE idCar = ?");
$dbh->execute([$name,$description,$idCar]);
如果使用
最后,我得到了解决方案。我不知道如何在我的HttpPut
方法上看到我的应用程序上使用了什么数据,所以通过在互联网上搜索,我终于找到了一种方法来查看正在使用什么数据。内容如下:
在执行响应后,可以输入这两行:
HttpEntity entity = response.getEntity();
String responseText = EntityUtils.toString(entity);
然后你可以看到HttpPut
和Log
发送了什么数据:
Log.d("response",responseText);
使用这个方法,我看到了正在发送的数组,并且它给了我一个错误,它告诉我我cannot add or update a child row
。这是因为$idCar
在另一个表中有一个引用(级联),而我正在发送一个在另一个表上不存在的值。
当我发送一个存在于第二个表中的值时,它会正常工作!
EDIT:要查看你正在使用的值的数组,你必须输入
print_r([$name,$description,$idCar]);
在你的put方法中的php script
上,并在设置变量值之后。这样的:
$name = $app->request->put("name");
$description = $app->request->put("description");
$idCar = $app->request->put("idCar");
print_r([$name,$description,$idCar]);