What are the best practices for handling database access permissions in PHP?

When handling database access permissions in PHP, it is important to follow the principle of least privilege, meaning granting only the necessary permissions to each user or role. This helps minimize the risk of unauthorized access or data breaches. Additionally, using parameterized queries and prepared statements can help prevent SQL injection attacks.

// Example of setting up database access permissions in PHP using PDO
$dsn = 'mysql:host=localhost;dbname=mydatabase';
$username = 'myuser';
$password = 'mypassword';

try {
    $pdo = new PDO($dsn, $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    echo 'Connection failed: ' . $e->getMessage();
    die();
}