What are the potential advantages of using PDO over mysqli for database connections in PHP?
When it comes to database connections in PHP, PDO (PHP Data Objects) is often preferred over mysqli due to its flexibility and support for multiple database types. PDO provides a consistent interface for accessing databases, making it easier to switch between different database systems without changing much code. It also supports prepared statements, which can help prevent SQL injection attacks.
// Using PDO for database connection
$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);
echo "Connected successfully";
} catch (PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}