2013-06-01 52 views
0

我有簡單的SQL查詢,所以我也這樣寫的,可以從綁定變量中受益:PDO與綁定行爲不端的參數

$stmt = $this->db->prepare("SELECT * FROM activities WHERE user_id=':user_id' AND date(start_time)=date(':on_specific_day')"); 
$stmt->bindParam(':user_id',$where['user_id']); 
$stmt->bindParam(':on_specific_day',$where['on_specific_day']); 

正如你可以看到有一個關聯數組稱爲where這是用來存儲我條件。當我執行這個語句時,它不會返回任何錯誤,但行計數爲零。如果我不是拋棄我使用綁定變量的夢想,這樣做:

$stmt = $this->db->prepare("SELECT * FROM activities WHERE user_id='{$where['user_id']}' AND date(start_time)=date('{$where['on_specific_day']}')"); 

查詢運行得很好,並返回2個結果在我的測試案例。有人能幫助我擺脫瘋狂嗎? :^)

回答

3

你不需要附上PDO parameters用引號:

$stmt = $this->db->prepare("SELECT * FROM activities WHERE user_id=:user_id AND date(start_time)=date(:on_specific_day) 
+3

要解釋一下:在準備好的查詢參數是完整的變量,而不僅僅是文字被取代。所以一個字符串變量不需要額外的引號,因爲DB已經知道它是一個字符串。 – IMSoP

+1

我愛一個簡單的答案。像魅力一樣工作。非常感謝! – ken