K. D. K. D. - 1 year ago 87
MySQL Question

pdo prepared statements with wildcards

I want to execute the following mysql query:

SELECT * FROM `gc_users` WHERE `name` LIKE '%anyname%'

I tried the following two things without success:

$stmt = $dbh->prepare("SELECT * FROM `gc_users` WHERE `name` LIKE :name");
$stmt->bindParam(':name', "%" . $name . "%");

$stmt = $dbh->prepare("SELECT * FROM `gc_users` WHERE `name` LIKE '%:name%'");
$stmt->bindParam(':name', $name);

So I ask you if it is possible to use the % wildcard with prepared statements.


Thank you. Its working with

$stmt = $dbh->prepare("SELECT * FROM `gc_users` WHERE `name` LIKE :name");
$stmt->bindValue(':name', '%' . $name . '%');

Answer Source

It can work with bind param too in following way:

$name = "%$name%";
$query = $dbh->prepare("SELECT * FROM `gc_users` WHERE `name` like :name");
$query->bindParam(':name', $name);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download