Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP MySQL edit form select dropdown preselected

Tags:

php

mysql

I have certainly browsed and just haven't been able to get this seemingly easy answer!

I have a form where I can update records, and I can also edit them by clicking on the edit button I made. When I click to edit them, I obviously want the current settings to be chosen by default. Through $_GET variables, I have prefilled in the text inputs with their correct values from the DB.

However, I have three dropdown lists, and I am unable to get these to choose their correct value and name.

My form, for one example, has a dropdown list of all my users coming from a query of:

SELECT
    users.id AS 'Users ID',
    users.first_name AS 'User First Name',
    users.last_name AS 'User Last Name'
FROM users
ORDER BY users.first_name;

With the following it is correctly showing the list of users by name, and the values are being sent as IDs to the DB

<div class="form-group">
    <label>Choose User</label><br />
    <select name="userid">
    <?php
        while($usersrow = $usersresult->fetch_assoc()) {
        //Display Customer Info
        $output = '<option value="'.$usersrow['User ID'].'">'.$usersrow['User First Name'].' '.$usersrow['User Last Name'].'</option>';

        //Echo output
        echo $output;                   
        }
    ?>
    </select>
</div>

With this as a setup, does anybody know how I can go to my edit field and have my dropdown preselected where the values remain the users ID? I have tried quite a few different ways including concatening with ternary if, and other $_GET variables of $id (for user id) and $name (for user name), but to no avail.

Any help is appreciated!

EDIT

To put it a bit more simply...I am trying to have my dropdown be preselected based off of a $id $_GET variable that matches the value in a dropdown option.

Thanks

like image 704
Ridge Robinson Avatar asked Apr 20 '26 17:04

Ridge Robinson


1 Answers

Set the selected attribute for the option that matches the userId being edited:

<div class="form-group">
    <label>Choose User</label><br />
    <select name="userid">
    <?php
        while($usersrow = $usersresult->fetch_assoc()) {
        //Display Customer Info
        if($usersrow['User ID'] == $_GET['userid']){
          $selected = "selected";
        }else{
          $selected = "";
        }
        $output = '<option value="'.$usersrow['User ID'].'" '.$selected.'>'.$usersrow['User First Name'].' '.$usersrow['User Last Name'].'</option>';

        //Echo output
        echo $output;                   
        }
    ?>
    </select>
</div>
like image 168
Evis Bregu Avatar answered Apr 23 '26 07:04

Evis Bregu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!