Home > Backend Development > PHP Tutorial > How to Execute a LIKE Query with PDO Prepared Statements in PHP?

How to Execute a LIKE Query with PDO Prepared Statements in PHP?

Linda Hamilton
Release: 2024-11-01 17:03:30
Original
986 people have browsed it

How to Execute a LIKE Query with PDO Prepared Statements in PHP?

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>
Copy after login

adds unnecessary double quotes, leading to incorrect results.

Similarly, this syntax is also incorrect:

<code class="php">$ret = $prep->execute(array(':searchTerm' => '%'.$searchTerm.'%'));</code>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template