How can PHP be used to control which columns are visible to different users in a table?
To control which columns are visible to different users in a table, you can use PHP to dynamically generate the table based on the user's permissions or role. You can create an array of column names that are allowed to be displayed for each user role, and then loop through this array to only display the allowed columns in the table.
<?php
// Define user roles and their allowed columns
$userRoles = [
'admin' => ['id', 'name', 'email', 'role'],
'user' => ['id', 'name', 'email']
];
// Get current user role (for demonstration purposes)
$userRole = 'admin';
// Table data
$tableData = [
['id' => 1, 'name' => 'John Doe', 'email' => 'john@example.com', 'role' => 'admin'],
['id' => 2, 'name' => 'Jane Smith', 'email' => 'jane@example.com', 'role' => 'user']
];
// Display table
echo '<table>';
echo '<tr>';
foreach ($userRoles[$userRole] as $column) {
echo '<th>' . ucfirst($column) . '</th>';
}
echo '</tr>';
foreach ($tableData as $row) {
echo '<tr>';
foreach ($userRoles[$userRole] as $column) {
echo '<td>' . $row[$column] . '</td>';
}
echo '</tr>';
}
echo '</table>';
?>
Related Questions
- What are common mistakes to avoid when using variables in PHP function parameters?
- What best practices should be followed when handling database connections and query results in PHP scripts to avoid errors and improve performance?
- What could be causing the issue of PHP code displaying in Opera and IE browsers?