Sobes.tech
Junior — Middle

Can you explain what PHP Data Objects (PDO) are and their role in working with databases?

sobes.tech AI

Answer from AI

PHP Data Objects (PDO) is a PHP extension that provides a unified interface for working with various databases. It allows executing queries, retrieving results, and managing transactions through the same set of methods, regardless of the type of DBMS (MySQL, PostgreSQL, SQLite, etc.).

Main advantages of PDO:

  • Database abstraction: code becomes portable across different DBMS.
  • Support for prepared statements, which enhances security by preventing SQL injections.
  • Transaction management.

Example of using PDO to connect and fetch data from MySQL:

try {
    $pdo = new PDO('mysql:host=localhost;dbname=testdb', 'user', 'password');
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $stmt = $pdo->prepare('SELECT * FROM users WHERE email = :email');
    $stmt->execute(['email' => 'example@example.com']);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);

    print_r($user);
} catch (PDOException $e) {
    echo 'Connection error: ' . $e->getMessage();
}