2013-08-21 323 views
0

我們有像準備LIKE語句

SELECT title, link 
    FROM search 
    WHERE title LIKE '%$keyword%' 

聲明我怎樣才能使一個事先準備好的聲明,使用戶輸入正確消毒,如:

​​

上面似乎失敗,我甚至嘗試過'%'+?+'%''%'.?.'%'

回答

2

使用CONCATMysql Docs function in your SQL

SELECT title, link 
    FROM search 
    WHERE title LIKE CONCAT('%', ?, '%') 
        ################### 

它接受參數要綁定的方式。因此,準備好的聲明。

瞭解更多在重複的問題的答案的詳細描述:

+0

這是否被認爲是一種良好做法?我看到了優勢,你不必編寫應用程序邏輯來支持「like」語句。但我不確定這是否應該在應用程序中使用。 –

+0

您也可以用一個問號替換整個虛線部分,並從您的應用程序中提供字符串表達式。它只是顯示你需要一個參數作爲參數 - 而不是在一個字符串表達式中,例如尋找問號。您可以通過指向重複問題的鏈接找到更多信息。 – hakre

-1

在Perl中,你必須在%-placeholder添加到變量至極,你會使用,而不是:

select searchtitle,searchdescription,searchlink from search where 
searchtitle like ? or searchdescription like ? 

使用下面的綁定PARAMS爲SQL語句:

Bindparams = ['%searchtitle%', '%searchdesc%']; 

我認爲這也必須在PHP中完成。

1

它只是如下所示?

$stmt = $dbh->prepare("select searchtitle,searchdescription,searchlink from search where 
searchtitle like :title or searchdescription like :description"); 
$stmt->bindParam(':title', '%' . $title . '%'); 
$stmt->bindParam(':description', '%' . $description . '%'); 
$stmt->execute(); 

$stmt->bindParam(':title', "%$title%"); 
$stmt->bindParam(':description', "%$description%"); 

我已經修改了示例given here

+0

這不會產生相同的結果。 – user2703510