用户点击关注/取消关注按钮后,会出现相同的按钮(因为页面未刷新,如果用户再次点击该按钮,则会弹出错误,因为用户正在尝试访问重复的字段)但是我想要在点击任何按钮后刷新页面这是我对php和所用函数的代码:
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>";
}
}
}
我在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
}
?>
我首先检查用户是否未登录,在这种情况下,只显示一个不执行操作的按钮。否则,如果他已登录但未跟随上传者,则显示以下按钮。否则,如果用户正在关注,则显示取消关注按钮。