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
Release: 2024-12-28 13:28:10
Original
867 people have browsed it

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%
Copy after login

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, '%')
Copy after login

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);
Copy after login

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!

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