Sobes.tech
Junior — Middle

What is the main function and purpose of the PDO extension when working with databases in PHP?

sobes.tech AI

Answer from AI

PDO (PHP Data Objects) is a PHP extension that provides a unified interface for working with databases. Its main function is to abstract the interaction with different DBMSs (MySQL, PostgreSQL, SQLite, etc.) through a single set of methods.

Main advantages of PDO:

  • Allows writing portable code that is independent of the specific database.
  • Supports prepared statements, which enhance security and protect against SQL injection.
  • Provides a convenient and object-oriented interface for executing queries and processing results.

Example of using PDO:

$pdo = new PDO('mysql:host=localhost;dbname=testdb', 'user', 'password');
$stmt = $pdo->prepare('SELECT * FROM users WHERE id = :id');
$stmt->execute(['id' => 1]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);
print_r($user);

Thus, PDO simplifies and standardizes working with databases in PHP.

What is the main function and purpose of the PDO… - sobes.tech