Search code examples
phpmysqlpdobackslashapostrophe

LIKE-Query with PHP, mySQL and PDO


I want to match \' in my a column in a table in a MySQL Database, because these are entries where the data wasn't properly escaped.

I use PHP with PDO, this is the relevant code:

$stmt = $db->prepare("SELECT * FROM table WHERE title LIKE :title");
$stmt->bindValue(':title',"%\\'%",PDO::PARAM_STR);

Problem is, this matches titles with \' as well with a single '. I tried various combinations of \\\\\' etc., but nothing really worked to just match \', not the single '.

What am I doing wrong?


Solution

  • As it turns out, you actually need to do this:

    $stmt->bindValue(':title',"%\\\\\\'%",PDO::PARAM_STR);
    

    That is 6 backslashes and one apostrophe which then matches one backslash and one apostrophe. Anyone got an explanation for this?

    PS: I don't know why just adding backslashes didn't work before, I tried that, seems like I had double quotes or something.