Search code examples
phpmysqlmysqliternary

Using ternary operator in MySQLi query


I want to use ternary operation in my MYSQLi query. I have searched the forum and found an answers how its done, but in my case its not working at all. I will post what I tried:

$topsearch_listings = mysqli_query($conn, "SELECT * FROM listing WHERE published='yes' AND topsearch=1 ".$selected_category == 'All' ? '' : 'AND category='$selected_category''." ORDER BY rand()");

So what Im trying to do is if selected category is equal to "All" do nothing, and if selected category isnt equal to All add AND category='$selected_category'. What is wrong with my ternary and how can I use it inside my query?


Solution

  • A query like that is nothing more than just a string so treat it the same - the operator needs to know where are its boundries - therefore:

    $topsearch_listings = mysqli_query($conn, "SELECT * FROM listing WHERE published='yes' AND topsearch=1 ". ($selected_category == 'All' ? '' : 'AND category=\''.$selected_category.'\'')  ." ORDER BY rand()");
    

    Be sure yet to know that it is not safe to execute queries like this. I would suggest executing DIFFERENT queries for the open case (All) and particular ones (where there is a category). Plus you should use bound variables or at least try to escape the input.