Implementing LIKE Queries Correctly in PDO
When attempting to execute a LIKE query in PDO, it's important to ensure proper syntax to retrieve accurate results. In the query provided, the issue lies with the placement of the % wildcard characters.
The correct syntax for LIKE queries in PDO is to include the % signs within the $params array, rather than the query itself. Here's an example:
$query = "SELECT * FROM tbl WHERE address LIKE ? OR address LIKE ?"; $params = array("%$var1%", "%$var2%"); $stmt = $handle->prepare($query); $stmt->execute($params);
If the % signs were included within the $params array, the generated query would look like the following:
SELECT * FROM tbl WHERE address LIKE '%"foo"%' OR address LIKE '%"bar"%'
However, in the original query provided, the % signs were included within the query itself:
$query = "SELECT * FROM tbl WHERE address LIKE '%?%' OR address LIKE '%?%'";
When the query is executed, the prepared statement quotes the values inside of an already quoted string, resulting in an incorrect query. By moving the % signs to the $params array, the intended query will be executed correctly.
The above is the detailed content of How to Avoid Incorrect Queries When Using LIKE in PDO?. For more information, please follow other related articles on the PHP Chinese website!