In my current plugin, I am picking up the order by
column as user input. So I thought of using wpdb->prepare
to escape it.
$wpdb->get_results($wpdb->prepare("Select id from $wpdb->posts order by %s %s", $order_by_col, $order_by);
This is not working because it gets turned into
select id from wp_posts order by 'post_date' 'asc'
(Note the quotes)
So is there way to remove the quotes? Also is this a proper way to use $wpdb->prepare()? Should I manually escape it myself?
You can’t use
prepare
for column names, and you can’t really use it for the sort order either.prepare
will always quote the string. You will need to swap in the values yourself. Rather than try to “sanitize” the data, I’d use a white-list approach.Though, I wonder why you are not using
WP_Query
for this.As of Mar 29, 2023:
As of milestone 6.2, which was released Mar 29, you can now use
%i
instead of%s
as a placeholder inside$wpdb-prepare()
statements for table and column names. Here’s a dev-note about it with examples.Whitelisting is a good option for ‘ASC’ ‘DESC’, but for table names on your ORDERBY clause, WordPress has a built-in function just for you!
https://codex.wordpress.org/Function_Reference/sanitize_sql_orderby
$order_by_col = sanitize_sql_orderby( $order_by_col );