Score:2

Is the following code secure when saving data to database?

th flag
fin

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();
    
Score:1
us flag

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.

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.