Home >Database >Mysql Tutorial >How to Properly Bind LIKE Values with Trailing Percentage Symbols in PDO?

How to Properly Bind LIKE Values with Trailing Percentage Symbols in PDO?

DDD
DDDOriginal
2024-12-28 13:28:10867browse

How to Properly Bind LIKE Values with Trailing Percentage Symbols in PDO?

Binding LIKE Values with PDO

In a database query, LIKE operators are used to perform wildcard searches. When binding LIKE values using the PDO extension, it's important to handle the trailing percentage symbol correctly.

Bind LIKE Values with Trailing Percentage Symbol

In the query provided, you want to bind the variable $partial%. The correct approach is to use a placeholder with a trailing percentage sign:

select wrd from tablename WHERE wrd LIKE :partial%

where :partial is bound to $partial="somet", with the percentage symbol appended automatically.

Alternative Approaches

While the above approach is standard, you can also consider:

  • Using CONCAT: The query can be rewritten as:
SELECT wrd FROM tablename WHERE wrd LIKE CONCAT(:partial, '%')

This approach defers string concatenation to MySQL.

Escaping Special Characters

If the partial word being searched contains special characters like %, _, or , additional escaping is necessary. Use the following approach:

$stmt= $db->prepare("SELECT wrd FROM tablename WHERE wrd LIKE :term ESCAPE '+'");
$escaped= str_replace(array('+', '%', '_'), array('++', '+%', '+_'), $var);
$stmt->bindParam(':term', $escaped);

By escaping these characters, you ensure that they are interpreted correctly in the LIKE condition.

The above is the detailed content of How to Properly Bind LIKE Values with Trailing Percentage Symbols in PDO?. 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