Search code examples
phppdosql-like

LIKE statement and special characters in PDO / PHP


I've already checked answers to questions like this one (How do I create a PDO parameterized query with a LIKE statement in PHP). I've ended up to this solution:

$sql  = "SELECT count(*) ".
        "FROM mytable ".
        "WHERE num_certif LIKE CONCAT('%',:val,'%')";
$valeur = 'azert';
$stmt = $pdo->prepare($sql);
$stmt->bindValue(':val', $val);

This works, but here is my problem: how do I handle the '%' char? (i.e. $valeur = '%'; returns all the rows)?


Solution

  • You need to escape the % character,

      $valeur = '\%';