如何使用php/pdo从MySQL数据库中删除友谊,并检查是否成功


How to delete a friendship from a MySQL db using php/pdo and check if it is successful

我试图从数据库中删除两个用户之间的友谊

友情表很简单:

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)
}