Home > Backend Development > PHP Tutorial > Why Does PDO Prepared Statement Fail to Return Results with LIKE Query?

Why Does PDO Prepared Statement Fail to Return Results with LIKE Query?

DDD
Release: 2024-11-01 12:50:29
Original
583 people have browsed it

Why Does PDO Prepared Statement Fail to Return Results with LIKE Query?

PDO Prepared Statement in PHP: Issues with MySQL LIKE Queries

PHP's PDO class with MySQL offers a mechanism for executing SQL statements with parameterized queries, improving security and performance. However, users may encounter difficulties when using LIKE queries.

Issue: PDO Prepared Statement not Returning Results with LIKE Query

When attempting to execute a query similar to the following using PDO:

<code class="mysql">SELECT *
FROM hs
WHERE hs_text LIKE "%searchTerm%"</code>
Copy after login

Users may find that no results are returned.

Solution: Correct Parameterization

The issue lies in the incorrect parameterization of the search term. In PHP, prepared statements use named placeholders, which require different syntax. The correct parameterization for the LIKE query is:

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

Explanation:

Prepared statements separate the data from the query and use placeholders. Therefore, it is not necessary to wrap the search term in double quotes or perform string concatenation.

Other Common Mistakes:

<code class="php">WHERE hs_text LIKE :searchTerm
$ret = $prep->execute(array(':searchTerm' => '"%'.$searchTerm.'%"'));  // Incorrect</code>
Copy after login
  • This approach is incorrect as it adds unnecessary double quotes.
<code class="php">WHERE hs_text LIKE CONCAT(\'%\', ?, \'%\')
$ret = $prep->execute(array($searchTerm));  // Incorrect</code>
Copy after login
  • Using CONCAT to wrap the search term within the query is not necessary for parameterization.

By using the correct parameterization, you can successfully execute LIKE queries using PDO prepared statements in PHP.

The above is the detailed content of Why Does PDO Prepared Statement Fail to Return Results with LIKE Query?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template