Do I need to use wpdb prepare before wpdb->insert?
If I am inserting values into a wordpress table using wpdb->insert, do I need to “clean” my data before inserting it or does this method (wpdb->insert) do that for me?
Do I need to use wpdb prepare before wpdb->insert?
If I am inserting values into a wordpress table using wpdb->insert, do I need to “clean” my data before inserting it or does this method (wpdb->insert) do that for me?
You must be logged in to post a comment.
No, you shouldn’t prepare or escape the data, this is done for you by the
wpdb
class.From the wpdb class reference:
If, however, you were writing your own SQL rather than using the
insert
method, then yes, you should escape usingprepare
.The following is a warning for the wpdb class.
https://codex.wordpress.org/Class_Reference/wpdb
So I read this as – the wpdb class does not automatically prepare or escape the data for you.
I am pretty sure that if you cannot trust 100% the data source in your code, then I suggest using the prepare class(?).
Do not think that using the prepare class will fix it without using the prepare class properly. I am fairly new to this so please post any corrections as a reply if I am not right.
$wpdb->prepare( “SELECT * FROM table WHERE ID = %d AND name = %s”, $id, $name );
In the above statement, there are 2 extra attributes. One for the ID and one for the name. As far as I read it, each corresponds in order to the number of items in your query. Also %s = string, %d = integer and %f = float.
Also, from my reading, if you don’t put the extra attributes in, then prepare will actually do nothing. There will be a warning, but if you switch that off, perhaps you won’t know.
Here is an example from the class reference itself where they add a prepare class into an INSERT below.
https://codex.wordpress.org/Class_Reference/wpdb#Protect_Queries_Against_SQL_Injection_Attacks
My concern is that the upvoted answer is incorrect according to the same page that ‘nobody’ references. I am assuming that you use prepare() but not other standard php methods of escape because I took this answer as correct as well… until I dug deeper.
Anyway… perhaps things have changed since the original answer.
No you do not need to prevent against SQL injections when you use – wpdb insert or wpdb delete.
See the following links:
https://codex.wordpress.org/Data_Validation#Database
https://codex.wordpress.org/Class_Reference/wpdb#Protect_Queries_Against_SQL_Injection_Attacks