What are the advantages of using PDO and PreparedStatements in PHP for database operations?

Using PDO (PHP Data Objects) and Prepared Statements in PHP for database operations is advantageous because it helps prevent SQL injection attacks by separating SQL logic from user input. Prepared Statements also improve performance by allowing the database to prepare the query once and execute it multiple times with different parameters. Additionally, PDO provides a consistent interface for working with different types of databases, making it easier to switch between database systems without changing your code.

// Connect to the database using PDO
$dsn = 'mysql:host=localhost;dbname=mydatabase';
$username = 'username';
$password = 'password';
$pdo = new PDO($dsn, $username, $password);

// Prepare a SQL statement using a Prepared Statement
$stmt = $pdo->prepare('SELECT * FROM users WHERE id = :id');

// Bind parameters to the Prepared Statement
$id = 1;
$stmt->bindParam(':id', $id);

// Execute the Prepared Statement
$stmt->execute();

// Fetch the results
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Loop through the results
foreach ($results as $row) {
    echo $row['username'] . '<br>';
}