What are the advantages and disadvantages of using PDO vs mysqli for database connection in PHP?
When choosing between PDO and mysqli for database connection in PHP, PDO is often preferred for its flexibility and support for multiple database types, while mysqli is known for its procedural style that may be easier for beginners to understand. However, PDO offers better security features such as prepared statements and parameterized queries, making it a more secure option overall.
// Using PDO for database connection in PHP
try {
$pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}