What are the recommended alternatives to using the MySQL extension in PHP, and why are they preferred?

The MySQL extension in PHP is deprecated and removed in PHP 7.0 and later versions. It is recommended to use either the MySQLi extension (improved version of MySQL) or PDO (PHP Data Objects) for database operations in PHP. These alternatives provide better security, support for prepared statements, and are more versatile in handling different types of databases.

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

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

// Using PDO
$pdo = new PDO("mysql:host=localhost;dbname=database", "username", "password");

if (!$pdo) {
    die("Connection failed");
}