• Hi I am trying to create a query where the user has the option to choose ordeby post_count or by registerdate, i’ve created sql query but my problem i cannot add if statmente inside the query so that if input field postcount empty orderby registration ASC/DESC, else if not empty orderby postcount ASC or DESC, I have tried to add the iff inside the sql query but s not working i’ve tried to concatenate sql query but not sure if i did right based on wordpress prepare stament it doesnt work. can someone please help me out below my query

     $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
            )
        );
Viewing 1 replies (of 1 total)
  • Moderator bcworkz

    (@bcworkz)

    If I read your code correctly, you’re trying to append an ORDER BY clause after the query had already been made. AFAICT, you don’t actually need any IF logic to manage ordering. You can chain ORDER BY criteria. If the first criteria doesn’t exist in the found data, all such data will be ordered by the second criteria.

    In any case, you’re attempting to use PHP to decide what ORDER BY clause to use. This is perfectly fine to do, but you must do so before running the SQL through prepare(). Something along this line:

    $sql = 'SELECT foo FROM bar WHERE author = %s';
    if ( $snafu ) {
      $sql .= ' ORDER BY snafu;';
    } else {
      $sql .= ' ORDER BY count;';
    }
    $wpdb->request( $wpdb->prepare( $sql, $author ));

    Note that you cannot directly use PHP variables in SQL in prepare(). Variables must be inserted by way of sprintf()-like syntax using placeholders for each variable.

Viewing 1 replies (of 1 total)
  • The topic ‘Is it possible to add if statments inside php sql query’ is closed to new replies.