2017-06-28 41 views
0

我試圖從4個表中提取數據。當我從MySQL表中的3(user_table,posts,followers)提取數據時,數據檢索得很好。它當我試圖從第四表(post_likes)拉特定的列,我遇到問題。所有的數據根本不顯示。PDO:無法從MySQL中的第4個表中提取數據

這裏的數據庫結構:

USER_TABLE:user_id, username, name

帖子:post_id, body, user_id, likes

追隨者:follower_id, user_id, follower_id

post_likes:likes_id, post_id, user_id

連接腳本:

class DB { 

     private static function connect() { 
       $pdo = new PDO ('mysql:host=localhost;dbname=test;charset=utf8','root',''); 
       $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 
       return $pdo; 
     } 

     public static function query($query, $params = array()) { 
      $statement = self::connect()->prepare($query); 
      $statement->execute($params); 
      if (explode(' ', $query)[0] == 'SELECT') { 
      $data = $statement->fetchAll(); 
      return $data; 
      } 
    } 
    } 

腳本,從3代表的工作原理提取數據:

$posts = DB::query('SELECT posts.post_id, posts.body, posts.likes, 
users_table.username, users_table.name FROM users_table, posts, followers 
WHERE posts.user_id = followers.user_id 
AND users_table.user_id = posts.user_id 
AND follower_id = :userid 
ORDER BY posts.posted_at DESC', array(':userid'=>$userid)); 

腳本不從4桌工作拉動數據:

$posts = DB::query('SELECT posts.post_id, posts.body, post_likes.post_id, 
post_likes.user_id, posts.likes, users_table.username, users_table.name 
FROM users_table, posts, followers, post_likes 
WHERE posts.user_id = followers.user_id 
AND users_table.user_id = posts.user_id 
AND follower_id = :userid 
ORDER BY posts.posted_at DESC', array(':userid'=>$userid)); 

任何幫助,我能爲這個? thanx

+1

從等式中刪除PDO和測試上的MySQL查詢直。是否返回任何數據?這聽起來像查詢只是導致零記錄。什麼記錄在沒有WHERE條款的情況下返回?這些表如何加入?提示:顯式連接比隱式連接更容易管理。不要用逗號分隔表格,而要使用實際的'JOIN'子句。也許隱式連接沒有達到你期望的效果。 – David

回答

0

做正確的方法是:

SELECT 
posts.post_id, posts.body, post_likes.post_id, 
post_likes.user_id, posts.likes, users_table.username, users_table.name 
FROM 
users_table 
inner join posts on users_table.user_id = posts.user_id 
inner join followers on posts.user_id = followers.user_id 
inner join post_likes on post_likes.id = <your condition> 
WHERE 
follower_id = :userid 
ORDER BY posts.posted_at DESC 

我們假設follower_id列只存在於表中其他含糊不清的錯誤1將被拋出

+0

thanx。這工作 – user2938948

1

4表查詢失敗的原因是由於在查詢中添加了post_likes表,但未提供從當前數據集到post_likes表的任何鏈接。

注意所有where子句將您的錶鏈接在一起。在你的post_likes表中沒有where子句鏈接。

我asummption是你需要更新你的WHERE子句這樣的:

WHERE posts.user_id = followers.user_id 
AND post_likes.post_id = posts.post_id //Link post_likes here 
AND users_table.user_id = posts.user_id 
AND follower_id = :userid 

編輯:正如大衛指出你應該用實際連接的命令。

+0

這仍然給我相同的結果 – user2938948