jeudi 30 avril 2020

How to search database and filter results using multiple checkboxes? PHP

I'm a complete newbie, so please bear with me.

I need to create a html form that searches through a music database (using GET method) called 'top_albums'. One of the requirements for the form is to create checkboxes (titled.. US, UK, FR, DE, CA, and AU) so that results are filtered so only albums in the corresponding country are displayed. I should be able to select as many or as few checkboxes as I want. And the results returned should show albums in ALL the countries selected.

How would I go about doing this? Also, in the top_albums database, columns are named artist, albums, US, UK, FR, DE, CA, AU.

So far, I've succeeded in creating a text input that allows filtering the database by artist name (which is also a requirement) and the checkboxes on the form (without php code).

Here is part of my html form:

<form action="results.php" method="get">
<fieldset><legend>Popular Music Database Search</legend>
<p>Artist Name: <input type="text" name="search" /></p>

<p><input type="checkbox" name="country[]" value="US">US
<input type="checkbox" name="country[]" value="UK">UK
<input type="checkbox" name="country[]" value="FR">FR
<input type="checkbox" name="country[]" value="DE">DE
<input type="checkbox" name="country[]" value="CA">CA
<input type="checkbox" name="country[]" value="AU">AU</p>

<p><input type="submit" /></p>
</form>

Here is my PHP:

 <?php
    $search = $_GET['search'];

    $servername = "localhost";
    $dbname = "";
    $username = "";
    $password = "";
    $conn = new mysqli($servername, $username, $password, $dbname);
    if ($conn->connect_error) {
      die("Connection failed: " . $conn->connect_error);
    }
?> 
<table>
  <tr>
    <th>Artist</th>
    <th>Album</th>
  </tr>
  <?php
    $sql = "select * from top_albums where artist like '%$search%'";
    $result = $conn->query($sql);

    if ($result->num_rows > 0){
    while ($row = $result->fetch_assoc())
    {
      echo("<tr><td>".$row["artist"]."</td><td>".$row["album"]."</td></tr>");
    }
    } else {
        echo "0 records";
}

$conn->close();
 ?>
</table>

Thanks in advance




Aucun commentaire:

Enregistrer un commentaire