Learn to Code
All tracks
Learn to Code

Free lessons from scratch to pro — every language, databases and DevOps.

AboutContactPrivacy PolicyTerms of Use

Your progress is saved in this browser. © 2026 Learn to Code

PHP
PHP
0/12 completed
Beginner
Hello PHPVariables and arraysControl flowFunctions
Intermediate
Strings, dates and JSONForms, requests and sessionsDatabases with PDO
Advanced
Object-oriented PHPErrors, exceptions and typesSecurity essentials
Pro
Composer, autoloading and testingLaravel basics
Tracks / PHP / Intermediate

Databases with PDO

Almost every PHP application stores data in a database: users, orders, posts. PDO (PHP Data Objects) is PHP's built-in, database-independent way to talk to MySQL, MariaDB, PostgreSQL, SQLite and others with the same code. The editors here use SQLite in memory, so you can run every example without installing a database server.

Connecting

PHP · editable

The first argument is a DSN (data source name). For other databases:

php
$pdo = new PDO('mysql:host=127.0.0.1;dbname=shop;charset=utf8mb4', 'shop_user', getenv('DB_PASSWORD'), $options);
$pdo = new PDO('pgsql:host=127.0.0.1;dbname=shop', 'shop_user', getenv('DB_PASSWORD'), $options);

Keep passwords out of your code: read them from environment variables or a config file that isn't committed to Git.

Creating tables and inserting rows

PHP · editable

exec runs a statement that returns no rows; query runs a fixed query and returns rows you can loop over.

Prepared statements: the most important rule

Never put user input directly into SQL. Use prepared statements with placeholders, and pass the values separately. The database then treats them strictly as data:

PHP · editable

The first query is an SQL injection: the attacker's quote broke out of the string and added OR '1'='1', which is always true, so every user was returned. With a prepared statement, the whole input is compared as one value. SQL injection has been one of the most common and damaging web vulnerabilities for decades; prepared statements prevent it completely.

Placeholders can be positional (?) or named (:email). They work for values only, not for table or column names. If those must vary, check them against a fixed list (an allow-list).

Fetching results

PHP · editable
Method Returns
fetch() The next row, or false
fetchAll() Every row
fetchColumn() The first column of the next row
fetchAll(PDO::FETCH_KEY_PAIR) [first column => second column]
fetchAll(PDO::FETCH_CLASS, Order::class) Objects of your class

Transactions

When several changes must succeed or fail together (move stock and create an order; debit one account and credit another), wrap them in a transaction:

PHP · editable

The failed transfer had already added 500 to Ravi before the second update failed. rollBack() undid it, so the money didn't appear from nowhere.

A small repository class

Keep SQL in one place, so the rest of the app works with plain PHP objects and methods:

PHP · editable

Frameworks take this further with ORMs (Laravel's Eloquent, Doctrine), which map tables to classes for you. Under the hood they still use PDO and prepared statements.

Practice

  1. Create a books table (title, author, year), insert five books with a prepared statement, and list the books after 2000.
  2. Write findByEmail(PDO $pdo, string $email): ?array that returns null when there's no match.
  3. Try the SQL injection example with your own malicious input, then fix it.
  4. Write a transaction that creates an order and lowers product stock, and rolls back if the stock would go negative.
✎ Check your understanding

1.What prevents SQL injection?

2.What does PDO::ERRMODE_EXCEPTION do?

3.What does $stmt->fetch() return when there are no more rows?

4.When do you need a transaction?

← Forms, requests and sessions