There is a PDO tag wiki where you can learn the right way (as well as many other useful things) from someone who had a real experience with PDO.
$dsn = "mysql:host=$host;dbname=$db;charset=utf8";
$opt = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
);
$pdo = new PDO($dsn,$username,$password, $opt);
Unlike all other codes which are useless for handling connection errors (as they set exception mode after the actual connect) it will
- make PHP throw an exception on connection error
- will not reveal sensitive information to a potential attacker on a live server by echoing an error out.
- provide you with indispensable stack trace.
- set the connection encoding in the right place
Unlike your old code it will not die with useless message but it will either
- die with useful error message on-screen
- die with useful error message logged, leaving screen blank
- die with useful error message logged, with conventional error page shown
- not die at all but gracefully handled with designated handler function
... depends on the chosen settings.