Home » Php » php – pdo prepared statements with wildcards

php – pdo prepared statements with wildcards

Posted by: admin April 23, 2020 Leave a comment

Questions:

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();
How to&Answers:

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();

Answer:

This could be an alternative:

$className = '%' . $this->className . '%';
$query->bind_param('s', $className);