How can PDO be used to simplify data retrieval and manipulation in PHP?

Using PDO in PHP simplifies data retrieval and manipulation by providing a consistent interface for interacting with different types of databases. It helps prevent SQL injection attacks by automatically escaping input parameters. Additionally, PDO supports prepared statements, which can improve performance when executing the same query multiple times.

// Connect to the database using PDO
$dsn = 'mysql:host=localhost;dbname=mydatabase';
$username = 'username';
$password = 'password';
try {
    $pdo = new PDO($dsn, $username, $password);
} catch (PDOException $e) {
    echo 'Connection failed: ' . $e->getMessage();
}

// Prepare and execute a query using PDO
$stmt = $pdo->prepare('SELECT * FROM users WHERE id = :id');
$stmt->bindParam(':id', $id, PDO::PARAM_INT);
$id = 1;
$stmt->execute();

// Fetch data from the query result
$user = $stmt->fetch(PDO::FETCH_ASSOC);
echo $user['username'];