In what situations is it recommended to switch from using mysql_connect to PDO in PHP for database connections, and what are the advantages of doing so?

It is recommended to switch from using mysql_connect to PDO in PHP for database connections when you need to improve security, portability, and flexibility in your code. PDO provides a more secure way to interact with databases by supporting prepared statements and parameterized queries, making it less vulnerable to SQL injection attacks. Additionally, PDO allows you to work with multiple database systems using the same codebase, providing better portability. Lastly, PDO offers a more object-oriented approach to working with databases, making your code cleaner and easier to maintain.

// Using PDO for database connection
$dsn = 'mysql:host=localhost;dbname=my_database';
$username = 'username';
$password = 'password';

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