'Correct way to use LIKE '%{$var}%' with prepared statements?

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



Solution 1:[1]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1