What is PDO in PHP

PDO, or PHP Data Objects, is a database access layer that provides a uniform method of access to different databases. It enables developers to interact with a variety of database management systems (DBMS) using a consistent API. PDO is designed to help developers write database-agnostic code and provides features such as prepared statements, which help prevent SQL injection attacks.

With PDO, you can connect to databases like MySQL, PostgreSQL, SQLite, and more, allowing for greater flexibility in application development. It also supports transactions, error handling, and different fetching modes for retrieving and processing data.

Example Usage of PDO in PHP


try {
    // Create a new PDO instance
    $pdo = new PDO('mysql:host=localhost;dbname=testdb', 'username', 'password');
    // Set the PDO error mode to exception
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    // Prepare and execute a SQL statement
    $stmt = $pdo->prepare('SELECT * FROM users WHERE email = :email');
    $stmt->execute(['email' => 'example@example.com']);

    // Fetch the result
    $user = $stmt->fetch(PDO::FETCH_ASSOC);
    print_r($user);

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

PDO PHP Data Objects database access prepared statements SQL injection PHP database management systems MySQL PostgreSQL SQLite