从数据库中的多个表中搜索的PHP代码

时间:2016-07-06 17:05:20

标签: php pdo

我的数据库中有三个不同的表,我需要从所有表中搜索内容但由于它具有不同的属性而无法正常工作

这是我的表结构

表1名称>>博文

| bid   | title     | body          | author    |
|-----  |-------    |-------------  |--------   |
| 1     | new       | hello new     | you       |
| 2     | cast      | broadcast     | me        |
| 3     | hack      | who hack us   | you       |

table2 name>> forumnew

| fid   | ftitle    | fbody         | user  |

|-----  |-------    |-------------  |--------   |
| 1     | new forum | hello new     | you       |
| 2     | cast me   | broadcast     | me        |
| 3     | hack you  | who hack him  | us        |

table3名称>>下载

| did   | file      | disc          | type      |

|-----  |-------    |-------------  |--------   |
| 1     | whoweare  | hello new     | php       |
| 2     | cast      | broadcast     | html      |
| 3     | hack      | who hack us   | c++       |

我使用这个PHP代码从单个表中选择

<?php
if(isset($_GET['postid'])){
$search = $_GET['postid'];


    $output;

    if(!empty($search)){
        $dsn = new DBController();
        $dsn->prepare("SELECT * FROM blogpost WHERE title LIKE :search LIMIT 10");
        $dsn->bind(':search', '%'.$search.'%');
        $dsn->execute();
        $output = $dsn->getAll();
        $dsn->free();
    }

    if(!is_null($output)):
        $html = '';
        foreach($output as $i => $row){
            $id = $row->bid;
            $title = $row->title;
            $cont = $row->body;
            $html .= '<article> <div class="spacer js-gps-track">
  <a href="'.$id.'" class="readmore related ret">'.$title.'</a> 
$body
</div></article>';
        }
        echo $html;
    else: ?>
<h5 style="color: #2f2f2f;">No related search found</h5><br/>
<?php endif;
}?>

1 个答案:

答案 0 :(得分:0)

你有几个选择:

  • 使用三个单独的查询
  • 使用UNION

关于如何进行联合的一个例子就是:

SELECT
   *
FROM (
    (SELECT 'post' AS type, bid AS id, title, body AS description, author AS owner FROM blogpost) AS search_posts
    UNION
    (SELECT 'forum' AS type, fid AS id, ftitle AS title, fbody AS description, user AS owner FROM forumnew) AS search_forum
    UNION
    (SELECT 'download' AS type, did AS id, file AS title, disc AS description, type AS owner FROM download) AS search_downloads
)
WHERE title LIKE :search
   OR description LIKE :search

诀窍是从所有三个表中选择一组具有相同名称的列。