Adriana
Adriana

Reputation: 11

Is it possible to add if statments inside php sql query

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,
    }
?>

Upvotes: 0

Views: 59

Answers (3)

Adriana
Adriana

Reputation: 11

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

Upvotes: 0

Adriana
Adriana

Reputation: 11

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

Upvotes: 0

DCodeMania
DCodeMania

Reputation: 1157

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";
}

Upvotes: 2

Related Questions