PHP从嵌套查询中选择字段

时间:2014-11-23 11:08:48

标签: php mysql

我正在对2个表运行查询,以返回博客中的信息。嵌套查询选择与该博客关联的标记,该博客是一个单独的表。

我希望能够获得'标记'来自'标签的行表并在页面上显示这些。我的代码如下,我已经评论了我希望选择行的位置。

<?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 个答案:

答案 0 :(得分:-1)

有两个部分是Query,第二个是数据显示。所以数据显示是基于总的 在您的业务电话上(如何在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 . "')");

请使用此。