Search code examples
phppdoprepare

Escapeing values in PDO statements


Doesn't prepare() escape any quotes(') in a PDO statement ? For some reason when I do this:

$sql = "INSERT INTO sessions (id, name) VALUES (1,'O'brian')";
$query = $this->connection->prepare($sql);
$query->execute();

I get this error:

Could not insert record SQLSTATE[42000]: [Microsoft][SQL Server Native Client 10.0][SQL Server]Incorrect syntax near 'brian'.

How could this be if I'm using prepare() ?


Solution

  • Since you are not passing the value in the execute method, it will not be automatically escaped for you. The following would be escaped for you:

    $sql = "INSERT INTO sessions (id, name) VALUES (1, ?)";
    $query = $this->connection->prepare($sql);
    $query->execute(array("O'brian"));