PHP PDO LIKE : escaping the % character when combi

2019-04-13 01:41发布

$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条回答
太酷不给撩
2楼-- · 2019-04-13 02:21

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

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’));
查看更多
登录 后发表回答