Raddy Website Design & Development Tutorials

Show selected option value from Array & MySQL DB using PHP

By Raddy in PHP ·

In this tutorial, you will learn how to create an array of categories, display the values inside HTML select box and have selected options pre-defined with PHP and also I will show you how to get the selected options from a database using the ID of the record.

Full project code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Select Option Dropdown</title>
</head>
<body>
    <style>
        body {
            font-size: 2em;
        }
        .container {
            display: grid;
            grid-template-rows: repeat(2, 1fr);
            grid-template-columns: repeat(2, 1fr);
            grid-gap: 6rem;
            padding: 5rem;
            border: 1px solid #ccc;
            justify-content: space-evenly;
        }
        select {
            font-size: 1em;
        }
    </style>

    <div class="container">
        <div>Selected From Array</div>
        <div>Selected From DB Record</div>
        <div>
            <?php
                $selected = "Adult";
                $options = array('Comedy', 'Adventure', 'Drama', 'Crime', 'Adult', 'Horror');
                echo "<select>";
                foreach($options as $option){
                    if($selected == $option) {
                        echo "<option selected='selected' value='$option'>$option</option>";
                    }
                    else {
                        echo "<option value='$option'>$option</option>";
                    }
                }
                echo "</select>";
            ?>
        </div>
        <div>
        
        <?php
        define('DB_SERVER', 'localhost');
        define('DB_USERNAME', 'root');
        define('DB_PASSWORD', 'password');
        define('DB_NAME', 'phplearning');

        $link = mysqli_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_NAME);

        if($link === false){
            die("Error: Could not connect." . mysqli_connect_error());
        }

        if(isset($_GET['category'])){
            $categoryName = $_GET['category'];

            $sql = "SELECT * FROM categories WHERE id = $categoryName";
            if($result = mysqli_query($link, $sql)) {
                if(mysqli_num_rows($result) > 0) {
                    while($row = mysqli_fetch_array($result)){
                        $dbselected = $row['category'];
                    }
                    // Function frees the memory associated with the result
                    mysqli_free_result($result);
                }
                else {
                    echo "Something went wrong...";
                }
            }
            else {
                echo "ERROR: Could not execute $sql." . mysql_error($link);
            }
        }

        $options = array('Comedy', 'Adventure', 'Drama', 'Crime', 'Adult', 'Horror');
        echo "<select>";
        foreach($options as $option){
            if($dbselected == $option) {
                echo "<option selected='selected' value='$option'>$option</option>";
            }
            else {
                echo "<option value='$option'>$option</option>";
            }
        }
        echo "</select>";
        ?>
        
        </div>
    </div>
</body>
</html>

Thank you for reading this article. Please consider subscribing to my YouTube Channel.

      1. katlego says:

        youre the man!!!

        1. Raddy says:

          šŸ˜ŽšŸ˜€

  1. Venkatesh says:

    Sir,

    I have a website works in local host.

    I have some additional features like search, filter option according to city state basis.

    if you are interested to do kindly let me know that i send you the files to update.

    1. Raddy says:

      You have created those features and you wish to publish them on my blog or you want me to make tutorials on how to do them?

  2. Nani says:

    Nice one Raddy!

  3. rahul lohar says:

    Editor *

    –select–

    <option value="”>

    hi im acquiring data from db using function , but when i try to edit it , it doesnt show the already selected value, please help

    1. Raddy says:

      Are you sure you are getting the data you need from the database? Strange that the options are not there. Double-check to see if you have any typos

  4. Nilton Oliveira says:

    How to use select option (insert, update)
    tbCustomers(idCustomer,NameCustomer,phoneCustomer,idState,idCity)
    tbStates (idState, nameState)
    tbCities(idCity,nameCity,idState)

    I’ve done several searches on the internet, this part seems complicated in php. because finding help like this is difficult.

    1. Raddy says:

      Sometimes is hard to find answers when you have a very specific question. Saying this I am not sure if I understand your question well. Can you give me more details? Maybe a short explanation of what you are trying to achieve.

      1. Nilton Oliveira says:

        Construct the select using data from two foreign key tables
        1. First the customer table – customer data:
        (Name, Address, State, City)
        2. State table, where the customer resides;
        3. City table, your city;

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.