K. D. K. D. - 4 months ago 17
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->execute();

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


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

/edit

Thank you. Its working with
bindValue
:

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

Answer

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);
$query->execute();
Comments