Home >Database >Mysql Tutorial >How to Correctly Bind LIKE Values with PDO in SQL Queries?
In SQL queries, the LIKE operator is used for pattern matching comparisons. When using the PDO extension to execute queries, it's crucial to bind LIKE values correctly to avoid ambiguous results.
One common scenario is binding a partial string to a LIKE expression, such as:
select wrd from tablename WHERE wrd LIKE '$partial%'
To bind this using PDO, the incorrect approach is to simply replace $partial% with a named parameter, e.g.:
select wrd from tablename WHERE wrd LIKE ':partial%'
This won't work because PDO won't interpret the % as a wildcard character, leading to incorrect results. Instead, there are several options to achieve the desired behavior:
Bind the parameter with an escaped version of the partial string. For example:
$stmt = $db->prepare("SELECT wrd FROM tablename WHERE wrd LIKE :partial"); $escapedPartial = $db->quote($partial . '%'); $stmt->bindParam(':partial', $escapedPartial);
Build the LIKE expression dynamically within the query using the CONCAT() function. This allows you to avoid the need for escaping, as the wildcard character is added at the MySQL end. For instance:
SELECT wrd FROM tablename WHERE wrd LIKE CONCAT(:partial, '%')
If the partial string contains special characters like %, _, or , you can use the ESCAPE clause to specify a placeholder character which cancels the special meaning of the character. For example:
$stmt = $db->prepare("SELECT wrd FROM tablename WHERE wrd LIKE :term ESCAPE '+'"); $escapedTerm = str_replace(array('+', '%', '_', '\'), array('++', '+%', '+_', '\+'), $term); $stmt->bindParam(':term', $escapedTerm);
The above is the detailed content of How to Correctly Bind LIKE Values with PDO in SQL Queries?. For more information, please follow other related articles on the PHP Chinese website!