Coding tips

PHP PDO Tutorial: The Complete Guide to Safe Database Code (2026)

A complete PHP PDO tutorial: connect, prepared statements, fetch modes, insert and lastInsertId, transactions, password hashing and secure forms, with linked guides.

By 3 min read 5 views
Cover image for PHP PDO Tutorial: The Complete Guide to Safe Database Code (2026)

PDO (PHP Data Objects) is the standard way to talk to a database from modern PHP. It works with MySQL, MariaDB, PostgreSQL and SQLite through one API, and its prepared statements are the simplest reliable defence against SQL injection. This page is the map: a short overview of each step, with a link to the detailed guide for it. Work through them in order if you are learning, or jump to the one you need.

1. Connect to the database

$pdo = new PDO('mysql:host=localhost;dbname=app;charset=utf8mb4', $user, $pass, [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    PDO::ATTR_EMULATE_PREPARES => false,
]);

Keep the username and password in an environment variable or a config file outside the web root, never in a public Git repository. Always set charset=utf8mb4 in the DSN so emoji and non-English text survive.

2. Run queries with prepared statements

Every value that comes from a user goes in through a placeholder, never through string concatenation.

3. Read rows back

4. Insert, update and get the new ID

5. Keep changes consistent with transactions

6. Store users and passwords safely

7. Handle form input and output

8. Build an API on top

PDO vs MySQLi: which should you use?

PDOMySQLi
DatabasesMySQL, PostgreSQL, SQLite and moreMySQL and MariaDB only
Named placeholdersYes (:email)No, only ?
Prepared statementsYesYes
API styleObject-orientedObject-oriented or procedural

Both are safe when used with prepared statements. I recommend PDO for new projects because the same code moves to another database with only a DSN change.

A free tool to speed things up

The PDO prepared statement generator takes a table name and column list and writes ready-to-paste INSERT, SELECT, UPDATE and DELETE code with placeholders. It runs entirely in your browser.

FAQs

Is PDO still used in 2026?

Yes. It is part of core PHP, and frameworks such as Laravel and Symfony (Doctrine DBAL) are built on top of it.

Does PDO prevent SQL injection automatically?

Only when you use placeholders for values. Table and column names cannot be placeholders, so whitelist them in code.

Which PHP version do I need?

The examples on these pages target PHP 8.1 and newer. PHP versions older than 8.1 no longer get security updates.

Share X LinkedIn WhatsApp Facebook
Was this helpful?