Php 准备声明以检查跟随者是否为';你还没跟在Followee后面吗?

Php 准备声明以检查跟随者是否为';你还没跟在Followee后面吗?,php,pdo,prepared-statement,Php,Pdo,Prepared Statement,我需要检查MySQL数据库,看看跟随者是否已经在跟随跟随者。但我不知道怎么做。我猜我应该使用IF语句。以下是我到目前为止所做的 <?php header('Cache-Control: no-cache, must-revalidate'); include 'pdo.php'; $userid = $_POST['userid']; $currentuserid = $_POST['currentuserid']; $checkexist = "SELECT follow

我需要检查MySQL数据库,看看跟随者是否已经在跟随跟随者。但我不知道怎么做。我猜我应该使用IF语句。以下是我到目前为止所做的

<?php

header('Cache-Control: no-cache, must-revalidate');
include 'pdo.php';

$userid = $_POST['userid'];
$currentuserid = $_POST['currentuserid'];

$checkexist = "SELECT follower, followee FROM follow WHERE followee = :userid";
$checkvalues = [':userid' => $userid];

$query = "INSERT INTO follow (followee, follower) VALUES(:followee, :follower)";
$values = [':followee' => $userid, ':follower' => $currentuserid];

try {
    $stmt = $pdo->prepare($checkexist);
    $stmt->execute($checkvalues);
    $rows = $stmt->fetchall(PDO::FETCH_ASSOC);

    foreach ($rows as $row) {
        if ($row->followee != $currentuserid) {
            if ($row->follower != $userid) {
                $res = $pdo->prepare($query);
                $res->execute($values);
                echo "Successfully followed user";
            }
        } else {
            echo "You can't follow yourself";
        }
    }
} catch (PDOException $e) {
    echo 'Error following user';
    die();
}

您可以将
$userid
$currentuserid
进行比较,确定是第一个?至于检查他们是否已经在跟踪,请更改表以使follower/followee的组合唯一,当您尝试插入新行时,它将拒绝这样做,您可以捕获错误。哇,我不知道您可以这样做!如何更改表以使组合唯一?在表设计中使用唯一键约束。这是否回答了您的问题?指定IGNORE意味着您不希望它因为约束而返回错误-如果您确实希望捕获错误,请不要指定IGNORE。