1

I've used mysql_real_escape_string() to make strings safe before using Drupal.

Must I escape string before inserting it to database? If the answer is yes, then how must I do it?

I use something like this to insert into database:

\Drupal\Core\Database\Database::setActiveConnection('mydb');
$connection = \Drupal\Core\Database\Database::getConnection();
db_insert($table_name)->fields(array(
'myfield1' => 'My String',
))->execute();
\Drupal\Core\Database\Database::setActiveConnection();

1 Answer 1

4

No need to worry about escaping. The Drupal database abstraction layer is taking care of query parameter escaping by turning them into placeholders and escaping the data.

1
  • 2
    ... as long as you either use one of the query builders like select, update, insert, .. and the fields() or condition() methods. If you use query() or ->where() method of query builders, make sure you use :placeholders and you are fine too.
    – Berdir
    Jun 1, 2016 at 16:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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