Question

I've read several topics about this and different people have different views on the best practice.

In terms of WordPress, how do I write data to the database the safest way?

This is one insert I'm using now:

$result = $wpdb->insert(
    $table_name , 
    array( 
        'arena'         => $galleryData['arena'],
        'year'          => substr( $galleryData['season'], 2 ),
        'copyright'     => $galleryData['copyright'],
        'description'   => $galleryData['description'],
        'path'          => $galleryData['path'],
        'fk_brand_id'   => $galleryData['brand']
    ), 
    array( '%s', '%d', '%s', '%s', '%s', '%d' )
);

Another way of inserting data is doing this:

$sanitized_sql = $wpdb->prepare( "
    INSERT INTO my_plugin_table 
    SET 
        field1 = %1$d,
        field2 = %2$s,
        field3 = %3$s’,
        32, 
        'Aaron Brazell',
        'Washington, D.C'
" );
$wpdb->query( $sanitized_sql );

Do I still need to sanitize data using wp_kses() or mysql_real_escape_string()?

I'm just confused on what method is the better for safely writing data to the database. I found a helpful answer on Stack Overflow.

So should I or should I not sanitize data before input?

Was it helpful?

Solution

No the sanitization is already done. Well the mysql_real_escape_string is done, it's considered bad form to filter html on input. I personally think doing it on output kinda breaches DRY. If you did in WordPress I highly suspect somewhere else will do it again resulting in double html entities encoding.

Also by the way, wpdb::insert is basically just a wrapper for wpdb::prepare.

OTHER TIPS

Note that storing data safely is different from safe data. For example JavaScript code can be totally harmless in context of database security, but nightmare in context of front-end.

There is no single blanket approach, that is why WordPress has massive amount of related functions.

You must consider:

  1. What data is.
  2. Where it comes from.
  3. How is it going to be used.
Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange
scroll top