Matty
Matty

Reputation: 34543

PDO: Quotes in SQL

I'm seeing some weirdness when I try to run a query using PDO. The following code shouldn't return results, but it does:

$safe_path = $this->_databaseConnection->quote($unsafe_path);
$sql = "SELECT * FROM routes WHERE path=$safe_path LIMIT 1";
$statement_handle = $this->_databaseConnection->query($sql);
var_dump($statement_handle->fetchAll());

I'm confused because there aren't single quotes around the $safe_path variable as there would be if I were using the mysqli extension - but it's working. If I enclose $safe_path in quotes, no results are returned. This seems strange to me.

Upvotes: 1

Views: 824

Answers (3)

Brendan Bullen
Brendan Bullen

Reputation: 11819

Aren't you adding quotes?

$safe_path = $this->_databaseConnection->quote($unsafe_path);

Upvotes: 1

MatTheCat
MatTheCat

Reputation: 18761

The PDO quote method just add quotes in a string context.

http://php.net/manual/en/pdo.quote.php

PDO::quote() places quotes around the input string (if required)[...]

Upvotes: 2

Treffynnon
Treffynnon

Reputation: 21563

You are already quoting the $safe_path variable with your first line in the sample:

$safe_path = $this->_databaseConnection->quote($unsafe_path);

That is why it works as it stands. If you attempt to add quotes yourself in the:

$sql = "SELECT * FROM routes WHERE path='$safe_path' LIMIT 1";

line then you would be doubling up the quotes and therefore breaking the SQL query.

Please see the manual page for quote() for more information:

PDO::quote() places quotes around the input string (if required) and escapes special characters within the input string, using a quoting style appropriate to the underlying driver.

Upvotes: 2

Related Questions