2011-07-06 39 views
1

我想寫我的第一個查詢,使用數據庫連接。我已經離開了一個教程網站,只是它似乎沒有顯示任何東西,任何人都可以看到我的代碼有任何明顯的錯誤?不能調用數據,第一次寫數據庫連接

//USers with Same Interests 
$interests_query = "SELECT * 
         FROM produgg_users AND user_interests 
        WHERE produgg_users.id = user_interests.user_id 
         AND (interest = $interest1 
         OR interest = $interest2 
         OR interest = $Interest3)"; 
$interests_result = mysql_query($interests_query); 

if($interests_result != 0) { 
    while($interests_row = mysql_fetch_array($interests_result, MYSQL_ASSOC)) { 
    echo $row->id; 
    } 
} else { 
    echo "No users to display!"; 
} 
//END SAME INTERESTS 

去@Jay答案我現在這只是它仍然沒有帶回任何信息,只打印出「沒有用戶diaply」

//USers with Same Interests 
$interest1 = "footy"; 
$interests_query = "SELECT * FROM produgg_users 
        join user_interests on produgg_users.id = user_interests.user_id 
        where interest = $interest1 OR interest = $interest2 OR interest = $Interest3"; 
$interests_result = mysql_query($interests_query); 

if($interests_result != 0) { 
while($interests_row = mysql_fetch_array($interests_result, MYSQL_ASSOC)) 
{ 
    echo $row->id; 
} 
} 
else 
{ 
echo "No users to display!"; 
} 
//END SAME INTERESTS 

回答

1

你應該有... mysql_query($interests_query) or die(mysql_error())捕捉任何語法錯誤。

如果沒有結果,mysql_query()不返回「0」。它返回一個結果句柄,或者一個布爾型的false來表示查詢完全失敗。您可以檢查與之匹配的行數mysql_num_rows($interests_result)

+0

啊,這就是現在導致這個,謝謝.... 你的SQL語法有錯誤;檢查與您的MySQL服務器版本相對應的手冊,以找到在第3行'OR interest ='附近使用的正確語法。 – Liam

+0

回覆您正在構建的查詢字符串,以確切瞭解它是什麼..我猜測它是這樣的'$ Interest3'。變量在PHP中區分大小寫,可能你打算使用'$ interest3'。 –

+0

我刪除了他們所有,只是堅持1 var現在,我收到這個錯誤,雖然.....未知列'footy'在'where子句'....我想選擇所有行的利息值是質量'腳',我想我需要以某種方式指定這個? – Liam

3

與JOIN嘗試查詢連接兩個表。

SELECT * 
    FROM produgg_users 
     INNER JOIN user_interests 
      ON produgg_users.id = user_interests.user_id 
    WHERE (interest = $interest1 OR interest = $interest2 OR interest = $Interest3) 
+0

+1:也可以將ORs變成IN –

+0

小馬:確實如果它是內連接則不會有任何區別。 – Jay

+0

謝謝Joe,我已經更新了我的代碼... – Liam

0

SELECT * FROM produgg_users和user_interests WHERE produgg_users.id = user_interests.user_id AND(利息= $ INTEREST1或利息= $ INTEREST2或利息= $ Interest3)「;

你的關鍵的問題是,這是不是正確的連接語法,你不需要在表名之間加上「和」,你可以輸入一個逗號,然後在where子句(舊的,笨拙的樣式)中給出連接條件,或者編寫「join」和將連接條件放在「打開」子句中(新的,漂亮的樣式)

舊樣式:

SELECT * FROM produgg_users, user_interests 
WHERE produgg_users.id = user_interests.user_id 
AND (interest = $interest1 OR interest = $interest2 OR interest = $Interest3) 

新風格:

SELECT * FROM produgg_users 
join user_interests on produgg_users.id = user_interests.user_id 
where interest = $interest1 OR interest = $interest2 OR interest = $Interest3