2016-07-06 30 views
0

我有我的數據庫三種不同的表,我需要從所有表中搜索內容,但沒有工作,因爲它有不同的屬性PHP代碼從多個表中搜索在DATABSE

這裏是我的表結構

表1名>>博文

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

表2名>> forumnew

| fid | ftitle | fbody   | user | 

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

表3名>>下載

| 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; 
}?> 
+0

編輯您的文章,以顯示哪些字段與其他表匹配,並添加搜索條件示例顯示預期結果 – dbmitch

+0

好@dbmitch我試圖讓表,但沒有工作 – Frank

+0

@dbmitch,我的表結構看起來如何 – Frank

回答

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 

訣竅是選擇從所有三個表中的數據轉換爲一組具有相同名稱的列。

+0

,所以我可以用這個「所有者」和「描述」,「標題」和「ID」返回搜索結果。 ?關於帖子,論壇和下載在開始? – Frank

+0

我剛剛添加了'type'字段,以便您可以辨別記錄來自哪個表。你可能不需要甚至不關心它來自哪裏。 –

+0

我只是測試它,並得到太多的錯誤,我需要輸出'content TYPE,DESCRIPTION AND AUTHOR'作爲搜索結果 – Frank