使用Toxi解决方案计算事件数

时间:2013-06-08 22:44:12

标签: php mysql many-to-many

我是mysql的新手。

我想为我的博客开发一个简单的标记系统,并且遇到了制作3个表格的“Toxi”解决方案。

所以,我有3张桌子:

`blog` containing `id` and `title`. 
`blog_tags` containing `id` and `tags_id` and `blog_id`.
`tags` containing `id` and `name`.

tags_id已连接到Internal Relation表格中的idtags。 同样,blog_id已连接到Internal Relation表格中的idblog

所以,当我在我的函数中(我得到与单个博客有关的所有标签的数组)时,我执行一个查询例子(将博客id作为函数中的参数传递),

    $result = mysql_query("SELECT tags_id FROM blog_tags WHERE blog_id = '".$id."'");
    $tags = array();
    if($result === FALSE) {
        die(mysql_error()); // TODO: better error handling
    }
    while($row = mysql_fetch_assoc($result)) {
        $tags[] = I don't know what should come over here?   
    }
    return $tags;

或者在此Toxi实现中是否还有其他方法可以执行查询?

1 个答案:

答案 0 :(得分:0)

更新您需要一个简单的JOIN。您的查询应该看起来像

SELECT bt.tags_id, t.name
  FROM blog_tags bt JOIN tags t
    ON bt.tags_id = t.id
 WHERE bt.blog_id = n -- < n is an id of a blog

这是 SQLFiddle 演示。

现在php非常简单

$sql = "SELECT bt.tags_id, t.name
          FROM blog_tags bt JOIN tags t
            ON bt.tags_id = t.id
         WHERE bt.blog_id = $id";     
$result = mysql_query($sql);
if($result === FALSE) {
    die(mysql_error()); // TODO: better error handling
}
$tags = array();
while($row = mysql_fetch_assoc($result)) {
    $tags[] = $row['name'];  
}
...

旁注:切换到PDO或mysqli。不推荐使用mysql_ *扩展名。在PDO中,您可以使用语法糖fetchAll()。更重要的是学会使用准备好的陈述。现在你的代码容易受到sql注入攻击。

相关问题