Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 357
Cârnăciov Avatar asked Feb 07 '15 17:02

Cârnăciov


1 Answers

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.

like image 181
Jean-François Savard Avatar answered Oct 29 '22 03:10

Jean-François Savard