12

This does not work

$sql = 'SELECT * FROM `users` WHERE username LIKE \'%{?}%\' ';

Warning: mysqli_stmt::bind_param(): Number of variables doesn't match number of parameters in prepared statement in /home/rgero/public_html/php/searchadmins.php on line 1

This one doesn't work either

$sql = 'SELECT * FROM `users` WHERE username LIKE %{?}% ';

Fatal error: Wrong SQL: SELECT * FROM users WHERE username LIKE %{?}% Error: 0 in /home/rgero/public_html/php/searchadmins.php on line 1

How would I go about this? I'm trying to make a search for players function that updates the results as you're typing in the form, something like how google already shows answers while you're typing. I need for the username Admin , if you type dm, to show it already among other usernames that contain "dm". It should also be case insensitive

Dharman
  • 26,923
  • 21
  • 73
  • 125
Cârnăciov
  • 1,129
  • 1
  • 11
  • 22
  • 2
    You have to pre- and append `%` to the variable you're binding to the `?` parameter. – Charlotte Dunois Feb 07 '15 at 17:33
  • Yep, just use `bindParam(1, "%$var%")` etc. and a literal `LIKE ?` in the query. – mario Feb 07 '15 at 17:34
  • So I have to take the variable and add %{ to the beginning and %} to the end? – Cârnăciov Feb 07 '15 at 17:35
  • @Fred-ii- Right. The latter one is more exact of a dupe. However, the gist of the answer remains the same. It's really just the underscory `_` difference between `bindParam` and `bind_param` for mysqli. – mario Jan 06 '17 at 16:11
  • 2
    @mario I just didn't want future readers to get the wrong impression and some may even think they can mix different APIs *lol* - How many times I've seen that. – Funk Forty Niner Jan 06 '17 at 16:13
  • 1
    I'm just replying because I get notifications for these comments. I think you should weigh in the number of views these 'duplicate' topics get. Considering the fact google is supposed to penalize duplicate content and that somehow a couple thousand people still ended up here means I've used different keywords to which this question pops up first. If this was closed without an answer, that would've meant 3k bounced hits for SO. I know it's impossible to detect this when the question is fresh but the signs were here for this one. – Cârnăciov Jan 09 '17 at 16:08

1 Answers1

31

Try this

$likeVar = "%" . $yourParam . "%";
$stmt = $mysqli->prepare("SELECT * FROM REGISTRY where name LIKE ?");
$stmt->bind_param("s", $likeVar);
$stmt->execute();

you need to prepare the query using simply ? then you bind the param using bind_param.

Jean-François Savard
  • 20,182
  • 6
  • 46
  • 71