Is it possible to have if statement inside query with php, I want the orderby depend on the selection of the user, so if a variable is not empty the
ORDER BY p.post_count ASC,
else if
ORDER BY user_registered ASC,
My attempt code below?
$users = '';
$users = $wpdb->get_results(
$wpdb->prepare(
"SELECT {$wpdb->users}.ID, p.post_count, display_name, user_registered
FROM {$wpdb->users}
LEFT JOIN (
SELECT post_author, COUNT(*) AS post_count
FROM {$wpdb->posts} WHERE post_type = 'advert'
GROUP BY post_author
) p ON {$wpdb->users}.id = p.post_author
WHERE user_registered between '2020/01/01' and '$data_final_format';
if (!empty($registro_asc_desc)) {
$users.= 'ORDER BY user_registered DESC';
} else if (!empty($post_asc_desc)) {
$users.= 'ORDER BY p.post_count DESC';
}
user_registered LIMIT 20",
$post_type
)
);
I donβt understand what is the content of $post_type, normally the second parameter of the prepare contains the prepared statements but you have none in you query string.
Also it makes absolutely no sense to set user=ββ if you reset it it to a new value in the next line.
You should use $data_final_format as a prepared statement also