Populating a Drop Down list with data from a database


Small script that demonstrates how to populate a drop down list or menu with data retrieved from a database using PHP and MYSQL.  Below I copy / pasted a sample data that I’m use as well as the MYSQL statement to query the database. 

Drop down list 
<form method="" name="testForm" id="testForm">
      <label>drop down select </label> 
      <select name="user_list" >
           <?php 
                foreach($get_userList as $user) { 
                    echo '<option value=' . $user['index'] . '>' . $user['FirstName']." " .
                          $user['FirstName'] .'</option>';
                } 
            ?> 
         </select> 
    </form>

Database query
Try {
     $stmt = $pdo->query('SELECT * FROM tb_testing'); 
     $get_userList = $stmt->fetchAll(PDO::FETCH_ASSOC);  
    }
    catch(PDOException $e) { 
        echo $e->getMessage().'Unable to access table'; 
    }

Sample data:
Array
(
    [0] => Array
        (
            [user] => 1
            [FirstName] => Trevor
            [LastName] => Day
            [Phone] => 1-392-702-0719
        )

    [1] => Array
        (
            [user] => 2
            [FirstName] => Grady
            [LastName] => Bradford
            [Phone] => 1-815-569-6815
        )

    [2] => Array
        (
            [user] => 3
            [FirstName] => Elmo
            [LastName] => Willis
            [Phone] => 1-192-945-6652
        )

    [3] => Array
        (
            [user] => 4
            [FirstName] => September
            [LastName] => Russo
            [Phone] => 1-609-342-2362
        )

    [4] => Array
        (
            [user] => 5
            [FirstName] => Sara
            [LastName] => Mercado
            [Phone] => 1-648-419-7298
        )

1 comment: