我试图从数据库中删除两个用户之间的友谊
友谊表很简单:
friend_one |friend_two
100 |142
142 |100
这是我有的代码,但是不起作用:
if (!empty($_POST)) {
$remover_id = $_POST['remover_id'];
$removed_id = $_POST['removed_id'];
try {
$query = "DELETE * FROM
`friendships`
WHERE
(friend_one = :remover_id AND friend_two = :removed_id)
OR
(friend_two = :remover_id AND friend_one = :removed_id)
";
$sth = $connection->prepare($query);
$sth->execute(
array(
':remover_id' => $remover_id,
':removed_id' => $removed_id
));
if($sth->rowCount () >=0){
$response["success"] = $http_response_success;
die(json_encode($response));
$connection = null;
} else {
$response["success"] = $http_response_server_error;
$response["message"] = $http_message_server_error;
die(json_encode($response));
$connection = null;
}
} catch (PDOException $ex) {
$response["success"] = $http_response_server_error;
$response["message"] = $http_message_server_error;
die(json_encode($response));
$connection = null;
}
} else {
$response["success"] = $http_response_bad_request;
$response["message"] = $http_message_bad_request;
die(json_encode($response));
$connection = null;
}
首先,我不认为我检查成功的方式是正确的,其次,无论如何,友谊并没有从数据库中删除。
运行此命令时,我会在else语句中发现自己:
if($sth->rowCount () >=0){
$response["success"] = $http_response_success;
die(json_encode($response));
$connection = null;
} else {
$response["success"] = $http_response_server_error;
$response["message"] = $http_message_server_error;
die(json_encode($response));
$connection = null;
}
最佳答案
您的DELETE语句有一个SQL错误
DELETE FROM `friendships` WHERE
(friend_one = :remover_id AND friend_two = :removed_id)
OR
(friend_two = :remover_id AND friend_one = :removed_id)
delete
之后有一个星号,不应有一个星号。 https://dev.mysql.com/doc/refman/5.0/en/delete.html至于检查PDO错误,则不应使用
$sth->rowCount()
。if(!$sth->execute($data)) {
// Error (SQL Error)
}
if($sth->rowCount() > 0) {
// At least 1 record was updated / inserted / deleted / (Possibly Selected)
}