5

In order to do a LIKE search with PDO, I need to add the % to the parameter before passing it.

This works:

$qry = ' 
    SELECT product_id
    FROM cart_product
    WHERE product_manufacturer_num LIKE :search_string
';
$sth = $this->pdo->prepare($qry);
$sth->execute( array("search_string"=>'%'.$search_string.'%') );

To me this feels more like a hack, Is there a more official way of doing this?

JD Isaacks
  • 56,088
  • 93
  • 276
  • 422
  • Duplicate of: http://stackoverflow.com/questions/583336/how-do-i-create-a-pdo-parameterized-query-with-a-like-statement-in-php/7357296#7357296 – Kzqai Sep 09 '11 at 04:56

1 Answers1

4

It's fine. It doesn't feel like a hack to me.

The difficulty comes when you want to allow a literal % or _ character in the search string, without having it act as a wildcard.

Community
  • 1
  • 1
bobince
  • 528,062
  • 107
  • 651
  • 834
  • I thought a large part of binding parameters was for PDO / SQL to escape things like % or _ for you... So I'm confused. – RonLugge Jul 18 '12 at 05:13
  • 1
    @RonLugge: PDO does the escaping/parameterisation necessary to get string literals into the database. The issue is that the `LIKE` pattern syntax is a separate layer, on top of SQL string literals. MySQL confuses the issue by using the same escape character for both layers, but they are conceptually unconnected, implemented at completely different levels. – bobince Jul 18 '12 at 09:02