【问题标题】:How do I get categories links from links table where categories in one table matched links in another table"如何从链接表中获取类别链接,其中一个表中的类别与另一表中的链接匹配“
【发布时间】:2012-03-08 00:02:48
【问题描述】:

我是编程新手,碰壁了。我正在尝试构建一个简单的链接站点作为学习 mysql 和 php 的起点。

我有两个表:类别 - 链接

在类别表中,我列出了 35 个类别。 id (int) 自增主键和类别 varchul

在链接中我有 id(int)auto increment 主键、链接名称、url 和描述。

我已经到了可以列出要列出的类别并使用 category?id=$id 为每个类别创建一个 url 的地步。但我无法获取与类别关联的链接以按类别显示。我要么得到所有链接,要么没有链接。我使用过 join、left join、right join,其中 links.categories=categories.categories 。没有任何效果。这是获取类别的代码,我只是不知道如何获取每只猫的链接。谁能指出我正确的方向。

enter code here
    <? include "db.php" ?>
    <?php
    $id = intval($_GET['id']); // force user input to an int
    if(!empty($id)) // if the user input is not empty or 0
    {
    $query = "SELECT * FROM categories WHERE id =  $id  LIMIT 1"; // attempt to select the row for the given id
    $result = mysql_query($query) or die(mysql_error());

    if(mysql_num_rows($result) > 0) // if the categorie was found
    {
    $row = mysql_fetch_assoc($result); // fetch the resultset to an array called $row

    echo $row['categories']; // echo the categories field from the row
    // etc.
    }
    else
    {
    die('Error: Bad ID'); // the categories was not found
    }
    }
    else
    {
    die('Error: Bad ID'); // the id given was not valid
    }
    mysql_close();
    ?>

我希望有人可以提供帮助。提前致谢

【问题讨论】:

    标签: mysql


    【解决方案1】:

    您的设计中的类别和链接之间没有任何关系,这就是您无法获得任何数据的原因。

    1. 如果每个链接只能属于一个类别,则将 categoryid 字段添加到链接表中,然后在链接和类别之间连接时使用该字段。

    2. 如果每个链接可以属于多个类别,那么您需要一个包含 categoryid 和 linkid 列的 categorylinks 表,这两个列都是主键,以防止将同一链接多次分配给同一类别。然后您可以使用此表加入

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多