8

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.

7
  • I do it in the execute, $stmt->execute(array('%' . $key . '%');... that's in PDO not sure if mysqli supports that. Commented Apr 7, 2015 at 1:18
  • @chris85 ^ Yes, that would also work with mysqli_. Have a look stackoverflow.com/a/24207056 Commented Apr 7, 2015 at 1:34
  • it throws an error: Warning, execute() expects exactly 0 parameters and 1 is given Commented Apr 7, 2015 at 1:50
  • 1
    Here, try this LIKE CONCAT ('%', ?, '%') that should work. Commented Apr 7, 2015 at 2:27
  • 1
    that works!!, @Fred-ii- make it an answer so i can upvote you Commented Apr 7, 2015 at 2:34

2 Answers 2

11

You can use CONCAT(), like this:

LIKE CONCAT ('%', ?, '%')
Sign up to request clarification or add additional context in comments.

1 Comment

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.
1

You can do this as follows:

$key="%$key%"

Then bind $key.

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

1 Comment

doesn't work that just crates a string '%$key%' and then it searches the database for column_name with " '%$key%' " in it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.