What are the differences between using mysqli_ and PDO for database access in PHP, and which one is recommended for security reasons?
When accessing databases in PHP, using PDO (PHP Data Objects) is recommended for security reasons over mysqli_. PDO provides a more secure and flexible way to interact with databases, as it supports multiple database systems and uses prepared statements to prevent SQL injection attacks. Additionally, PDO provides a more consistent interface for working with different databases.
// Using PDO for database access 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();
}