wpdb get_results() and prepare when to use prepare?

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?

Topic sanitization wpdb Wordpress

Category Web


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.


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.

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.