skip to Main Content

I have php function with query I want to add different Order by ASC/DESC depending on the form value the user selects so I had if statement inside the query line.
I tried but I get no error and no result, but if I without the if it works.

<?php
    SELECT * FROM Customers
     if(!empty($registro_asc_desc)){
    ORDER BY user_registered DESC, 
    } else  if(!empty($post_asc_desc)){else {
    ORDER BY postDESC,
    }
?>

3

Answers


  1. Chosen as BEST ANSWER

    Unfortunately none of the above worked; no error but still no result! Here is my full query, I want to add the if statements on the line of the ORDER BY

    function get_users_by_post_count( $post_type = 'advert' ) {
        global $wpdb;
    
        $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 '2021/10/01' and '2022/02/01'
                ORDER BY p.post_count ASC, 
                user_registered LIMIT 5",
                $post_type
            )
        );
        return $users;
    }
    

  2. You can try this way:

    $sql = "SELECT * FROM Customers";
    
    if (!empty($registro_asc_desc)) {
      $sql .= " ORDER BY user_registered DESC";
    } else if (!empty($post_asc_desc)) {
      $sql .= " ORDER BY post DESC";
    }
    
    Login or Signup to reply.
  3. I did try but did not work here example with the example mention above

     $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
            )
        );
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search