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();
K. D.
  • 4,041
  • 9
  • 48
  • 72
  • 6
    As for your first attempt - change `bindParam` to `bindValue` and turn [error reporting for PDO](http://stackoverflow.com/questions/15990857/reference-frequently-asked-questions-about-pdo#15990858) – Your Common Sense Apr 27 '13 at 18:48
  • [As an alternative to the given answer](https://stackoverflow.com/a/36593020/3536236) you can also use the [MySQL CONCAT function](https://dev.mysql.com/doc/refman/5.7/en/string-functions.html#function_concat) – Martin Nov 25 '19 at 16:37

2 Answers2

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();
Sumoanand
  • 8,835
  • 2
  • 47
  • 46
1

This could be an alternative:

$className = '%' . $this->className . '%';
$query->bind_param('s', $className);
jgritty
  • 11,660
  • 3
  • 38
  • 60
jroi_web
  • 1,992
  • 22
  • 23