Binding LIKE Values in PDO
When using LIKE queries in PDO, it's crucial to understand how to correctly bind the search value to avoid unexpected results.
Binding with Partial Match
To bind a partial match, you can use the following syntax:
SELECT wrd FROM tablename WHERE wrd LIKE :partial
Bind the parameter :partial to the partial value you want to search for. For example, if you have $partial = "somet", you would bind it as:
$stmt->bindParam(':partial', $partial);
Binding with Wildcard
To bind a partial match with a wildcard at the end, you can use either of these methods:
PDO-Generated Wildcard:
Use the following syntax:
SELECT wrd FROM tablename WHERE wrd LIKE ':partial%'
Bind the parameter :partial to the partial value without the wildcard.
SQL-Generated Wildcard:
Use the following syntax:
SELECT wrd FROM tablename WHERE wrd LIKE CONCAT(:partial, '%')
Bind the parameter :partial to the partial value without the wildcard.
Complex LIKE Queries
If the partial value contains special characters like %, _, or \, you need to escape them to prevent unintended results. Use the following code:
$stmt = $db->prepare("SELECT wrd FROM tablename WHERE wrd LIKE :term ESCAPE '+'"); $escaped = str_replace(array('+', '%', '_'), array('++', '+%', '+_'), $var); $stmt->bindParam(':term', $escaped);
By following these guidelines, you can effectively bind LIKE values in your PDO queries.
以上がPDO クエリで LIKE 値を効果的にバインドするにはどうすればよいですか?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。