Skip to content
PHP Logo

What are the advantages of using PDO over the mysql functions in PHP for database interactions?

Using PDO over the mysql functions in PHP for database interactions provides several advantages, including better security through prepared statements that help prevent SQL injection attacks, support for multiple database systems (not just MySQL), and object-oriented interface that allows for easier maintenance and code readability.

php
// Using PDO for database interactions
try {
    $pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");
    $stmt = $pdo->prepare("SELECT * FROM users WHERE id = :id");
    $stmt->bindParam(':id', $id, PDO::PARAM_INT);
    $stmt->execute();
    $result = $stmt->fetch();
} catch (PDOException $e) {
    echo "Error: " . $e->getMessage();
}