SQL参数化查询LIKE'%? %'PHP

问题描述:

我在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:// * .com/a/24207056/ –

+0

它引发一个错误:警告,执行()期望完全0参数和1给出 – user3634933

您可以使用CONCAT(),像这样:

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

你可以做到这一点,如下所示:

$key="%$key%" 

然后绑定$关键。

另见PHP Binding a Wildcard的几乎同样的问题....

+0

不起作用,只是形成一个字符串'%$ key%',然后它在数据库中搜索带有“'%$ key%''”的column_name。 – user3634933