7

I have a Search function in php and have created it using a parameterized query to make it secure.

$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"]
  }
}

however I want $stmt statement to be

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

otherwise people have to type in the entire value of column_name to find it.

user3634933
  • 135
  • 1
  • 12

2 Answers2

11

You can use CONCAT(), like this:

LIKE CONCAT ('%', ?, '%')
Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
  • This isn't very flexible. What if you want the wildcard in the middle of the string for example. Their must be a better way. – danielson317 Jul 04 '18 at 20:08
1

You can do this as follows:

$key="%$key%"

Then bind $key.

Also see PHP Binding a Wildcard for pretty much the same question....

Community
  • 1
  • 1
Norbert
  • 6,026
  • 3
  • 17
  • 40
  • doesn't work that just crates a string '%$key%' and then it searches the database for column_name with " '%$key%' " in it. – user3634933 Apr 07 '15 at 02:02