How to Correctly Use PDO Prepared Statements for MySQL LIKE Queries?

Susan Sarandon
Release: 2024-10-31 02:05:29
Original
303 people have browsed it

How to Correctly Use PDO Prepared Statements for MySQL LIKE Queries?

PHP PDO Prepared Statement: MySQL LIKE Query

When performing a LIKE query using PHP's PDO class, it's essential to correctly handle the LIKE operator and prepare the statement properly.

Problem: In the provided code, the original query worked using the MySQL client but encountered issues when migrated to PHP.

Solution: The error lies in the WHERE clause within the prepare method. The following lines are incorrect:

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

Explanation:

  • Prepared statements: They transport data separately from the query, making quotes unnecessary when embedding values.
  • LIKE operator: Requires a wildcard character, such as % or _, to represent arbitrary character sequences.
  • Correct query: The correct WHERE clause should be:
<code class="php">WHERE hs.hs_text LIKE :searchTerm</code>
Copy after login

And the prepared statement should be executed as follows:

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

Now, the query should return the desired results.

The above is the detailed content of How to Correctly Use PDO Prepared Statements for MySQL LIKE Queries?. 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!