0

将尽我所能描述我遇到的问题:)

我论坛中的每个主题/主题都代表一张光盘。论坛的注册成员使用一系列复选框(显示在每张光盘旁边)来勾选他们收藏中的每张光盘。当表单是 $_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 中,这确实成功删除了重复的主题 - 但是,它删除了错误的主题。我打勾的光盘不再显示,只留下未打勾的版本。

希望这是有道理的。任何人都可以提供任何见解或想法吗?非常感谢。

4

2 回答 2

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。这是故意的吗?

于 2010-03-01T01:25:48.423 回答
0

我可以看到解决这个问题的两种简单方法:

第一的:

使用两个查询,您将查询分组,第二个来获取用户拥有的所有 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!';
    }
  }
}
于 2010-03-01T01:42:07.007 回答