PDO prepared statements and LIKE escaping

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Hi folks.  I am trying to figure out the best way to handle an interesting 
issue in PDO prepared statements.  Consider:

$search = 'mystring';

$stmt = $dbh->prepare("SELECT * FROM mytable WHERE myfield LIKE :myfield");
$stmt->execute(array(':myfield' => $search . '%'));

The above will search for any record whose myfield entry begins with the value 
in $search.  Great.  And because it's a prepared statement, the database 
handles SQL injection protection for us.

According to the manual, that is the correct way of handling LIKE statements:

http://us3.php.net/manual/en/pdo.prepared-statements.php

(See Example #6)

But!  Now consider this:

$search = "100% pure PHP";

When that is run, the % in the literal string will get interpreted by the SQL 
server as another wildcard character.  That is not desired.

IIRC, the way in SQL to circumvent that is to convert "100%" into "100%%".  
However, that does rather defeat the purpose of a prepared statement if I 
have to do my own escaping anyway, does it not?  We also cannot use 
$dbh->quote(), as that is intended for cases where you're building a query 
string directly rather than using a prepared statement.

How do other folks handle this issue?

-- 
Larry Garfield
larry@xxxxxxxxxxxxxxxx

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux