Search code examples
phppdoforeachselected

Foreach role_id HTML select options


I'm updating a small page where I can update a users info.

I have this query, where I join two database tabels:

SELECT * FROM users JOIN roles ON roles.id = users.`role_id` WHERE users.id=$id

To output the the name of the role according to the role id, i've created the variable $role

$role = $result["role_name"];

So that I can outbut it just by echoing $role

What I would like to be able to do, is to have a form where I can select the users role. And also display the users current role with the selected attribute.

Something similar to this (my old solution):

<select name="role">                    
<?php
if ($role == 'Admin')
{
echo "<option value='Admin' Selected>";
}
else
{
echo "<option value='Admin'>";
}
echo "Admin </option>";

if ($role == 'User')
{
echo "<option value='User' Selected>";
}
else 
{
echo "<option value='User'>";
}
echo "User </option>";

?>
</select>

But as you can see, this was not very scalable. If i added a new role to my DB I would have to manually update my select code with another if statement.

Therefor I was thinking that it could be a possibility to use a foreach statement instead. But I simply can't wrap my head around how to mark the users current role with the Selected attribute.

To get all my roles in an array, I've done this:

$sql = $db->prepare ("SELECT * FROM roles");
$sql->execute ();
$roles = $sql->fetchAll ();

And the array will look like this:

Array ( [0] => Array ( [id] => 1 [role_name] => Admin ) [1] => Array ( [id] => 2 [role_name] => User ) ) 

Solution

  • You could populate an array of roles from your database in this format:

    $roles = array( "Admin" => 1, "User" => 2, ...);
    

    then create the options like this between your select tags:

    foreach($roles as $k => $v)
    {
        $s = $role_id == $v ? "selected" : "";
        echo("<option value='$v' $s>$k</option>");
    }