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
Susan SarandonOriginal
2024-12-20 01:53:13263browse

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.'%"'));

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.'%'));

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!

Statement:
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