Should user permissions be managed solely in PHP code or also enforced at the database level for better security?

User permissions should be managed at both the PHP code level and enforced at the database level for better security. This approach ensures that access control is implemented consistently across the application and prevents any potential vulnerabilities that may arise from bypassing PHP code.

// PHP code to check user permissions before executing a query

$user_id = $_SESSION['user_id'];
$query = "SELECT * FROM users WHERE id = $user_id AND role = 'admin'";
$result = mysqli_query($conn, $query);

if(mysqli_num_rows($result) > 0) {
    // Execute the query
} else {
    // Handle unauthorized access
}