Bind LIKE Values with PDO Extension
In database queries using the LIKE operator, it's crucial to properly bind values to prevent SQL injection attacks. When dealing with LIKE queries involving wildcard characters (% or _) at the end, understanding the appropriate binding technique is essential.
Let's consider the example query:
select wrd from tablename WHERE wrd LIKE '$partial%'
Here, we want to bind the variable $partial using PDO. The correct way to do this is:
select wrd from tablename WHERE wrd LIKE :partial
where :partial is bound to $partial with the value "somet%" (with the trailing wildcard). This ensures the query searches for words that match somet followed by any number of characters.
Alternatively, you could use:
SELECT wrd FROM tablename WHERE wrd LIKE CONCAT(:partial, '%')
to perform the wildcard concatenation in MySQL instead of the PDO statement.
However, if the partial word you're searching for might itself contain wildcard characters (% or _) or backslashes, additional escaping mechanisms may be necessary in the PDO preparation and parameter binding.
以上がPDO で LIKE 演算子を使用して値を適切にバインドするにはどうすればよいですか?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。