How can PHP beginners effectively create a function or class to connect to a database using PDO?

To effectively create a function or class to connect to a database using PDO in PHP, beginners can encapsulate the connection logic in a reusable function or class. This helps in maintaining a clean and organized codebase while promoting reusability and scalability.

// Function to connect to a database using PDO
function connectToDatabase($host, $dbname, $username, $password) {
    try {
        $pdo = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        return $pdo;
    } catch (PDOException $e) {
        die("Connection failed: " . $e->getMessage());
    }
}

// Example usage
$pdo = connectToDatabase('localhost', 'mydatabase', 'root', 'password');