What are the differences between using mysqli and PDO in PHP for database interactions, and what are the advantages of using PDO?
When it comes to database interactions in PHP, both mysqli and PDO are popular choices. PDO offers a more flexible and secure way to interact with databases compared to mysqli. PDO supports multiple database systems, while mysqli is specific to MySQL databases. Additionally, PDO provides prepared statements which help prevent SQL injection attacks.
// Using PDO for database interactions
try {
$pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $pdo->prepare("SELECT * FROM users WHERE id = :id");
$stmt->bindParam(':id', $userId, PDO::PARAM_INT);
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
// Do something with the result
} catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}