gpt4 book ai didi

php - 根据条件更改元素的显示

转载 作者:可可西里 更新时间:2023-11-01 06:30:39 25 4
gpt4 key购买 nike

我希望用户能够区分他们是否已投票给某事(通过加粗)或尚未投票(未加粗)。

例如:

       Voted For Post     Unvoted forVotes:  77 ↑ ↓             12 ↑ ↓

Here is how my database is set up:

intro

Contains messages

    message_id    intro            user_id      up_vote     10            Voted For Post   5            77     11            Unvoted for      5            12

voting

Contains votes

    Voting_id     message_id_fk      user_id     18             10               5        19             10               3     

users

Contains user names

    first_name    user_id     BOB           5

I don't know how to properly query the database then make the proper if statement that will distinguish between voted for and unvoted for posts.

Here's what I have so far:

$sql = mysql_query("SELECT * FROM intro
INNER JOIN users ON intro.user_id = users.user_id
ORDER BY `up` DESC ");

echo $row['first_name'] . " " . $row['intro'];

if( ??? ) {
echo "<strong>" . $row['up_vote'] . "</strong>";
} else {
echo $row['up_vote'];
}

有什么想法吗?

最佳答案

左加入投票表,查看是否找到对应项:

SELECT intro.message_id, intro.intro, intro.user_id, intro.up_vote,
IF(Voting.user_id IS NULL, 0, 1) AS has_voted
FROM intro
INNER JOIN users ON intro.user_id = users.user_id
LEFT JOIN Voting ON Voting.message_id_fk=intro.message_id
AND Voting.user_id = 5
ORDER BY `up` DESC

然后在 PHP 中:

if($row['has_voted'){
echo "<strong>".$row['up_vote']."</strong>";
}else {
echo $row['up_vote'];
}

一些解释:

  • 如果未找到匹配的行,LEFT JOINed 表中的列为NULL
  • IF() 是一个函数,如果第一个参数的计算结果为真,则返回第二个参数,否则返回第三个参数。作为一个函数,它可以很容易地在 SELECT 子句中使用
  • 我将 SELECT * 替换为显式选择所需的列,这被认为是最佳实践,在这种情况下是必要的,因为列名不明确
  • 当然,您必须将文字 5 替换为您当前的用户 ID。使用准备好的语句或像这样连接查询:"...Voting.user_id = "。整数($current_user_id)。 “……”

关于php - 根据条件更改元素的显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14530245/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com