What are the benefits of using PDO and prepared statements in PHP for database interactions compared to traditional MySQL queries?
Using PDO and prepared statements in PHP for database interactions is more secure and helps prevent SQL injection attacks compared to traditional MySQL queries. Prepared statements separate SQL logic from data, which allows the database to distinguish between code and data, making it harder for malicious users to inject harmful code. PDO also provides a consistent interface for accessing different types of databases, making it easier to switch between database systems in the future.
// Using PDO and prepared statements to interact with a MySQL database
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');
$stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username');
$stmt->bindParam(':username', $username);
$stmt->execute();
$results = $stmt->fetchAll();
foreach ($results as $row) {
// Process each row
}