What are the advantages of using PDO for database access in PHP scripts?

When writing PHP scripts that interact with databases, it is important to use a secure and reliable method for database access. One common way to achieve this is by using PDO (PHP Data Objects) which provides a consistent interface for accessing different types of databases, such as MySQL, PostgreSQL, SQLite, etc. PDO also helps prevent SQL injection attacks by using prepared statements, making it a safer choice for database operations in PHP.

// Connect to a MySQL database using PDO
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

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