What are the best practices for handling MySQL connections in PHP, especially considering the deprecation of the mysql_ functions?

With the deprecation of the mysql_ functions in PHP, it is recommended to use MySQLi or PDO for connecting to MySQL databases. These newer extensions provide improved security, performance, and support for modern MySQL features.

// Using MySQLi
$mysqli = new mysqli("localhost", "username", "password", "database_name");

if ($mysqli->connect_error) {
    die("Connection failed: " . $mysqli->connect_error);
}

// Using PDO
try {
    $pdo = new PDO("mysql:host=localhost;dbname=database_name", "username", "password");
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    die("Connection failed: " . $e->getMessage());
}