PDO Introduction

Ma Mahalakshmi V Updated 14 Nov 2026
5 min read ·Lesson 207 of 255

What Is PDO?

In simple terms: PDO (PHP Data Objects) is PHP's standard way to talk to databases. With one consistent set of classes and methods, you can work with MySQL, MariaDB, PostgreSQL, SQLite, SQL Server, and more. Learning PDO once means you can use the same code style with any of them.

Technically: PDO is a data-access abstraction layer. It provides a uniform API — connecting, preparing statements, binding parameters, fetching results, handling transactions and errors — while database-specific drivers (pdo_mysql, pdo_pgsql, pdo_sqlite, …) handle communication with each database. PDO does not translate SQL between databases: SQL dialect differences remain your responsibility.

Why PDO Is the Common Choice

AdvantageExplanation
One API for many databasesSwitching between MySQL in production and SQLite in tests requires mostly configuration changes
Named placeholders:email instead of ? makes queries with many parameters readable
Flexible fetch modesRows as arrays, objects, key-value pairs, grouped arrays, or instances of your classes
Exceptions by defaultSince PHP 8.0, errors throw PDOException
Industry standardLaravel, Symfony/Doctrine, and most libraries are built on PDO

PDO vs MySQLi

PDOMySQLi
DatabasesMany (via drivers)MySQL / MariaDB only
Placeholders? and named :name? only
Fetching into objects of your classesPDO::FETCH_CLASSfetch_object($class)
MySQL-specific featuresMostAll (async queries, multi-statement helpers)
API styleObject-orientedObject-oriented and procedural

Both are secure when used with prepared statements. The previous lessons used MySQLi; this part of the section shows the same tasks with PDO. For new projects, PDO is generally recommended.


The Three Core Classes

ClassRepresentsExamples of Methods
PDOA database connectionprepare(), query(), exec(), beginTransaction(), lastInsertId()
PDOStatementA prepared statement and its resultexecute(), bindValue(), fetch(), fetchAll(), rowCount()
PDOExceptionA database errorgetMessage(), getCode(), errorInfo

PHP 8.4 also added driver-specific subclasses such as Pdo\Mysql and Pdo\Sqlite, which expose features unique to each database.


Checking the Available Drivers

<?php
print_r(PDO::getAvailableDrivers());

Output (depends on the installed extensions)

Array
(
    [0] => mysql
    [1] => sqlite
)

The driver name must be installed and enabled for the database you want to use (on Ubuntu, php8.4-mysql provides pdo_mysql, and php8.4-sqlite3 provides pdo_sqlite).


A First Complete Example

The following script works without a database server, because SQLite can run in memory. The same code works with MySQL by changing only the connection line.

<?php
$pdo = new PDO('sqlite::memory:');
// MySQL: new PDO('mysql:host=127.0.0.1;dbname=gocourse_shop;charset=utf8mb4', $user, $password);

$pdo->exec('CREATE TABLE products (
    id INTEGER PRIMARY KEY,
    sku TEXT NOT NULL UNIQUE,
    name TEXT NOT NULL,
    price_paise INTEGER NOT NULL
)');

$insert = $pdo->prepare('INSERT INTO products (sku, name, price_paise) VALUES (:sku, :name, :price)');

foreach ([['PEN-01', 'Gel Pen', 2000], ['LAMP-01', 'Desk Lamp', 129900]] as [$sku, $name, $price]) {
    $insert->execute(['sku' => $sku, 'name' => $name, 'price' => $price]);
}

echo "Last inserted ID: " . $pdo->lastInsertId() . "\n";

$select = $pdo->prepare('SELECT name, price_paise FROM products WHERE price_paise > :min ORDER BY price_paise');
$select->execute(['min' => 1000]);

foreach ($select->fetchAll(PDO::FETCH_ASSOC) as $row) {
    echo $row['name'] . ': ₹' . number_format($row['price_paise'] / 100, 2) . "\n";
}

Output

Last inserted ID: 2
Gel Pen: ₹20.00
Desk Lamp: ₹1,299.00

How It Works

  1. new PDO($dsn) opens a connection. The DSN (data source name) sqlite::memory: selects the SQLite driver and an in-memory database that disappears when the script ends.
  2. exec() runs a statement that returns no rows (here, CREATE TABLE).
  3. prepare() creates a statement with named placeholders (:sku, :name, :price); execute() receives the values as an associative array. The statement is prepared once and executed twice.
  4. lastInsertId() returns the ID of the last inserted row — as a string.
  5. The SELECT uses a placeholder as well; fetchAll(PDO::FETCH_ASSOC) returns all rows as associative arrays.

Every step — connecting, preparing, executing, fetching — follows the same pattern for every database.


query(), exec(), and prepare()

MethodUse ForReturns
$pdo->exec($sql)Fixed statements without results (CREATE, fixed UPDATE)Number of affected rows
$pdo->query($sql)Fixed SELECT statements without external valuesPDOStatement
$pdo->prepare($sql) + execute($params)Any statement with values from outside the codePDOStatement

Use exec() and query() only for SQL written entirely in your code. As soon as a value comes from a user, a file, an API, or even the database, use prepare() (see PDO Prepared Statements).


The PDO Lessons in This Section

LessonTopic
PDO ConnectDSNs, options, configuration, and connection errors
PDO Prepared StatementsPositional and named placeholders, binding, and security
PDO Fetch ModesGetting rows as arrays, objects, key-value pairs, and groups
PDO TransactionsMaking several changes succeed or fail together
PDO Error HandlingExceptions, SQLSTATE codes, and translating database errors

Common Misconceptions

"PDO Makes My SQL Portable"

PDO unifies the PHP API, not the SQL language. MySQL's LIMIT, PostgreSQL's RETURNING, and SQLite's type system differ. Query builders and ORMs (Doctrine DBAL, Laravel's query builder) generate database-specific SQL for you.

"PDO Automatically Prevents SQL Injection"

Only when values are passed through placeholders. Concatenating input into SQL is just as dangerous with PDO as with any other API.

"PDO::query() Is Safe Because It Is PDO"

query() executes the SQL string as given. Use it only for fixed SQL.


Best Practices

  • Use PDO for new projects, especially if more than one database type may be involved.
  • Use prepared statements for every value that does not come from your code.
  • Configure the connection consistently (error mode, fetch mode, charset) in one place.
  • Test with SQLite where appropriate, but keep in mind the SQL differences from MySQL.
  • Move on to a query builder or ORM when an application's data access grows complex.

Official reference: https://www.php.net/manual/en/intro.pdo.php

0 Comments

Reviewed before they appear

No comments yet.

PHP
PHP Home PHP Intro PHP Install PHP Built-in Web Server PHP Syntax PHP Tags PHP and HTML PHP Comments PHP Multiline Comments PHP Variables Variables Scope Static Variables Variable Variables PHP Echo / Print PHP printf / sprintf PHP Data Types PHP Booleans PHP NULL PHP Strings String Functions Modify Strings Concatenate Strings Slicing Strings Escape Characters String Interpolation Heredoc and Nowdoc Search in Strings Multibyte Strings PHP Floats PHP Casting PHP Type Juggling PHP Math PHP Random Numbers PHP Constants PHP Magic Constants PHP Operators Arithmetic Operators Assignment Operators Comparison Operators Increment / Decrement Operators Logical Operators Null Coalescing Operator Spaceship Operator Operator Precedence PHP If...Else...Elseif PHP If PHP If Operators PHP If...Else PHP Shorthand if PHP Nested if PHP Switch PHP Match Alternative Syntax PHP Loops While Loop Do While Loop For Loop Foreach Loop Nested Loops Break Statement Continue Statement PHP Functions User-defined Functions Function Arguments Default Argument Values Pass by Reference Named Arguments Variadic Functions Return Values Type Declarations in Functions Recursive Functions Variable Functions Anonymous Functions Closures Arrow Functions First-class Callable Syntax PHP Arrays Indexed Arrays Associative Arrays Create Arrays Access Array Items Update Array Items Add Array Items Remove Array Items Sorting Arrays Multidimensional Arrays Array Destructuring Array Spread Operator Search in Arrays Merge Arrays array_map / array_filter / array_reduce Array Functions PHP Superglobals $GLOBALS $_SERVER $_REQUEST $_POST $_GET $_FILES $_COOKIE $_SESSION \$\_ENV PHP RegEx RegEx Patterns RegEx Modifiers preg_match preg_replace preg_split PHP RegEx Functions PHP Form Handling PHP Form Validation PHP Form Required PHP Form URL/E-mail Form Input Sanitizing Escaping Output (htmlspecialchars) Checkbox, Radio and Select Inputs Sticky Forms PHP Form Complete PHP Date and Time Date Formatting DateTime Class Timezones PHP Include Include vs Require PHP File Handling PHP File Open/Read PHP File Create/Write File Delete / Rename / Copy PHP Directories PHP CSV Files PHP File Upload PHP Cookies PHP Sessions PHP Filters PHP Filters Advanced PHP Callback Functions PHP JSON PHP Exceptions Error Handling Custom Error Handler Error Logging HTTP Headers and Redirects Output Buffering Sending Email PHP cURL Consuming REST APIs PHP Generators PHP What is OOP PHP Classes/Objects The $this Keyword PHP Properties PHP Methods PHP Constructor Constructor Property Promotion PHP Destructor PHP Access Modifiers Readonly Properties PHP Inheritance Method Overriding The final Keyword PHP Class Constants PHP Abstract Classes PHP Interfaces Polymorphism PHP Traits PHP Static Methods PHP Static Properties Late Static Binding Magic Methods Object Cloning Comparing Objects Anonymous Classes PHP Enums PHP Namespaces Autoloading Classes PHP Iterables Iterators Object Serialization Strict Types Union Types Nullable Types Mixed and Never Types Nullsafe Operator PHP Attributes PHP Fibers Readonly Classes Property Hooks (PHP 8.4) Asymmetric Visibility (PHP 8.4) Reflection API SPL Data Structures MySQL Database MySQL Connect MySQL Create DB MySQL Create Table MySQL Insert Data MySQL Get Last ID MySQL Insert Multiple MySQL Prepared MySQL Select Data MySQL Where MySQL Order By MySQL Delete Data MySQL Update Data MySQL Limit Data MySQL Joins with PHP Pagination with PHP PDO Introduction PDO Connect PDO Prepared Statements PDO Fetch Modes PDO Transactions PDO Error Handling PHP XML Parsers PHP SimpleXML Parser PHP SimpleXML - Get PHP XML Expat Parser PHP DOM Parser PHP XMLReader PHP XMLWriter AJAX Intro AJAX PHP AJAX Database AJAX XML AJAX Live Search AJAX Poll AJAX with JSON Security Introduction Password Hashing SQL Injection Prevention XSS Prevention CSRF Protection Session Security Secure Cookies File Upload Security Filesystem Security Error Reporting in Production Hiding PHP Encryption with Sodium PHP Configuration (php.ini) PHP Command Line (CLI) Composer PSR-4 Autoloading Installing Extensions (PECL / PIE) Debugging PHP OPcache & Performance Garbage Collection PHP-FPM Migrating to PHP 8 Project: Contact Form with Email Project: Login & Registration System Project: CRUD App with MySQL Project: Image Upload Gallery Project: Shopping Cart with Sessions Project: Simple Blog Project: REST API with PHP
Ask about this post
AI Ask about this post

Ask questions about PDO Introduction and get answers drawn from it.

Signed-in readers only.