What best practices should be followed when connecting to a database in PHP to avoid unnecessary connections and improve performance?
To avoid unnecessary connections and improve performance when connecting to a database in PHP, it is recommended to use a persistent connection instead of creating a new connection for each request. This can be achieved by using the PDO extension and setting the `PDO::ATTR_PERSISTENT` attribute to `true`.
<?php
$dsn = 'mysql:host=localhost;dbname=mydatabase';
$username = 'username';
$password = 'password';
$options = array(
PDO::ATTR_PERSISTENT => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
);
try {
$dbh = new PDO($dsn, $username, $password, $options);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}