gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 13:05:59 24 4
gpt4 key购买 nike

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

友谊表很简单:

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)

删除之后出现了一个星号,而本不应该有这个星号。 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)
}

关于php - 如何使用 php/pdo 从 MySQL 数据库删除友谊并检查是否成功,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22695385/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com