连接表后不从db检索行

时间:2013-05-05 10:20:17

标签: php mysql database join

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

表名:文章

  • ID
  • CATEGORY_ID
  • 标题
  • 消息

表名:类别

  • ID
  • 名称

我想做什么:

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

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

  

$ sql =“SELECT * FROM articles JOIN categories ON articles.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 =“SELECT articles.id AS articleid,title,message,FROM articles JOIN categories ON articles.category_id = categories.id
  $ stmt = $ pdo-&gt; query($ sql);
  $ articles = $ stmt-&gt; 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列行。

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

2 个答案:

答案 0 :(得分:2)

我假设两个类别和文章表中都有一列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将重命名输出数据中的列。

答案 1 :(得分:0)

查询中的表名错误。使用文章而不是areport

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
相关问题