Jump to content

How can I make this MySQL Insert statement secure?


vbmark

Recommended Posts

Using this framework:

http://stefangabos.ro/php-libraries/zebra-database/

 

The author says:

"It encourages developers to write maintainable code and provides a better default security layer by encouraging the use of prepared statements, where parameters are automatically escaped."

 

The documentation shows an example of an Insert as:

 

$db->insert(
    'table',
    array(
        'column1'   =>  'value1',
        'column2'   =>  'value2',
));
 

 

The framework code that gets run is:

 

    function insert($table, $columns, $ignore = false, $highlight = false)
    {

        // enclose the column names in grave accents
        $cols = '`' . implode('`,`', array_keys($columns)) . '`';

        // parameter markers for escaping values later on
        $values = rtrim(str_repeat('?,', count($columns)), ',');

        // run the query
        $this->query('

            INSERT' . ($ignore ? ' IGNORE' : '') . ' INTO
                ' . $table . '
                (' . $cols . ')
            VALUES
                (' . $values . ')'

        , array_values($columns), false, $highlight);

        // return true if query was executed successfully
        if ($this->last_result) return true;

        return false;

    }
 

The question is:

Is the example secure against SQL injection or do I need to write it differently?

 

Thank you!
Mark

 

the code is building what appears to be a prepared query, with ? placeholders for the values. as long as the table and column names are not coming from unvalidated external data and the ->query() method is actually running a prepared query, it's secure against sql injection.

 

edit: the code should also place the table name within back-ticks if it is trying to be universal code that won't fail with an error for any arbitrary table/column names.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.