What are the benefits of using PDO in PHP for database connections?
When connecting to a database in PHP, using PDO (PHP Data Objects) is recommended due to its security features, flexibility, and support for multiple database types. PDO helps prevent SQL injection attacks by using prepared statements, allows for easier code maintenance and portability, and provides a consistent interface for interacting with different database systems.
// Database connection using PDO
$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();
}