Hello and welcome to our community! Is this your first visit?
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    Regular Coder
    Join Date
    Dec 2010
    Thanked 11 Times in 11 Posts

    PHP/SQL show 'all' in specific columns

    Hi, I'm really struggling to get my head around this.

    I'm making a search form with drop down menus. I want the option of 'all' to show all records regardless of that criteria. But when something is selected, then only show that match.

    There are two drop downs, 'location' and 'position' (this is for a teaching jobs) and say i had a user select - "location: all, position: head teacher", or "location: London, position: head teacher", I want both to be able to work accordingly.

    How can I get the 'all' to work? Of course looking for the term 'all' in the table is going to return no results! Can I put an 'if' statement actually in the WHERE clause? Or this this bad practice? I also thought I could use 'LIKE' and then just make $location or $position NULL if 'all' is selected and use the wildcard method?

    This is what I have so far

    PHP Code:
    $subject $_GET['subject'];
    $location $_GET['location'];

    $result $db->query("SELECT * FROM jobBoard WHERE subject = '$subject' AND location = '$location'");

    $row $result->fetch_assoc()){ ... } 

  • #2
    New Coder
    Join Date
    Nov 2007
    Thanked 1 Time in 1 Post
    Heya, you want to test for there being a value in the search field. If there aren't any get values then the user must want all te results. Something like the code below should work.

    PHP Code:
    // If both subject and location exist build a query for both search parameters.
    if(isset($_GET['subject']) && isset($_GET['location']))
    $query "SELECT * FROM jobBoard WHERE subject = '$_GET['subject']' AND location = '$_GET['location']'";

    //Build search query for only subject search
    elseif (isset($_GET['subject']))
    $query "SELECT * FROM jobBoard WHERE subject= '$_GET['subject']'"

    //Build search query for only location search
    $query "SELECT * FROM jobBoard WHERE location = '$_GET['location'];"

    //If both search parameters aren't set you must want all results.
    else{$query "SELECT * FROM jobBoard";}

    $result $db->query($query);

    $row $result->fetch_assoc()){ ... } 
    Do be aware of the fact that using GET values directly is extremely unsafe and that you should strip them first.
    Last edited by mathew edison; 11-11-2013 at 10:48 PM.


    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts