Home >Database >Mysql Tutorial >How Can Prepared Statements Improve the Efficiency and Security of LIKE Searches?
LIKE
Searches with Prepared StatementsDatabase queries using the LIKE
operator for pattern matching require careful handling to prevent vulnerabilities and ensure performance. Improper use can lead to errors.
Let's examine some flawed approaches:
<code class="language-sql">$sql = 'SELECT * FROM `users` WHERE username LIKE \'%{?}%\' ';</code>
This fails because the number of variables in the SQL string doesn't match the parameters provided to bind_param()
.
<code class="language-sql">$sql = 'SELECT * FROM `users` WHERE username LIKE %{?}% ';</code>
This results in a syntax error due to incorrect placement of wildcard characters (%{}) within the query string.
The correct method uses prepared statements, employing a question mark placeholder and binding the variable appropriately:
<code class="language-php">$likeVar = "%" . $yourParam . "%"; $stmt = $mysqli->prepare("SELECT * FROM REGISTRY where name LIKE ?"); $stmt->bind_param("s", $likeVar); $stmt->execute();</code>
This code:
$yourParam
).?
placeholder.bind_param()
.Using prepared statements with LIKE
prevents SQL injection and enhances query efficiency.
The above is the detailed content of How Can Prepared Statements Improve the Efficiency and Security of LIKE Searches?. For more information, please follow other related articles on the PHP Chinese website!