Correctly use LIKE '%{$var}%' with prepared statements
You may encounter problems using the LIKE '%{$var}%' syntax when trying to perform a case-insensitive search for usernames that contain a specific substring (for example, as you type). This problem occurs when trying to use this syntax with prepared statements.
To solve this problem, a different approach is suggested: first define a 'likeVar' variable containing the pattern "%{$yourParam}%". Then, prepare the query using the '?' placeholder and bind the 'likeVar' variable using bind_param.
An example is as follows:
<code class="language-php">$likeVar = "%" . $yourParam . "%"; $stmt = $mysqli->prepare("SELECT * FROM REGISTRY WHERE name LIKE ?"); $stmt->bind_param("s", $likeVar); $stmt->execute();</code>
In this method, you first concatenate the "%" character with $yourParam to create the 'likeVar'. Then, use the '?' placeholder in the preprocessed query and bind the 'likeVar' variable to it using the string's 's' specifier. This method should ensure successful search and display of results.
The above is the detailed content of How to Safely Use LIKE '%{$var}%' with Prepared Statements?. For more information, please follow other related articles on the PHP Chinese website!