0

I need to check MySQL database to see if a follower is already following a followee. But I'm not sure how to do it. I'm guessing I should be using IF statements. Here's what I've managed so far;

<?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();
}

What I'm really trying to do is;

First, check that the follower isn't trying to follow themselves (the followee).

Then check that the follower isn't already following the followee.

Finally to insert a record with the follower following the followee.

Dharman
  • 30,962
  • 25
  • 85
  • 135
Meggy
  • 1,491
  • 3
  • 28
  • 63
  • 2
    You can just compare `$userid` and `$currentuserid` for the first one, surely? As for checking whether they're already following, change the table to make the combination of follower / followee unique and when you try to insert the new row, it'll refuse to do so and you can trap the error. – droopsnoot Oct 22 '20 at 17:51
  • Wow I didn't know you could do that! How do I change the table to make the combination unique? – Meggy Oct 22 '20 at 18:09
  • 1
    Use UNIQUE key constraint in your table design. – Dharman Oct 22 '20 at 18:42
  • 1
    Does this answer your question? [Best way to avoid duplicate entry into mysql database](https://stackoverflow.com/questions/2219786/best-way-to-avoid-duplicate-entry-into-mysql-database) – Dharman Oct 22 '20 at 18:43
  • That worked! I constrained the table, removed the first query entirely, and simply used $query = "INSERT IGNORE INTO follow (followee, follower) VALUES(:followee, :follower)"; Now is there any way I can check if the INSERT did IGNORE so that I can echo a message telling the user they already followed? – Meggy Oct 22 '20 at 20:05
  • 1
    Specifying IGNORE means that you don't want it to return an error because of a constraint - if you do want to trap an error, don't specify IGNORE. – droopsnoot Oct 23 '20 at 07:57

0 Answers0