2

so if i have a function that gets terms from the database ( not the user ) do I need to use prepare first ( before get_results() ), or some sort of data sanitizing?

1

2 Answers 2

2

so if i have a function that gets terms from the database ( not the user ) do I need to use prepare first ( before get_results() ), or some sort of data sanitizing?

Yes, but you should be using get_terms/WP_Term_Query/wp_get_object_terms/etc and the other term APIs instead as they're safer and can be much faster. SQL bypasses object caches and performance plugins, as well as local caches, bulk fetches and security protections.

If you're going to perform an SQL query though, don't try to escape it, use prepare to insert variables into the query ( never do it directly! ):

$safe_sql = $wpdb->prepare(
    "SELECT * FROM `table` WHERE `column` = %s AND `field` = %d OR `other_field` LIKE %s",
    [ 'foo', 1337, '%bar' ]
);

Remember, if you need to use an SQL query on the core WordPress tables, there's a high chance you've done something wrong or don't know about a function that does it for you.

2
  • thank you, can you pls explain the array parameters, [ 'foo', 1337, '%bar' ] Apr 28, 2022 at 7:48
  • they're just examples, the placeholders in the SQL query %s get replaced with the items in the array, so the %s gets replaced with foo and the %d gets replaced with 1337 etc. The replacement happens in the order they appear. I recommend checking out the WPDB Prepare docs on wordpress.org for more examples and a more detailed explanation
    – Tom J Nowell
    Apr 28, 2022 at 9:23
1

You shouldn't need to pre-sanitize, wordpress takes care of that with the wpdb class.

   global $wpdb;
   $rows = $wpdb->get_results("SELECT * FROM " . $wpdb->prefix . "posts");

However, have a look at this:

https://wordpress.stackexchange.com/questions/217765/do-i-need-to-prepare-query-before-get-results-get-row-and-get-var#:~:text=You%20can%20sanitize%20before%20passing,doing%20the%20sanitization%20for%20you.

1
  • 1
    This answer only works because no dynamic variables are being inserted other than the table prefix. Taken at face value this leads to dangerous and insecure conclusions
    – Tom J Nowell
    Apr 27, 2022 at 10:21

Your Answer

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

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