id thread post likes user_id created
id post_id user_id created
这是我的查询,以获取线程$ thread_id:
从$ start到$ next的帖子 $query = "SELECT
post_forum.id,
post_forum.user_id,
post_forum.post,
post_forum.likes,
post_forum.created
FROM post_forum
WHERE post_forum.thread ='{$thread_id}'
ORDER BY post_forum.id DESC LIMIT $start,$next";
我想要做的是获取每个帖子,0
或1
字段值,表示用户$user_id
是否喜欢每个帖子,$user_id
如果可能,在一个查询中询问帖子的用户的ID。
非常感谢,提供任何帮助。
答案 0 :(得分:2)
您需要这样的查询:
SELECT p.id, CASE WHEN l.id IS NULL THEN 0 ELSE 1
FROM post_forum p
LEFT JOIN likes_to_post l
ON l.post_id = p.id
AND l.user_id = ?
这假设您正在使用带参数化查询的PDO。该查询将用户标识作为其唯一参数。
答案 1 :(得分:1)
$query = "SELECT
a.id,
a.user_id,
a.post,
a.likes,
a.created,
IF(b.user_id IS NOT NULL,1,0)
FROM post_forum a
LEFT JOIN likes_to_post b
ON b.user_id=$user_id AND a.id = b.post_id
WHERE a.thread ='{$thread_id}'
ORDER BY a.id DESC LIMIT $start,$next";
这是查询:如果喜欢则会返回1
,如果没有,则返回0
:
但是您应该使用mysqli或PDO来防止安全攻击< / p>
修改强>
Mysqli的例子(我不确定thread_id,我想这是一个数字):
$query = "SELECT
a.id,
a.user_id,
a.post,
a.likes,
a.created,
IF(b.user_id IS NOT NULL,1,0)
FROM post_forum a
LEFT JOIN likes_to_post b
ON b.user_id=? AND a.id=b.post_id
WHERE a.thread ='{?}'
ORDER BY a.id DESC LIMIT ?,?";
//Connect to datatabase
$mysqli = new mysqli($Hostname, $Username, $Password, $DatabaseName);
$stmt = $mysqli->stmt_init();
$stmt->prepare($query);
$stmt->bind_param('iiii', $user_id,$thread_id,$start,$next)
$stmt->execute()
$stmt->store_result();
$result = $stmt->bind_result($id, $user_id, $post, $likes, $created,$liked);
if($stmt->num_rows>0){
while (mysqli_stmt_fetch($stmt)) {
[Do something]
}
}