'How to pass value in dropdown list and render the page in php

I have song lists displayed in my homepage and they are all from my database. I'm thinking about adding a dropdown A-Z filter option so that it can filter based on the song Title first letter.

I'm just wondering how and what the best way to do this so that I don't have to copy and repeat the sql statement for A-Z again and again.

and also just wondering how can I pass the to my dropdown value.

Any help or suggestion will be really appreciated.

// Not sure what will be the best method so that I don't have to copy this query again and again for A-Z
<?php
  require_once '../config.php';
  $sql = "SELECT id, title FROM song Where title like 'A%'";
  $stmt = $conn->prepare($sql);
  $stmt->execute(['title' => $title]);
  // fetch all rows
  $songTitle = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>


//Drop down list, there will be A-Z

        <br>
          <select name="color" id="color">
            <option value="">--- Filter ---</option>
            <option value="A">A</option>
            <option value="B">B</option>
            <option value="C">C</option>
          </select>
        <br>

//Render the list based on selected value in the dropdown option.

        <?php // display the song title
          foreach ($songTitle as $song) {
           echo "<a href='details.php?id={$song['id']}'>{$song['title']} <br> </a>";
          } ?>


Solution 1:[1]

Place the <select> inside a <form action="GET">.

Then you can test for the existence of a value in $_GET["color"] and use this in your query:

$sql = $this->mysql->prepare("SELECT id, title FROM song WHERE title like ?");
$sql->bind_param('s', $_GET["color"]);

You should perform some validation on the value of $_GET["color"] before applying to the SQL. For example, ensuring that $_GET["color"] is set, contains a value preg_match(/^[A-Z]$/, $_GET["color"]); and add a default if $_GET["color"] is not set so that the page functions the first time you load it, and if the user doesn't select a filter value.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1