【问题标题】:not retrieving rows from db after joining tables加入表后不从数据库中检索行
【发布时间】:2013-04-29 07:26:30
【问题描述】:

我一直在为博客创建一个简单的系统,但在加入 2 个表后检索数据库时遇到了一些困难,如下所示:

表名:文章

  • 身份证
  • category_id
  • 标题
  • 留言

表名:类别

  • 身份证
  • 姓名

我想做什么:

  • 加入以上 2 个表格中的信息。
  • 在我的管理面板中检索它们以编辑/删除文章。

我有什么问题: - 如果我使用以下方法加入表格:

$sql = "SELECT * FROM 文章在文章中加入类别.category_id = categories.id

我可以获取所有列,但似乎编辑和删除按钮正在识别类别 id 列,而不是文章 id 列。

我正在使用 foreach 检索数据库,如下面的简历:

<thead> 
    <tr>
        <th class="category">category</th>
        <th class="title">title</th>
        <th class="message">content</th>
        <th class="edit">edit</th>
        <th class="del">del</th>
    </tr>
</thead> 

<?php foreach ($articles as $article): ?>
<tbody> 
    <tr>   
        <td><?php echo h($article["name"]); ?></td>
        <td><?php echo h($article["title"]); ?></td>
        <td><?php echo h($article["message"]); ?></td>
        <td><a href="article_edit.php?id=<?php echo h($article["id"]); ?>"><img src="images/icn_edit.png" title="Edit"></a></td> 
        <td><a href="article_delete.php?id=<?php echo h($article["id"]); ?>"><img src="images/icn_trash.png" title="Trash"></a></td> 
    </tr>
</tbody>
<?php endforeach; ?>     

如果我尝试使用下面的编码来区分文章 ID:

$sql = "SELECTarticles.id AS articleid, title, message, FROM article JOIN categories ON items.category_id = categories.id
$stmt = $pdo->查询($sql);
$articles = $stmt->fetchAll();

并指定文章 id 链接如下:

        <td><a href="article_edit.php?id=<?php echo h($article["articleid"]); ?>"><img src="images/icn_edit.png" title="Edit"></a></td> 
        <td><a href="article_delete.php?id=<?php echo h($article["articleid"]); ?>"><img src="images/icn_trash.png" title="Trash"></a></td> 

现在编辑和删除按钮链接到正确的“文章 id”,但无法再获取 categories.name 列行了。

希望有人能帮我解决这个问题,非常感激。

【问题讨论】:

    标签: php mysql database join


    【解决方案1】:

    我假设类别和文章表中都有 id 列?

    你几乎就在那里,使用别名。

    SELECT articles.id AS article_id, articles.name AS article_name, categories.id AS category_id, categories.name AS category_name
    FROM articles
    INNER JOIN categories ON areport.category_id = categories.id
    

    选择数据时应避免使用*,只选择你真正需要的,如上所示使用AS会重命名输出数据中的列。

    【讨论】:

    • @user2351553 如果我做了这项工作,你应该接受这个答案来表示感谢。
    【解决方案2】:

    您在查询中的表名错误。使用文章而不是报告

    SELECT articles.id AS article_id, 
           articles.name AS article_name, 
           categories.id AS category_id, 
           categories.name AS category_name
    FROM articles
    INNER JOIN categories ON articles.category_id = categories.id
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多