2015-04-07 72 views
1

我在php中有一個搜索功能,並使用參數化查詢來創建它,以確保它的安全。

SQL參數化查詢LIKE'%? %'PHP

$words = $_POST['words']//words is the form that has the words submitted by the user 
$array = explode(',', $words); 
$con = mysqli_connect("localhost","user","pass","database"); 

$stmt = $con->prepare(" SELECT column_name FROM table WHERE column_name LIKE ?") 
foreach($array as $key) { //searches each word and displays results 
    $stmt->bind_param('s', $key) 
    $stmt->execute(); 
    $result = $stmt->get-result(); 

    while($row = $result->fetch_assoc(){ 
    echo $row["column_name"] 
    } 
} 

但是我想$ stmt是聲明是

$stmt = $con->prepare(" SELECT column_name FROM table WHERE column_name LIKE '%?%' ") 

否則人們必須鍵入列名的整個價值找到它。

+0

我做了執行,'$ stmt->執行(陣列('%'。$ key。'%');'......這是PDO不確定mysqli是否支持這個功能 – chris85

+0

@ chris85 ^是的,這也適用於'mysqli_'。看一看http:// stackoverflow .com/a/24207056/ –

+0

它引發一個錯誤:警告,執行()期望完全0參數和1給出 – user3634933

回答

4

您可以使用CONCAT(),像這樣:

LIKE CONCAT ('%', ?, '%') 
1

你可以做到這一點,如下所示:

$key="%$key%" 

然後綁定$關鍵。

另見PHP Binding a Wildcard的幾乎同樣的問題....

+0

不起作用,只是形成一個字符串'%$ key%',然後它在數據庫中搜索帶有「'%$ key%''」的column_name。 – user3634933