2

I have a form that I want to save to database. Do you consider the following code safe? I get the value directly from the $form_state and pass it into query. My understanding, it query will do the safe filter for me.

       $db = \Drupal::service('database');

       
        $result = $db->insert('invitation')
        ->fields([
            'guest_email' => $form_state->getValue('email'),
            'guest_name' => $form_state->getValue('name'),
            'guest_type' => $form_satte->getValue('type'),
            'created' => \Drupal::time()->getRequestTime(),
        ])
        ->execute();
    

1 Answer 1

1

As long as the values entered from users aren't concatenated directly into the string used for the SQL statement, there should not be any security risk.

The code shown in the question is safe because it uses the methods that take care of handling the values entered by users to avoid any possible issue.

The following code is an example of what to avoid.

$db = \Drupal::service('database');
$db->query("SELECT * FROM {users} WHERE name = '" . $form_state->getValue('name') . "'");

If the value entered for name were ' OR '1'='1' --, the executed query would became the following one. (-- is the comment start.)

SELECT * FROM {users} WHERE name = '' OR '1'='1' --

If multiple statements are allowed, the value entered from the user could also, for example, delete a database table, which could be possible by entering a'; DROP TABLE {users}; --. In this case the executed query would become the following one. (The comment at the end is just to let the database engine ignore the rest of the query.)

SELECT * FROM {users} WHERE name = 'a'; DROP TABLE {users}; --

Values entered by users need to be appropriately sanitized when output in a page. They should not be sanitized for that when saved in the database.

Your Answer

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

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