Looking for clarification on how escaping (slashes) works in wpdb and best practice

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

Read More
  1. $_POST data is automatically escaped with slashes
  2. by using $wpdb->insert and $wpdb->update data ends up WITH slashes in database
  3. data retrieved with $wpdb->get_row and $wpdb->get_results has slashes
  4. I used stripslashes to resolve this issue

Case 2 – I didn’t need to strip slashes on output

  1. $_POST data is automatically escaped with slashes
  2. using $wpdb->query to insert and update data ends up WITHOUT slashes in database
  3. data retrieved with $wpdb->get_row and $wpdb->get_results does not have slashes
  4. 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)

Related posts

Leave a Reply

1 comment