Reputation: 19
I just try to get my own user management tool, so first of all I just want to display all users by using a table. Then I want to allow to change the roles of the users by using <select>
tags. My problem is that I want to get the current role of every user pre-selected and I want to have the possibility to change by getting an array of the possible roles by searching database. But how is this possible? Here you can see my code:
<?php
header('Content-Type: text/html; charset=UTF-8');
include("db.php"); //just the database connection
session_start();
?>
<html>
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
</head>
<body>
</html>
<?php
$abfrage= mysql_query("SELECT * FROM user ORDER BY Name desc");
//$ergebnis = mysql_query($abfrage) or die( mysql_error() );
echo "<table>";
echo"<caption>Mitglieder<br></caption>";
echo"<table border=\"1\" style=\"width:300px\">";
echo "<th>Name</th>
<th>Prename</th>
<th>Role</th>";
while($row = mysql_fetch_object($abfrage)) {
echo "<tr>";
echo "<td align=center>",$row->Name,"</td>";
echo "<td align=center>",$row->Prename,"</td>";
echo "<td align=center><select><option value=",$row->Role,">",$row->Role,"</option></select></td>";
//Here is the Problem
echo "</tr>";
}
echo "</table>";
?>
It displays the table with the users and their role from database correctly. Bur I need to get the other roles selectable. I hope someone can help me.
Upvotes: 1
Views: 279
Reputation: 1066
EDIT - ADD SQL QUERY:
$available_roles = [];
$available_roles_query = mysql_query("SELECT * FROM roles");
while($role = mysql_fetch_object($available_roles_query)){
$available_roles[] = $role->Name;
}
ORIGINAL POST:
while($row = mysql_fetch_object($abfrage)): ?>
<tr>
<td align="center"><?php echo $row->Name; ?></td>
<td align="center"><?php echo $row->Prename; ?></td>
<td align="center">
<select>
<option value="none">Please Select:</option>
<?php foreach($available_roles as $role): ?>
<?php if($row->Role == $role): ?>
<option value="<?php echo $role; ?>" selected="true"><?php echo $role; ?></option>
<?php else: ?>
<option value="<?php echo $role; ?>"><?php echo $role; ?></option>
<?php endif; ?>
<?php endforeach; ?>
</select>
</tr>
<?php endwhile;
Anything you don't understand, let me know. I'm too tired to write out explanations for the most probable issues you might have.
P.S. This won't allow you to update values. You'll need to add that functionality yourself, and when you do I'd recommend using different keys for each role than its name.
Upvotes: 3
Reputation: 267
1.you need get all roles as array
$roles = ['admin', 'user', .....]; // or you can get roles from database
2.loop the roles
$options = "<option value=".$row->Role.">".$row->Role."</option>";
foreach( $roles as $role ){
$options .= "<option value={$role}>{$role}</option>";
}
echo "<td align=center><select>{$options}</select></td>";
Upvotes: 0