I am working on a personal project and I'm trying to create a php script to display a follow button if the logged in session user doesn't already follow the user displayed..
Heres what I've got:
<?php
$query = query("SELECT*FROM following, users WHERE followed_id=" .escape_string($_GET['id'])."
AND user_id=".escape_string($_GET['id'])." AND follower_id =".escape_string($_SESSION['user_id'])."");
confirm($query);
while($row = fetch_array($query)):
if(mysqli_num_rows($query)==0){
$followbutton=<<<DELIMITER
<form method="post" action="">
<input type="hidden" name="followed" value="{$row['user_id']}">
<input type="hidden" name="follower" value="{$_SESSION['user_id']}">
<input class="btn btn-info" type="submit" name="submit" value="follow">
</form>
DELIMITER;
echo $followbutton;
}elseif($row['follower_id'] == $_SESSION['user_id']){
$unfollowbutton=<<<DELIMITER
<form method="post" action="unfollow.php?id={$row['user_id']}">
<input class="btn btn-info" type="submit" value="Unfollow">
</form>
DELIMITER;
echo $unfollowbutton;
}
endwhile; ?>
Here's what query, escape_string, fetch_array and confirm do:
function redirect($location){
header("Location: $location");
}
function query ($sql){
global $connection;
return mysqli_query($connection,$sql);
}
function confirm($result) {
global $connection;
if(!$result){
die("QUERY FAILED ".mysqli_error($connection));
}
}
function escape_string($string){
global $connection;
return mysqli_real_escape_string($connection,$string);
}
function fetch_array($result) {
return mysqli_fetch_array($result);
}
The "following" table only has two columns; followed_id and follower_id. When the user clicks the follow button it passes the logged in user_id as the follower_id and the user_id for the person being followed as the followed_id. Since there wont be any entries if user A hasn't already followed user B I need the button to display only if no results are returned from the query.
SELECT
inSELECT*FROM following