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?
2 Answers
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.
-
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 withfoo
and the%d
gets replaced with1337
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
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:
-
1This 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