【发布时间】:2020-02-14 17:10:02
【问题描述】:
我正在处理一个个人项目,我正在尝试创建一个 php 脚本来显示一个关注按钮,如果登录的会话用户尚未关注显示的用户..
这就是我所拥有的:
<?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; ?>
查询、escape_string、fetch_array 和 Confirm 的作用如下:
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);
}
“以下”表只有两列; follow_id 和 follower_id。当用户单击关注按钮时,它会将登录的 user_id 作为 follower_id 传递,并将被关注人的 user_id 作为 follower_id 传递。由于如果用户 A 尚未关注用户 B,则不会有任何条目,因此我需要仅在查询未返回任何结果时才显示该按钮。
【问题讨论】:
-
欢迎来到 SO!请编辑您的问题,以准确说明最小示例(stackoverflow.com/help/minimal-reproducible-example 供参考)中的哪些问题。您当前拥有的内容是否存在错误,或者您想知道如何实现某些特定功能?是否真的有条件没有按预期工作,或者这个问题与输出/提交表单、连接到数据库等有关。
-
错误报告/日志显示什么,关于可能的错误?什么没有按照您想要的方式工作?
-
去掉AND follower_id =".escape_string($_SESSION['user_id'])."") 末尾的双引号
-
另外,尝试在
SELECT*FROM following中的SELECT之后放置空格 -
没有任何错误,我只是无法让它按照我想要的方式运行。如果用户 A 正在关注用户 B,则“取消关注”按钮会正确显示在用户 B 的个人资料上。但是,如果 sql 查询没有返回任何结果,我也希望显示“关注”按钮。
标签: php mysql sql if-statement session