我会尽力描述我遇到的问题:)
我论坛中的每个主题/主题代表一张光盘。论坛的注册成员使用一系列复选框(每张光盘旁边显示一个复选框)来勾选他们在收藏中的每张光盘。当表单为$ _POST时,它将信息存储在如下表中:
| user_id - disc_id |
+ -------------------- +
| 2 - 571 |
| 2 - 603 |
| 2 - 4532 |
当用户下次查看论坛时,我会在用户拥有的光盘上勾选并禁用复选框。这是使用:
完成的$sql = 'SELECT id, poster, subject, posted, last_post, last_post_id,
last_poster, num_views, num_replies, closed, sticky, moved_to, topicimage,
c.user_id, c.disc_id FROM topics LEFT JOIN collections AS c ON c.disc_id=id
WHERE forum_id='.$id.' ORDER BY sticky DESC;
以上抓取所有光盘,然后使用以下(精简版)代码显示:
$result = $db->query($sql) or error('Unable to fetch topic list '.$sql.'', __FILE__, __LINE__, $db->error());
// If there are topics in this forum
if ($db->num_rows($result))
{
while($ cur_topic = $ db-> fetch_assoc($ result))
{
//如果登录用户ID与当前光盘user_id匹配(即该用户拥有此光盘)
if($ cur_topic ['user_id'] == $ pun_user ['id']){
$ read ='
我拥有这个!';
} else {
$ read ='
我拥有这个!';
}
}
}
这很有效,直到第二个用户将相同的光盘ID添加到他的集合中,例如:
| user_id - disc_id |
+ -------------------- +
| 2 - 571 |
| 2 - 603 |
| 6 - 571 |
这会导致重复的帖子出现在论坛中。一个是正确的勾选(因为我拥有它),另一个没有勾选,虽然它共享所有相同的信息,如主题ID和图像。
我的第一个想法是尝试将GROUP BY c.disc_id添加到SQL,它确实成功删除了重复的主题 - 但是,它正在删除错误的主题。我已经勾选的光盘不再显示,只留下未标记的版本。
希望这是有道理的。任何人都可以提供任何见解或想法? 非常感谢。
答案 0 :(得分:0)
这是猜测,因为我不知道您的架构,但我没有看到您在WHERE子句中指定用户的ID。
之类的如何?
SELECT t.id, t.poster, t.subject, t.posted, t.last_post, t.last_post_id,
t.last_poster, t.num_views, t.num_replies, t.closed, t.sticky,
t.moved_to, t.topicimage, c.user_id, c.disc_id
FROM topics AS t LEFT JOIN collections AS c ON c.disc_id = t.id
WHERE forum_id = '.$id.'
AND c.user_id = '.$user_id.'
ORDER BY t.sticky DESC;
此外,您正在加入主题ID =光盘ID。这是故意的吗?
答案 1 :(得分:0)
我可以看到两种 easy 方式来解决这个问题:
第一
使用两个查询,您可以对查询进行分组,第二个用于获取用户拥有的所有disc_id
第二
第一次查询:
if ($db->num_rows($result)) {
$array = Array();
while ($cur_topic = $db->fetch_assoc($result)) {
$id = $cur_topic['disc_id'];
if (!array_key_exists ($id, $array)) { // allow only result per disc_id
$array[$id] = $cur_topic;
$array[$id]['owned'] = false;
}
// If logged in users ID matches the current discs user_id (i.e if this user owns this disc)
if ($cur_topic['user_id']==$pun_user['id']) // check if one is owned by the user
$array['owned'] = true;
}
foreach ($array as $cur_topic) {
if ($cur_topic['owned']) {
$read = '<br /><input type="checkbox" disabled="disabled" checked="checked" /> <span style="color:#999">I own this!</span>';
} else {
$read = '<br /><input type="checkbox" name="discs[]" value="'.$cur_topic['id'].'" /> I own this!';
}
}
}