PHP PDO LIKE : escaping the % character when combi

2019-04-13 01:36发布

问题:

$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’));