Skip to content Skip to sidebar Skip to footer

How Can I Create A Dropdown Menu To Search My Mysql Database?

I have to create a search form to retrieve data from a MySQL database. I used this to create a dropdown selection of one category. It does work, and the menu is clearly linked to t

Solution 1:

First, you need to fix your <select> and <option> elements. The select tag should have the name attribute. The <option> element doesn't have a name or type attribute. You also have a closing </fieldset> which you never open. Your <label> tag is also pointing to an invalid element. To submit the form, you need to have a submit button.

When the whole HTML is fixed it should look something like this:

<formclass="form-horizontal"action="search_keyword.php">
    Analysegegenstand
    <labelclass="col-md-4 control-label"for="searchinput">Analysegegenstand</label><selectname="type_select"id="searchinput"><optiondisabledselected>Analysegegenstand wählen</option><?phpinclude"db_connect.php";

        $records = mysqli_query($mysqli, "SELECT Analysegegenstand From Analysegegenstand");

        while ($data = mysqli_fetch_array($records)) {
            echo"<option value='" . htmlspecialchars($data['Analysegegenstand']) . "'>" . htmlspecialchars($data['Analysegegenstand']) . "</option>";
        }
        ?></select><inputtype="submit"value="Search"></form>

When the form gets submitted the value of your <select> will be available as $_GET['type_select'] because your <select> has a name="type_select".

All you need to do is to construct an SQL query using a prepared statement and execute the query with the selected value. The value you get from the form will be used in the WHERE query to compare it against the column you are trying to search in. The field you want to select need to be listed in the SELECT query too. After preparing, the value will be bound to the statement and then execute on the MySQL database server. It is then up to you to handle the results however you want to.

In your search_keyword.php file:

<?phpif (isset($_GET['type_select'])) {
    include"db_connect.php";

    $stmt = $mysqli->prepare("SELECT searched_fields FROM information WHERE searchable=?");
    $stmt->bind_param('s', $_GET['type_select']);
    $stmt->execute();
    $result = $stmt->get_result();
    foreach ($resultas$row) {
        printf("Found: %s\n", $row['searched_fields']);
    }
}

Tips:

  • You can use LIKE instead of = in SQL to allow users to search using wildcards % and _.
  • It is much better to use PDO than mysqli. It's easier and offers more functionality.
  • Don't mix HTML and PHP. Keep the database logic separate from presentation logic. Use PHP only to display the data within HTML, but prepare the data in a separate PHP file.
  • Use htmlspecialchars() whenever displaying any data within HTML context.

Post a Comment for "How Can I Create A Dropdown Menu To Search My Mysql Database?"