php - 检查重复记录

标签 php html mysql sql database

所以我有一个关注系统,想检查 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/

相关文章:

javascript - mysql数据库填充表中的多个搜索选项

php - 如何通过搜索用户并单击其链接来查看用户的个人资料

html - 忽略 CSS 填充

javascript - 使用 Canvas three.js 中的数据创建纹理

php - 如何对从数据库接收的数据运行 Javascript 查询

php - 在 PHP 中检查字符串长度

php - 将 bash 换行符转换为 HTML 换行符;在 BASH 中运行良好,但不能通过 shell_exec

html - 屏幕上的 CSS 中心页面

java - 用百万个条目填充数据库

mysql - 根据同一个表的不同条件,我需要两个不同的列值