所以我有一个关注系统,想检查 joe
是否关注 joe
,用户名是唯一的。所以我基本上想阻止用户关注自己。这是我现在拥有的
if($_SESSION['loggedIn'] == true){
$result1 = $con->prepare("SELECT * FROM followers WHERE follow_from = :username AND follow_to = :username");
$result1->bindParam(':username', $follower);
$result1->bindParam(':post_id', $username);
$result1->execute();
$reprint1 = $result1->rowCount();
}
if($reprint1 == 1){
echo 'Error';
exit();
}
elseif($_SESSION['loggedIn'] == true && $reprint1 == 0){
$result = $con->prepare("SELECT * FROM followers WHERE follow_from = :username AND follow_to = :post_id");
$result->bindParam(':username', $follower);
$result->bindParam(':post_id', $username);
$result->execute();
$reprint = $result->rowCount();
}
print_r($reprint);
if($result->rowCount() < 1){
$stmt = $con->prepare("INSERT INTO followers (follow_from, follow_to) VALUES (:ff, :ft)");
$stmt->bindValue(':ff', $follower, PDO::PARAM_STR);
$stmt->bindValue(':ft', $username, PDO::PARAM_STR);
$stmt->execute();
}
else{
echo 'Error';
exit();
}
问题是它返回错误 after insert joe
and joe
into the database.那么我该如何防止这种情况发生呢?
这是我数据库中当前的内容
+-----+-------------+-----------+
| id | follow_from | follow_to |
+-----+-------------+-----------+
| 256 | joe | joe |
+-----+-------------+-----------+
最佳答案
评论有点长。
如果您没有使用 MySQL,您只需向表添加一个check
约束:
check (following_from <> following_to)
唉,MySQL 支持语法,但什么都不做。大多数其他数据库都支持check
约束。
这给您留下了两个选择。首先是在 php 中检查 $follower != $username
。当它们相等时,产生错误或做你想做的事。当它们不相等时,则插入该行。
您还可以使用插入前触发器在数据库中强制执行此操作。
关于php - 检查重复记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24491011/