使用LIKE'%进行SQL参数化查询? %' PHP

时间:2015-04-07 01:14:13

标签: php mysql

我在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 '%?%' ")

否则人们必须输入column_name的整个值才能找到它。

2 个答案:

答案 0 :(得分:5)

您可以使用CONCAT(),如下所示:

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

答案 1 :(得分:2)

您可以按照以下方式执行此操作:

$key="%$key%"

然后绑定$ key。

另请参阅PHP Binding a Wildcard几乎相同的问题......