user784637
user784637

Reputation: 16152

Proper PDO syntax for parameterized query using LIKE with wildcards (ex %, _)

The following syntax is the current syntax I have that's works.

$dbh = connect();
$singer = strtolower($_GET["singer"]);

$SQL =
      "SELECT *
        FROM table
        WHERE field1 LIKE ?
        ORDER BY field2 ASC";

$sth = $dbh-> prepare ($SQL);
$sth->bindParam (1, $singer);
$sth->execute();

What changes do I need to make to the line of code WHERE field1 LIKE ? to perform the query with the wildcard %?

I've tried WHERE field1 LIKE '%?%' but that didn't work.

Do I have to prepend '%

and append %'

to the value stored in $singer?

Upvotes: 2

Views: 4525

Answers (1)

xkeshav
xkeshav

Reputation: 54050

TRY

$str = "%".$singer."%";
$SQL =
      "SELECT *
        FROM table
        WHERE field1 LIKE ?
        ORDER BY field2 ASC";

$sth = $dbh-> prepare ($SQL);
$sth->bindParam (1, $str);

Reference ==> see 3rd Example

Upvotes: 9

Related Questions