【发布时间】:2016-04-08 22:39:27
【问题描述】:
我的数据库中有一个名为flagged_posts 的表,它包含以下列:
id
thought_id
flagged_by_id
我想要做的是,如果登录用户已经标记了帖子,那么不要让他们再次标记帖子,我试图通过删除锚链接并将其替换为一条消息。
这是我的代码的 sn-p:
<?php
$query = mysqli_query($connect, "SELECT * FROM user_thoughts WHERE added_by='$user' AND shared ='yes' "."ORDER BY id DESC LIMIT {$start}, {$limit}");
while ($row = mysqli_fetch_array($query)) {
$thought_id = $row['id'];
$message_content = $row['message'];
$date_of_msg = $row['post_details'];
$thoughts_by = $row['added_by'];
$attachent = $row['attachment'];
$shared = $row['shared'];
// getting the id of the user who is logged in.
$see_if_flagged_q = mysqli_query($connect, "SELECT id FROM users WHERE username = '$username'");
$getting_deets = mysqli_fetch_assoc ($see_if_flagged_q);
$logged_in_user_id = $getting_deets ['id'];
echo "
<div class='more_options' style='float: right;'>";
$see_if_flagged_q2 = mysqli_query($connect, "SELECT * FROM flagged_posts WHERE flagged_by_id ='$logged_in_user_id' ");
while ($getting_deets2 = mysqli_fetch_assoc ($see_if_flagged_q2)){
$flagged_post_by_id = $getting_deets2 ['flagged_by_id'];
// If the user logged in has not flagged the post, i.e. there is no data in the database ..
// .. which says their user id has flagged this thought_id.. then display the link...
if ($logged_in_user_id == $flagged_post_by_id){
echo "<a href='/inc/flagged_post.php?id=$thought_id'> Flag </a>";
}
// if there is data stating this user has flagged this thought_id, then echo a message
if ($logged_in_user_id != $flagged_post_by_id) {
echo "Flagged";
}
}
echo " </div>";
}
?>
所以假设我以Conor 登录。 Conor 的 id 为 8(从 users 表获得的 ID)。 Conor 标记一个 id 为 209 的帖子(thought_id 来自user_thoughts 表)。所以在我的flagged posts 表中,我将看到以下行:
id: 1
thought_id: 209
flagged_by_id: 8
目前,链接和消息都没有出现。如果我更改我的查询,即$see_if_flagged_q2 = mysqli_query($connect, "SELECT * FROM flagged_posts ");(删除了 WHERE 子句),那么我会收到四次回显消息Flagged(因为flagged_posts 表中有四行,它们在每个帖子上都是回显,甚至那些没有被登录用户标记的。
更新:
首先是更新后的代码:
$see_if_flagged_q2 = mysqli_query($connect, "SELECT * FROM flagged_posts WHERE flagged_by_id = '$logged_in_user_id'");
$test_num = mysqli_num_rows ($see_if_flagged_q2);
$getting_deets2 = mysqli_fetch_assoc ($see_if_flagged_q2);
$flagged_post_by_id = $getting_deets2['flagged_by_id'];
if ($flagged_post_by_id == $logged_in_user_id){
echo "<a href='/inc/flagged_post.php?id=$thought_id'> Flag </a>";
echo $test_num;
}
if ($flagged_post_by_id != $logged_in_user_id) {
echo "Flagged";
}
有了以上内容,现在所有帖子的链接都会出现,即使它们被标记。我已经回显了 $flagged_post_by_id 和 '$logged_in_user_id',它们都回显了 12 的值(users 表中的 Conor 的 ID)。值是正确的,$test_num 返回的行数也是正确的。
【问题讨论】: