2013-09-23 67 views
1

可能不是一個標題的最佳描述,但我真的想不出任何東西。 我想要發生的是,我可以創建一個查詢,從列表中使用userID作爲關係選擇類型,然後選擇城鎮。使用變量選擇列

TABLE listings 
saleID userID type   description 
1  23  clothing  nice clothing 
2  45  clothing  More nice Clothing 

TABLE users 
userID country  county   town 
23   uk   county  townname1 
24   uk   county  townname2 

的變量在URL中設置爲獲取EG)?=型服裝&鎮= townname2

if (!isset($type)){ 
$query = "SELECT * FROM listings"; 
} 
if (isset($type)) { 
$query = "SELECT * FROM listings WHERE type = '{$type}'"; 
} 

這是位卻困我想與所有房源變量$型「服裝」,然後從用戶變量$鎮

if (isset($town)) { 
    $query = "SELECT users.town listings.userID listings.type FROM listings 
    WHERE type = '{$type}' 
    INNER JOIN users 
    ON users.town = '{$town}'";  
} 

霍普鎮我已經解釋了這口井enou選擇呃理解。 請幫我這最後詢問

+0

還驗證輸入值SQL注入,看看http://en.wikipedia.org/wiki/SQL_injection –

回答

1
SELECT u.town l.userID, l.type 
FROM listings l 
INNER JOIN users u on u.userID = l.userID 
WHERE l.type = '{$type}' 
AND u.town = '{$town}' 
+0

$結果=請求mysql_query($查詢); while($ listing = mysql_fetch_assoc($ results)){ – Ultigma

+0

抱歉,我一直按回車,如何訪問TABLE列表中的說明?我會做$列表['l.description'],因爲它似乎沒有找到它? – Ultigma

+0

想通了。需要它是全部,而不是隻指定特定的列。 CHANGED l.userID,l.type TO l。*再次感謝解決方案 – Ultigma

0
SELECT b.town, a.userID, a.type 
FROM listings a 
     INNER JOIN users b 
      ON a.userID = b.userID  
WHERE a.type = '{$type}' AND 
     b.town = '{$town}' 

爲了進一步獲得更多的知識有關加入,請訪問以下鏈接:


一點題外話,如果該值爲(SQL Injection),則該查詢易受攻擊s)的變量來自外部。請看下面的文章,瞭解如何防止它。通過使用PreparedStatements你可以擺脫使用單引號圍繞值。

+0

感謝您的回覆。我假設「a」作爲上市的變量? 「FROM listings ** a **」 – Ultigma

+0

不用客氣':)' –