37

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

2 Answers 2

38

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();
5
  • Not sure why this has been down voted but please note this solution also works. :)
    – Sumoanand
    Apr 27, 2013 at 19:37
  • 5
    I guess it has been downvoted because if your $name contains a wildcard itself, it is not escaped.
    – Alain
    Oct 15, 2013 at 22:38
  • 2
    I waste my time with have no charset=utf8 in the DSN, I search with Thai character.
    – ittgung
    May 16, 2016 at 10:12
  • Are the backticks required?
    – Ömer An
    Jul 5, 2021 at 11:12
  • Proper solution is to use CONCAT, see here: stackoverflow.com/a/54277113/5444623
    – PeterM
    Mar 8 at 7:22
1

This could be an alternative:

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.