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.