0

When passing values like 'ASC' or 'DESC' to prepare like:

[...]
$order = 'DESC';
[... (the whole query)], $order); // (as a prepare param)

it doesn't work because the resulting query from something like:

[...] group_concat(p.id ORDER BY p.post_date %s)

Will be:

[...] group_concat(p.id ORDER BY p.post_date 'DESC')

While should be:

[...] group_concat(p.id ORDER BY p.post_date DESC)

How to solve?

1 Answer 1

3

You don’t need to use $wpdb->prepare() for ORDER BY clauses. $wpdb->prepare() will always quote your variables.

Supposing you receive the ordering in the request, you can prevent SQL injection by not using the user entered value at all:

$sql = "SELECT....";
if ( 'asc' == $_GET['order'] ) {
    $sql .= ' ORDER BY p.post_date ASC';
} else {
    $sql .= ' ORDER BY p.post_date DESC';
}
$wpdb->prepare( $sql , $value_parameter );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.