2014-11-23 213 views
0

我在2个表运行查询,以从博客返回信息。嵌套查询选择与该博客相关联的标签,该博客是一个单独的表。PHP选择字段从嵌套查询

我希望能够从“标签”表获得“标签”行和在页面上显示这些。我的代码在下面,我已经评论了我想要选择的行的位置。

<?php 
include("inc/dbconnection.php"); 
$id  = $_GET['tag']; 
$id  = trim($id); 
$result = mysqli_query($conn, " 
SELECT * 
    FROM blog 
WHERE blog_id IN (SELECT blog_id FROM tags WHERE tag = '$id') 
"); 
if (!$result) { 
    die("Database query failed: " . mysqli_error($conn)); 
} //!$result 
else { 
    $rows = mysqli_num_rows($result); 
    if ($rows > 0) { 
     while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) { 
      $content = $row['content']; 
      $content2 = substr($content, 0, 100); 
      /* Below is where I would like to pull the row 'tag' from the nested query */ 
      $rawTag = $row['tag']; 
      $tag  = str_replace(" ", "", $rawTag); 
      $tagArray = explode(",", $tag); 
      $tag  = ""; 
      for ($i = 0; $i < count($tagArray); $i++) { 
       $tag .= "<a href='tag-" . $tagArray[$i] . ".php'>" . $tagArray[$i] . "</a> "; 
      } //$i = 0; $i < count($tagArray); $i++ 
      echo " 
        <table> 
        <tr> 
         <th> 
         <a href='blog-" . $row['blog_id'] . ".php'> 
          <h2>" . $row['title'] . "</h2> 
         </a> 
         </th> 
        </tr> 
        <tr> 
         <td> 
         <p>" . date("d/m/Y", strtotime($row['createdDate'])) . "</p><br /> 
         <span>" . $content2 . "...</span><br /> 
         <span><small>Tags: " . $tag . "</small></span> 
         </td> 
        </tr> 
        </table>"; 
     } //$row = mysqli_fetch_array($result, MYSQLi_ASSOC) 
    } //$rows > 0 
    else { //$rows > 0 
     echo "<br /><h1>There are currently no blogs with the selected tag (" . $_GET['tag'] . ")</h1><br /><h2>Please check back later.</h2>"; 
    } 
} 
?> 

很抱歉,如果这是一个愚蠢的问题,并在此先感谢您的帮助:)

+1

好,你正在使用先进的API,但现在看到准备好的发言 – Strawberry 2014-11-23 11:12:16

+0

唉唉拍!对不起,忘了提,-_-我想我的数据库中显示从辅助表“标签”行......我会更新的问题:) – Timothy 2014-11-23 11:16:26

+0

正确的,我只使用1 DB,但有2个表现在在这里 – Timothy 2014-11-23 11:20:18

回答

-1

有两个部分一个是查询和第二个是数据display.So数据显示基于 您的业务总调用(如何显示HTML标签数据。) 但在这里,你可以优化第一部分 (查询读取数据)如下:

$result = mysqli_query($conn, "SELECT b.*, t.* FROM blog b inner join tags t on 
b.blog_id= t.blog_id WHERE t.blog_id '" . $id . "')"); 

请使用。

+0

请在发布之前预览您的答案。 – Sumurai8 2014-11-23 11:57:23

+0

我认为OP想从两张表中抓取数据! – Strawberry 2014-11-23 12:03:18

+0

@Strawberry这是示例如何使用更好的查询如果查询是正确的,那么显然OP可以选择两个表列。如果您同意,请接受它。 – 2014-11-23 14:04:48