What are the advantages of using PDO over traditional mysql_connect for database operations in PHP scripts?
Using PDO over traditional mysql_connect in PHP scripts offers several advantages such as improved security through prepared statements, support for multiple database drivers, and better error handling capabilities. PDO also provides a more consistent and object-oriented approach to interacting with databases, making code more readable and maintainable.
<?php
// Using PDO for database operations
$dsn = 'mysql:host=localhost;dbname=mydatabase';
$username = 'username';
$password = 'password';
try {
$pdo = new PDO($dsn, $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Perform database operations using $pdo object
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
?>