What are the advantages of using prepared statements or PDO instead of the mysql extension for interacting with databases in PHP?

Using prepared statements or PDO instead of the mysql extension in PHP offers several advantages, including improved security by preventing SQL injection attacks, better performance through query optimization, and increased flexibility by supporting multiple database types. Prepared statements separate SQL logic from data input, reducing the risk of malicious code injection and improving code readability.

// Using PDO to interact with a database
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');

// Prepare a statement
$stmt = $pdo->prepare('SELECT * FROM users WHERE email = :email');

// Bind parameters and execute the statement
$email = 'example@example.com';
$stmt->bindParam(':email', $email);
$stmt->execute();

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