How can a database be integrated into PHP to handle user permissions and access rights effectively?

To handle user permissions and access rights effectively in PHP, a database can be integrated to store user roles, permissions, and access rights. By querying the database based on the user's role, the application can determine what actions the user is allowed to perform. This allows for a flexible and scalable way to manage user permissions.

// Connect to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Query the database to get user permissions based on role
$userRole = "admin";
$sql = "SELECT * FROM permissions WHERE role = '$userRole'";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // Output data of each row
    while($row = $result->fetch_assoc()) {
        echo "Permission: " . $row["permission"] . "<br>";
    }
} else {
    echo "0 results";
}

$conn->close();