Reputation: 1156
My site is based on Wordpress. To prevent SQL injection I need to sanitize data before the query. I have few questions about this.
1/ I read somewhere on stackoverflow, a person said that if we use get_results() for our query, we don't need to prepare() the sql query because data is already sanitized. So I'm not sure which case we must use prepare() and which case we don't need to use it.
$sql = prepare(....query...);
$wpdb->get_results($sql);
2/ Do we use prepare() with $wpdb->update()
$wpdb->insert()
$wpdb->get_row()
... or we just use prepare() for custom query like this $wpdb->query($wpdb->prepare(...query...))
3/ Say that I have a variable $data = $_POST['data']
. Which the best method below should I use to sanitize data before putting it in the query.
esc_sql($data);
or
sanitize_text_field($data);
or
mysql_escape_string($data);
or something else?
4/ Is there any safe query that we don't need to sanitize data for it or we have to sanitize all data before putting in the query?
Thank you.
Upvotes: 1
Views: 3922
Reputation: 44181
Th general rule seems to be: Functions like get_results
take a query, which may be a string or the return value of a call to prepare
(which also is likely a string). When building this string yourself, you should never use a user-provided variable without escaping. The preferred way to escape it is through prepare
. There may be other functions which are capable of doing the escaping, but I would recommend that you stick with prepare
(and very rarely esc_sql
).
As per the link above, data passed to insert
and update
do not need to be escaped, as these will do the escaping for you. Note that this applies only to the second (and third for update
) parameters.
Upvotes: 1