Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wordpress: How to unescape the results when using $wpdb->get_results?

To add a new rows to the database I use $wpdb->insert, and to get the rows I use $wpdb->get_results.

The problem is that $wpdb->insert seems to be escaping the input. For example, a"b is saved as a\"b in the database. But, $wpdb->get_results doesn't seem to unescape back a\"b to a"b.

Is this the correct behavior by design?

Should I unescape the result of $wpdb->get_results manually? (What is the proper function for this?)

like image 385
Misha Moroshko Avatar asked Aug 19 '12 12:08

Misha Moroshko


People also ask

What does Wpdb Get_results return?

The get_results() function returns the entire query result as an array where each element corresponds to one row of the query result.

What is$ wpdb in WordPress?

The $wpdb object can be used to read data from any table in the WordPress database, not just those created by WordPress itself.

How do I insert WordPress data into Wpdb?

Use $wpdb->insert() . $wpdb->insert('wp_submitted_form', array( 'name' => 'Kumkum', 'email' => '[email protected]', 'phone' => '3456734567', // ... and so on )); Addition from @mastrianni: $wpdb->insert sanitizes your data for you, unlike $wpdb->query which requires you to sanitize your query with $wpdb->prepare .


2 Answers

$wpdb->insert() and $wpdb->prepare() will escape data to prevent SQL injection attacks. The $wpdb->get_results() function is designed to work generically with SQL SELECT statements, so I believe the fact that the slashes are left in place is intentional. This allows the consumer of the data to process it as necessary.

Since the $wpdb->get_results() funciton returns an array of stdClass objects, in order to remove the slashes in all columns in every row, you must iterate through the rows, and through the properties of each row object running the PHP stripslashes() function on it.

foreach( $quotes as &$quote ) {
    foreach( $quote as &$field ) {
        if ( is_string( $field ) )
            $field = stripslashes( $field );
    }
}

More information on the wpdb->get_results() function: http://codex.wordpress.org/Class_Reference/wpdb#SELECT_Generic_Results

like image 70
Brady Avatar answered Nov 11 '22 06:11

Brady


http://codex.wordpress.org/Function_Reference/stripslashes_deep

//replace $_POST with $POST
    $POST      = array_map( 'stripslashes_deep', $_POST);
    $wpdb->insert( 
            'wp_mytable', 
            array( 
                'field_name'        => $POST['field_name'], 
                'type'              => $POST['type'],
                'values'            => serialize($POST['values']),
                'unanswered_link'   => $POST['unanswered_link'], 
            ), 
            array( 
                '%s','%s','%s','%s'
            ) 
        );
like image 40
keithics Avatar answered Nov 11 '22 07:11

keithics