PHP PDO Prepared Statement with MySQL LIKE Query
This article tackles the issue of using PHP's PDO class (MySQL driver) to perform a LIKE query with a MySQL database.
The problem arises when attempting to utilize LIKE with prepared statements, as the syntax employed in the PDO execute() method differs from the MySQL client.
The incorrect syntax:
<code class="php">$ret = $prep->execute(array(':searchTerm' => '"%'.$searchTerm.'%"'));</code>
adds unnecessary double quotes, leading to incorrect results.
Similarly, this syntax is also incorrect:
<code class="php">$ret = $prep->execute(array(':searchTerm' => '%'.$searchTerm.'%'));</code>
as it lacks additional syntax needed for prepared statements.
The correct syntax for executing a LIKE query with a PDO prepared statement is:
<code class="php">$prep = $dbh->prepare($sql); $ret = $prep->execute(array(':searchTerm' => '%'.$searchTerm.'%'));</code>
Prepared statements offer an advantage over string concatenation because they protect against SQL injection. They treat values as separate entities from the query, eliminating the need for cumbersome concatenation.
The above is the detailed content of How to Execute a LIKE Query with PDO Prepared Statements in PHP?. For more information, please follow other related articles on the PHP Chinese website!