Home > Net >  Make options select possible to select multiple options in stead of just one
Make options select possible to select multiple options in stead of just one

Time:12-02

I have some filters for music sheets with php, like one filter is about the genre. Right now you can only select one item. But I want to make it possible to select multiple genres for example Christmas and Pop.

<form id="filters" method="post">
            <input type="text" id="myInput" placeholder="Search for music..." title="Type in a name" />  
            <select name="genre">
                <option value="">Genre</option>
                <?php
                $query = 'SELECT * FROM `imslp_genre` WHERE 1';
                $result = $conn->query($query);
                if ($result->num_rows > 0) {
                    while ($row = $result->fetch_assoc()) {
                        $thisGenre = $row['genre'];
                        echo "<option value='$thisGenre'>$thisGenre</option>";
                    }
                }
                ?>
            </select>
            <select name="instrument">
                <option value="">Instrument</option>
                <?php
                $query = 'SELECT * FROM `imslp_instruments` WHERE 1';
                $result = $conn->query($query);
                if ($result->num_rows > 0) {
                    while ($row = $result->fetch_assoc()) {
                        $thisInstrument = $row['instruments'];
                        echo "<option value='$thisInstrument'>$thisInstrument</option>";
                    }
                }
                ?>
            </select>
            <button type="submit">Filter</button>
        </form>


For the results I use the code below. It gets added to the query.

       $genre = filter_input(
            INPUT_POST,
            'genre',
            FILTER_SANITIZE_SPECIAL_CHARS
        );
     if (!empty($genre)) {
            $query .= " AND `sheets_genre` = '$genre'";
        }
        $result = $conn->query($query);

CodePudding user response:

Add multiple to select as such

<select name="cars" id="cars" multiple>
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="opel">Opel</option>
  <option value="audi">Audi</option>
</select>

CodePudding user response:

Add multiple to select as such

<select name="cars[]" id="cars" multiple>
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="opel">Opel</option>
  <option value="audi">Audi</option>
</select>

Update: You use name="cars[]" and then your post or get variable will be an array

  • Related