What are the best practices for handling database connections and queries in PHP, especially when transitioning from the deprecated mysql_* functions to PDO?

When transitioning from the deprecated mysql_* functions to PDO in PHP for handling database connections and queries, it is best practice to use prepared statements to prevent SQL injection attacks and improve performance. PDO also provides a more secure and flexible way to connect to different types of databases.

// Establishing a PDO connection to a MySQL database
$host = 'localhost';
$dbname = 'database_name';
$username = 'username';
$password = 'password';

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