After the user hits the follow/unfollow button the same button appears (because the page is not refresh, and if the user clicks on the button again an error will pop since the user is trying to access a duplicate field) However i want the page to refresh after any of the buttons are clicked this is the code i have for both the php and the functions used:
function unfollow($userid, $uploader_id){
if(isset($_POST['unfollow'])){
$con = mysqli_connect('localhost', 'root', '', 'db');
$userid = sanitize($userid);
$uploader_id = sanitize($uploader_id);
//prepare statement
$stmt = $con ->prepare("DELETE FROM follow
WHERE u_id = ? AND uploader_id = ?");
$stmt -> bind_param("ss",$userid, $uploader_id);
if($result = $stmt->execute()){
header("Refresh:0");
echo "<h1 style='clear:left;font-size:15px; color:blue;'>UnFollowed</h1>";
}
}
}
function follow($userid, $uploader_id){
if(isset($_POST['follow']))
{
if(logged_in()){
if($userid != $uploader_id){
$con = mysqli_connect('localhost', 'root', '', 'db');
$userid = sanitize($userid);
$uploader_id = sanitize($uploader_id);
//prepare statement
$stmt = $con ->prepare("INSERT INTO follow (u_id, uploader_id) VALUES (?, ?)");
$stmt -> bind_param("ss",$userid, $uploader_id);
if($result = $stmt->execute()){
header("Refresh:1");
echo "<h1 style='clear:left;font-size:15px; color:blue;'>Followed</h1>";
}
else{
echo "Failed to follow";
}
}// users cant follow themselves
}//if not logged in do this
else{
echo "<h1 style='clear:left;font-size:15px; color:red;'>You have to be logged in to follow</h1>";
}
}
}
I am using it in the following format in php:
<?php
//if the user is not logged in just display a button that send him/her to the login page if clicked
if(!logged_in()){
?>
<form id="follow" style="clear:left;" action="">
<button id="follow_btn" type="submit">Follow</button>
</form>
<?php
}
//if the user is not following the uploader show the follow button
else if(!is_following($session_user_id, $uploaderid)){
?>
<form id="follow" method="POST" style="clear:left;" action="<?php follow($session_user_id, $uploaderid) ?>">
<button id="follow_btn" type="submit" name="follow">Follow</button>
</form>
<?php
//else show the unfollow button
}else{
?>
<form id="follow" method="POST" style="clear:left;" action="<?php unfollow($session_user_id, $uploaderid) ?>">
<button id="follow_btn" type="submit" name="unfollow">UnFollow</button>
</form>
<?php
}
?>
I am first checking if the user is not logged in, in that case just show a follow button that doesnt do a thing. Else if he is logged in but is not following the uploader then show the follow button. Else if the user is following show the unfollow button.