Home > Database > Mysql Tutorial > How to Correctly Use PHP PDO Prepared Statements with MySQL LIKE Queries?

How to Correctly Use PHP PDO Prepared Statements with MySQL LIKE Queries?

Susan Sarandon
Release: 2024-12-20 01:53:13
Original
284 people have browsed it

How to Correctly Use PHP PDO Prepared Statements with MySQL LIKE Queries?

PHP PDO Prepared Statement with MySQL LIKE Query

When querying data using PDO in PHP with a LIKE condition, it's crucial to understand the correct handling of search terms. Here's a solution for the reported issue:

The initial code incorrectly added double quotes to the search term when preparing the statement:

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

This extra quoting is unnecessary. Prepared statements separate data from the query, so quotes should not be embedded.

Additionally, the code incorrectly used WHERE hs.hs_text LIKE ":searchTerm" without adding the percentage symbols around the search term.

To rectify the issue, the corrected code should execute the statement as follows:

$prep = $dbh->prepare($sql);
$ret = $prep->execute(array(':searchTerm' => '%'.$searchTerm.'%'));
Copy after login

Explanation:

Prepared statements transport data separately from the query, so values are not directly substituted into the query string. Quotes are only needed when embedding values within a query, which is not the case here.

By using the correct syntax, the PDO prepared statement can effectively search for data using the LIKE condition with the provided search term.

The above is the detailed content of How to Correctly Use PHP PDO Prepared Statements with 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