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.
CREATE TABLE module3.eventrequest (
`EVENTNO` VARCHAR(8) NOT NULL,
`DATEHELD` DATE NOT NULL,
`DATEREQ` DATE NOT NULL,
`CUSTNO` VARCHAR(8) NOT NULL,
`FACNO` VARCHAR(8) NOT NULL,
`DATEAUTH` DATE NOT NULL,
`STATUS` VARCHAR(48) NOT NULL,
`ESTCOST` VARCHAR(48) NOT NULL,
`ESTAUDIENCE` VARCHAR(48) NOT NULL,
`BUDNO` VARCHAR(48) NOT NULL,
CONSTRAINT PK_EventNumber PRIMARY KEY (`EventNo`),
CONSTRAINT FK_CustomerNumber FOREIGN KEY (`CUSTNO`)
REFERENCES customer(`CUSTNO`)
)
2/ Do we use prepare() with $sql = prepare(....query...);
$wpdb->get_results($sql);
$wpdb->update()
$wpdb->insert()
... or we just use prepare() for custom query like this $wpdb->get_row()
3/ Say that I have a variable $wpdb->query($wpdb->prepare(...query...))
. Which the best method below should I use to sanitize data before putting it in the query.
$data = $_POST['data']
or
esc_sql($data);
or
sanitize_text_field($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.
答案 0 :(得分:1)
Th general rule seems to be: Functions like NULL
take a query, which may be a string or the return value of a call to get_results
(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 prepare
).
As per the link above, data passed to esc_sql
and insert
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.