46

I am running problems in implementing LIKE in PDO

I have this query:

$query = "SELECT * FROM tbl WHERE address LIKE '%?%' OR address LIKE '%?%'";
$params = array($var1, $var2);
$stmt = $handle->prepare($query);
$stmt->execute($params);

I checked the $var1 and $var2 they contain both the words I want to search, my PDO is working fine since some of my queries SELECT INSERT they work, it's just that I am not familiar in LIKE here in PDO.

The result is none returned. Do my $query is syntactically correct?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Leandro Garcia
  • 3,138
  • 11
  • 32
  • 44
  • Possible duplicate of [How do I create a PDO parameterized query with a LIKE statement?](https://stackoverflow.com/questions/583336/how-do-i-create-a-pdo-parameterized-query-with-a-like-statement) – feeela Aug 14 '18 at 09:32

5 Answers5

96

You have to include the % signs in the $params, not in the query:

$query = "SELECT * FROM tbl WHERE address LIKE ? OR address LIKE ?";
$params = array("%$var1%", "%$var2%");
$stmt = $handle->prepare($query);
$stmt->execute($params);

If you'd look at the generated query in your previous code, you'd see something like SELECT * FROM tbl WHERE address LIKE '%"foo"%' OR address LIKE '%"bar"%', because the prepared statement is quoting your values inside of an already quoted string.

Carlos Campderrós
  • 22,354
  • 11
  • 51
  • 57
  • +1 for the explanation.. But I don't think there is a way to look at the generated query.. is there anything like that? – Vignesh Jul 28 '15 at 12:22
  • Couldn't figure this out for the life of me and I had forgotten all about this. Awesome answer. Thanks! – b3tac0d3 Dec 18 '15 at 18:50
  • 2
    What happens if my parameter is "$name%" and the user enters: $name = '%bob'. Wouldn't that have the unintended side effect of an anchored search instead of a left anchored search? How would I prevent this? – danielson317 Jul 04 '18 at 20:29
8

Simply use the following:

$query = "SELECT * FROM tbl WHERE address LIKE CONCAT('%', :var1, '%')
            OR address LIKE CONCAT('%', :var2, '%')";

$ar_val = array(':var1'=>$var1, ':var2'=>$var2);
if($sqlprep->execute($ar_val)) { ... }
Grant
  • 2,413
  • 2
  • 30
  • 41
5

No, you don't need to quote prepare placeholders. Also, include the % marks inside of your variables.

LIKE ?

And in the variable: %string%

Madara's Ghost
  • 172,118
  • 50
  • 264
  • 308
4
$query = "SELECT * FROM tbl WHERE address LIKE ? OR address LIKE ?";
$params = array("%$var1%", "%$var2%");
$stmt = $handle->prepare($query);
$stmt->execute($params);
Miqdad Ali
  • 6,129
  • 7
  • 31
  • 50
2

You can see below example

$title = 'PHP%';
$author = 'Bobi%';
// query
$sql = "SELECT * FROM books WHERE title like ? AND author like ? ";
$q = $conn->prepare($sql);
$q->execute(array($title,$author));

Hope it will work.

Thiem Nguyen
  • 6,345
  • 7
  • 30
  • 50
Dinesh Goyal
  • 127
  • 1
  • 7