3

I've been reading through the documentation, but I feel like it's always a little bit vague on this, perhaps I'm missing something.

function foomodule_my_hook_menu_callback($unescapedUserInputString) {
    $sql = "select name from {foo_table} where bar=:inputString";
    $result = db_query($sql, array(':inputString' => $unescapedUserInputString));
}

Is the above code vulnerable to an SQL injection attack? Or will :inputString get appropriately escaped to make it safe for SQL? (I know I need to sanitize it for proper values in my implementation, but I'm just referring to the SQL safety)

What about with db_insert()?

$insert_id = db_insert('foo_table')
                ->fields(array(
                    'name' => $unescapedUserInputString,
                ))
                ->execute();
1

1 Answer 1

4

these functions are abstractions on top of php's PDO library. They are essentially prepared sql statements ... passed values to the query are safe from SQL-injection.

Feel free to jump into the PHP PDO Manual.

EDIT:

eg,

Many of the more mature databases support the concept of prepared statements. What are they? They can be thought of as a kind of compiled template for the SQL that an application wants to run, that can be customized using variable parameters. Prepared statements offer two major benefits:

The query only needs to be parsed (or prepared) once, but can be executed multiple times with the same or different parameters. When the query is prepared, the database will analyze, compile and optimize its plan for executing the query. For complex queries this process can take up enough time that it will noticeably slow down an application if there is a need to repeat the same query many times with different parameters. By using a prepared statement the application avoids repeating the analyze/compile/optimize cycle. This means that prepared statements use fewer resources and thus run faster.

The parameters to prepared statements don't need to be quoted; the driver automatically handles this. If an application exclusively uses prepared statements, the developer can be sure that no SQL injection will occur (however, if other portions of the query are being built up with unescaped input, SQL injection is still possible).

2
  • Even the db_query() where I'm passing it a custom SQL statement? Just want to be VERY sure. :) Commented Jun 28, 2012 at 20:56
  • YES. That's the point of placeholders.
    – Berdir
    Commented Jun 28, 2012 at 21:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.