Home >Backend Development >PHP Tutorial >How to Avoid 'Number of Variables Doesn't Match' Errors When Using LIKE '%{$var}%' with Prepared Statements?
How to Use LIKE '%{$var}%' Properly with Prepared Statements
When attempting to use LIKE '%{$var}%' with prepared statements, some users encounter the error: "Number of variables doesn't match number of parameters in prepared statement." This is because prepared statements require a specific number of parameters, and the syntax '%{$var}%' does not provide a clear parameter count.
Incorrect Example
$sql = 'SELECT * FROM `users` WHERE username LIKE \'%{?}%\' ';
Improved Solution
To resolve this issue, you should first create a variable containing the LIKE expression, with the wildcards included. Then, bind the variable to the prepared statement using the bind_param() method.
$likeVar = "%" . $yourParam . "%"; $stmt = $mysqli->prepare("SELECT * FROM REGISTRY where name LIKE ?"); $stmt->bind_param("s", $likeVar); $stmt->execute();
By following this method, you can effectively perform LIKE searches using prepared statements while maintaining case insensitivity and allowing for partial matches.
The above is the detailed content of How to Avoid 'Number of Variables Doesn't Match' Errors When Using LIKE '%{$var}%' with Prepared Statements?. For more information, please follow other related articles on the PHP Chinese website!