Question

I overthought a recent post and deleted it. Hopefully this version is a little clearer.

I have a multiselect dropdown, which I want to be able to filter a database table with.

So if I have the following drop down with roughly 70 entries:

<select multiple="multiple" id="filter" name="filter">
  <optgroup label="category1"> <!--jquery ui plugin allows for grouping -->
    <option value="sub1">Subcategory 1</option>
    <option value="sub2">Subcategory 2</option>
    <option value="sub3">Subcategory 3</option>
  </optgroup>
  <optgroup label="category2">
    <option value="sub4">Subcategory 4</option>
    <option value="sub5">Subcategory 5</option>
    <option value="sub6">Subcategory 6</option>

...

And I have 6 categories I need to search through in my sql statement, thus so far I have:

<?php
    include ("connect.php");

    $filter = $_POST["filter"];

        $result = mysql_query("SELECT * FROM edt_images
                                WHERE category1= '$filter'
                                OR category2= '$filter'
                                OR category3 = '$filter'
                                OR category4 = '$filter'
                                OR category5 = '$filter'
                                OR category6 = '$filter'")
            or die(mysql_error());
        while ($row = mysql_fetch_array($result)) {
            echo "<img src='files/small/thumb0_".$row['item_name'].".".$row['file_extension']."' border='0'/>"; 
        }
?>

Right now it works if I only select one item from the dropdown because it searches the six columns for that entry. So my question is how would I search these six columns for multiple entries?

Thanks in advance

Was it helpful?

Solution

If filter is an array of chosen categories you can use IN in your query:

$filterIn = implode("','",$filter);

SELECT * FROM edt_images
        WHERE category1 IN ('$filterIn')
        OR category2 IN ('$filterIn')
        OR category3 IN ('$filterIn')
        OR category4 IN ('$filterIn')
        OR category5 IN ('$filterIn')
        OR category6 IN ('$filterIn')

Note however you shouldn't be using unsanitised user input in an SQL query.

OTHER TIPS

IMHO first of all you need to allow to return multiple values from your multiselect. To do so you need to add brackets to name attribute like so:

<select multiple="multiple" id="filter" name="filter[]">
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top