Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pdo prepared statements with wildcards

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();
like image 336
K. D. Avatar asked Apr 27 '13 18:04

K. D.


2 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(); 
like image 86
Sumoanand Avatar answered Sep 19 '22 22:09

Sumoanand


This could be an alternative:

$className = '%' . $this->className . '%'; $query->bind_param('s', $className); 
like image 32
jroi_web Avatar answered Sep 20 '22 22:09

jroi_web