Search code examples
phpsqlpdo

How to use PDO::quote to escape a string in a LIKE expression?


I try to use PDO::quote to escape a string in a LIKE expression, so the user string must not be surrounded like in :

LIKE "%userStringToEscape%"

Is there a way to do that ?


Solution

  • $var = "%userStringToEscape%";
    $var = $pdo->quote($var);
    $sql = "SELECT * FROM table WHERE field LIKE $var";
    

    but instead of using quote() you should be really using prepared statements

    $var = "%userStringToEscape%";
    $stmt = $pdo->prepare("SELECT * FROM table WHERE field LIKE $var");
    $stmt->execute($var);
    $data = $stmt->fetchAll();