I’m just after fixing the output of some of my code to remove slashes from strings stored in and retrieved from the database using wpdb
functions. Then I expected to have to fix the same issue in another section of my code where strings are stored in and retrieved from the database but noticed that no slashes were added so I’m a bit confused about when slashes are added automatically. Here are my observations from these 2 cases that I encountered:
Case 1 – I needed to strip slashes on output
$_POST
data is automatically escaped with slashes- by using
$wpdb->insert
and$wpdb->update
data ends up WITH slashes in database - data retrieved with
$wpdb->get_row
and$wpdb->get_results
has slashes - I used stripslashes to resolve this issue
Case 2 – I didn’t need to strip slashes on output
$_POST
data is automatically escaped with slashes- using
$wpdb->query
to insert and update data ends up WITHOUT slashes in database - data retrieved with
$wpdb->get_row
and$wpdb->get_results
does not have slashes - no need to strip slashes on output
My questions are:
- Why is the behaviour different in these 2 cases?
- What is the best practice for dealing with escaping when using
wpdb
functions? - If a string contains a single quote, should that quote be escaped in the database? (i.e. if you view it in PHPMyAdmin)
From the codex:
You may also want to take a look at this section: http://codex.wordpress.org/Class_Reference/wpdb#Protect_Queries_Against_SQL_Injection_Attacks