What are the best practices for handling SQL database connections in PHP?

To handle SQL database connections in PHP, it is recommended to use PDO (PHP Data Objects) for a more secure and flexible approach. PDO provides a consistent interface for accessing databases and supports multiple database drivers.

// Database connection using PDO
$dsn = 'mysql:host=localhost;dbname=mydatabase';
$username = 'username';
$password = 'password';

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