0
0
PHPprogramming~5 mins

Why PDO is the standard in PHP

Choose your learning style9 modes available
Introduction

PDO helps you talk to many databases in the same way. It keeps your code safe and easy to change.

You want to connect to different types of databases without changing much code.
You need to protect your app from bad data that can cause security problems.
You want to write clean and simple database code.
You plan to switch databases later without rewriting everything.
You want to handle errors in a clear and consistent way.
Syntax
PHP
<?php
$pdo = new PDO('mysql:host=localhost;dbname=testdb', 'user', 'pass');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $pdo->prepare('SELECT * FROM users WHERE id = :id');
$stmt->execute([':id' => 1]);
$user = $stmt->fetch();
?>

PDO uses a consistent way to connect and run queries for many databases.

Prepared statements help keep your app safe from SQL injection attacks.

Examples
Connect to a SQLite database using PDO.
PHP
<?php
$pdo = new PDO('sqlite:/path/to/database.db');
?>
Use a prepared statement to safely insert data.
PHP
<?php
$stmt = $pdo->prepare('INSERT INTO users (name) VALUES (:name)');
$stmt->execute([':name' => 'Alice']);
?>
Set PDO to throw exceptions on errors for easier debugging.
PHP
<?php
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
?>
Sample Program

This program creates a temporary database, adds a user, and fetches that user safely using PDO.

PHP
<?php
try {
    $pdo = new PDO('sqlite::memory:');
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $pdo->exec('CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT)');
    $stmt = $pdo->prepare('INSERT INTO users (name) VALUES (:name)');
    $stmt->execute([':name' => 'Bob']);
    $stmt = $pdo->prepare('SELECT * FROM users WHERE name = :name');
    $stmt->execute([':name' => 'Bob']);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);
    print_r($user);
} catch (PDOException $e) {
    echo 'Error: ' . $e->getMessage();
}
?>
OutputSuccess
Important Notes

PDO supports many databases like MySQL, SQLite, PostgreSQL, and more.

Always use prepared statements to keep your app safe from SQL injection.

Setting error mode to exceptions helps find problems quickly.

Summary

PDO is a safe and flexible way to work with databases in PHP.

It uses prepared statements to protect your app from attacks.

PDO lets you switch databases easily without big code changes.