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,
}
?>
CodePudding user response:
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";
}
CodePudding user response:
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;
}