gpt4 book ai didi

php - 当where子句的条件为false时,如何返回true?

转载 作者:行者123 更新时间:2023-11-29 02:17:55 25 4
gpt4 key购买 nike

我有两个这样的表:

// Posts
+----+---------+-----------------+----------+
| id | title | content | amount |
+----+---------+-----------------+----------+
| 1 | title1 | content1 | NULL |
| 2 | title2 | content2 | 1000 |
| 3 | title3 | content3 | 5000 |
| 4 | title4 | content4 | NULL |
| 5 | title5 | content5 | 2000 |
+----+---------+-----------------+----------+
// ^ NULL means that question is free


// Money_Paid
+----+---------+---------+
| id | user_id | post_id |
+----+---------+---------+
| 1 | 123 | 2 |
| 2 | 345 | 5 |
| 3 | 123 | 5 |
+----+---------+---------+

我只想做的事:我的一些帖子不是免费的,任何想看的人都应该付费。现在我需要一个查询来检查当前用户是否支付了该帖子的费用? (仅针对非免费帖子)

select *, 
(select count(1) from Money_paid mp where p.amount is not null and mp.post_id = p.id and mp.user_id = :user_id) paid
from Posts p
where p.id = :post_id

以下是一些示例:(基于当前表格)

$stm->bindValue(":post_id", 2, PDO::PARAM_INT);
$stm->bindValue(":user_id", 123, PDO::PARAM_INT);
// paid column => 1 (the user of '123' can see this post because he paid post's cost)

$stm->bindValue(":post_id", 2, PDO::PARAM_INT);
$stm->bindValue(":user_id", 345, PDO::PARAM_INT);
// paid column => 0 (the user of '345' cannot see this post because he didn't pay post's cost)

$stm->bindValue(":post_id", 5, PDO::PARAM_INT);
$stm->bindValue(":user_id", 345, PDO::PARAM_INT);
// paid column => 1

我的问题是什么? 当帖子空闲时,我的查询输出为 0(当帖子免费时我需要 1)

再次。对于免费帖子和付费用户,我需要 1,对于非付费用户,我需要 0。像这样用 PHP 轻松处理它

if ($result['paid'] == 1) {
// show it
} elas {
// doesn't show it
}

我该如何解决?

最佳答案

我还没有测试过,但我认为如果用户已经付费或帖子是免费的,这将给出 $result['paid'] >= 1 或者 $result['paid '] == 0 如果它不是免费的并且用户没有付费:

SELECT COUNT(*) AS paid FROM Post p, Money_paid mp
WHERE p.amount IS NULL OR (mp.post_id = p.id AND mp.user_id = :user_id)

简而言之,if($result['paid'] == 0) 不显示或者如果你喜欢 if($result['paid'] >= 1) 显示。

根据你的评论获取帖子数据:

SELECT p.title, p.content FROM Post p, Money_paid mp
WHERE p.amount IS NULL OR (mp.post_id = p.id AND mp.user_id = :user_id)

然后使用 num_rows() 或 DB API 中的等效函数来决定是否显示它。

关于php - 当where子句的条件为false时,如何返回true?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36585463/

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