Home > Article > Backend Development > How to Properly Implement LIKE Queries with PDO for Secure and Efficient Search?
Implementing the LIKE Query in PDO
When using LIKE queries with PDO, it's important to ensure proper parameter handling. The example query provided:
SELECT * FROM tbl WHERE address LIKE '%?%' OR address LIKE '%?%'
is incorrect. To include the LIKE operator with variable values, the percentage (%) symbols should be included in the $params array, not in the query itself. The correct code:
$query = "SELECT * FROM tbl WHERE address LIKE ? OR address LIKE ?"; $params = array("%$var1%", "%$var2%"); $stmt = $handle->prepare($query); $stmt->execute($params);
By including the percentage symbols in the $params array, they are correctly substituted into the prepared statement query, resulting in a search for addresses containing either variable value.
Additional Notes:
The above is the detailed content of How to Properly Implement LIKE Queries with PDO for Secure and Efficient Search?. For more information, please follow other related articles on the PHP Chinese website!