2012-06-04 113 views
2

我使用這種語法而不是count(*),因爲它應該更快,但我不知道如何獲取產生的輸出MySQL&php PDO如何獲取:SELECT EXISTS(SELECT 1 FROM x WHERE y =:value)

$alreadyMember = $dataBase->prepare('SELECT EXISTS (SELECT 1 
FROM TheCommunityReachLinkingTable 
WHERE communityKey = :communityKey 
AND userID = :userID)'); 
$alreadyMember->bindParam(':communityKey', $_POST['communityKey'], PDO::PARAM_STR); 
$alreadyMember->bindParam(':userID', $_POST['userID'], PDO::PARAM_INT); 
$alreadyMember->execute(); 

if($alreadyMember->fetch()) {do code here} 

但它似乎沒有返回正確的東西,任何想法?

+0

錯誤的SQL語法的返回值? :) –

回答

5

使用EXISTS在這裏似乎不對。只要執行這個查詢,而不是:

SELECT 1 
FROM TheCommunityReachLinkingTable 
WHERE communityKey = :communityKey 
AND userID = :userID 
+0

我應該在最後設置LIMIT 1嗎? –

+0

@NicolasManzini只有當您知道會有多個記錄返回任何'communityKey'和'userID'組合的情況。 –

+0

好的,那麼謝謝你! –

0

正確的用法是一樣正常,捕捉取()

$row = $alreadyMember->fetch(); 
print_r($row); // you may have numeric or string indices depending on the FETCH_MODE you set, pick one, consider a column alias and associative 


//or the easy way 
$alreadyMember->execute(); 
if ($alreadyMember-fetchColumn()) { 
    //column 0 contained a truthy value 
} 
相關問題