pdo prepared statements with wildcards
17,765
Solution 1
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();
Solution 2
This could be an alternative:
$className = '%' . $this->className . '%';
$query->bind_param('s', $className);
Author by
K. D.
Updated on June 28, 2022Comments
-
K. D. almost 2 years
I want to execute the following mysql query:
SELECT * FROM `gc_users` WHERE `name` LIKE '%anyname%'
I tried this 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();