Add if statement inside sql query?

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
        )
    );

Write the string to a variable first, then prepare the variable. (or use an inline ternary, but the separate thing is cleaner)

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

So it should look like this:

1 Like

Seems to be the perfect solution havent tested 100% but I think it works thanks

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.