PHP PDO LIKE : escaping the % character when combining with wildcard

怎甘沉沦 提交于 2019-12-06 10:53:32

问题


$percent = ‘%’;
$st=$db->prepare(“SELECT * FROM x WHERE y LIKE ?”);
$st=$st->execute(array(‘%’.$percent.’%’)); /*I want to get all records with the string % included like 5% etc.*/

The above example will not match correctly, instead matching all records in table x. In order for this to work correctly, I apparently need to set $percent='\%'.

This is where I am left confused about the concept behind prepared statements. I thought the whole point of prepared statements was that the value itself( $percent) would simply be interpreted as a string instead of a special wildcard character. I would appreciate any feedback.

Thanks in advance


回答1:


In the PDO tag (info) you will find the correct procedure for using wildcards in parameters.

Then you can escape % in the parameter.

$percent = '%\%%';//Escape % within % wildcards
.......
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
.........
$st=$db->prepare("SELECT * FROM x WHERE y LIKE ?");
$st=$st->execute(array($percent’));


来源:https://stackoverflow.com/questions/22030451/php-pdo-like-escaping-the-character-when-combining-with-wildcard

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!