Explain it simply
Explain it simply
A database is the long-term memory of your app. PHP variables disappear the moment a request finishes, but rows stored in a database table are still there for the next visitor, tomorrow, and after a server restart. A table looks like a spreadsheet: each column is a named field (name, email, message) and each row is one record, such as one contact form submission. PHP does not store the data itself; it sends SQL commands to a database server (MySQL or MariaDB on most PHP hosting) and receives rows back.
To talk to the database PHP uses an extension. This course uses PDO, because one set of functions works with MySQL, PostgreSQL and SQLite. The lesson examples run on SQLite so you can practise without installing a server, and every difference you need for MySQL is called out.
Problem → Why → Solution
The problem: everything vanishes when the request ends
Think of the contact form from the forms lessons. A visitor submits a message, PHP validates it, shows 'thank you' and the request ends. Everything PHP held, every variable, array and object, is thrown away at that moment, so the message is gone before anyone reads it. Saving to a text file works for a while, but two visitors writing at once can corrupt it, you cannot search by email without reading everything, and nothing prevents a half-written line.
<?php
// Request 1: a visitor sends a message
$messages = [];
$messages[] = ['name' => 'Aye', 'text' => 'Hello'];
echo count($messages), " message stored\n";
// Request 2 is a brand-new run of the script, so the array starts empty again
$messages = [];
echo count($messages), " messages stored\n";Why a database server solves this
A database server is a separate, long-running program built for exactly this job. It keeps data on disk, lets many requests read and write at the same time safely, finds rows quickly by column value, and enforces rules such as 'email is required'. PHP simply becomes a client of that server.
Core concept: tables, SQL, constraints and PDO
Relational databases such as MySQL, MariaDB, PostgreSQL and SQLite store data in tables. A table has a fixed list of columns, each with a type, and any number of rows. A primary key is a column (usually id) whose value is unique for every row; it is how you point at exactly one record. Most tables let the database generate that id automatically, so PHP never has to invent one.
You talk to the database in SQL, a language separate from PHP. CREATE TABLE defines the structure once, and INSERT, SELECT, UPDATE and DELETE (the next lessons) add, read, change and remove rows. The SQL is just text that PHP sends, which is why it needs care: if you build that text by gluing user input into it, the input can rewrite the command, and that is SQL injection. Lesson 29 shows it happening and the cure, prepared statements.
Constraints are rules the database itself enforces: NOT NULL (a value is required), UNIQUE (no duplicates), PRIMARY KEY, DEFAULT (a fallback value) and foreign keys that link tables. Your PHP validation is the friendly layer that explains problems to the visitor, but constraints are the last line of defence, because bugs, scripts and other applications can reach the table without going through your form. Use both.
PHP offers two common APIs for MySQL. mysqli is specific to MySQL and MariaDB and has both a procedural and an object style. PDO (PHP Data Objects) is a database-neutral layer: you choose the driver with a DSN, a string such as mysql:host=localhost;dbname=app;charset=utf8mb4 or sqlite::memory:, and the rest of your code calls the same methods: prepare, execute, fetch. The runnable examples in this course use PDO with an in-memory SQLite database because it needs no server; for MySQL you change the DSN and a few column definitions, and everything else stays the same.
How a PHP request reaches the data
----------------------------------
Browser --HTTP--> Web server --> PHP script
|
new PDO($dsn) | prepare / execute / fetch
v
PDO driver (pdo_mysql, pdo_sqlite, ...)
|
v
Database server <--> data files on disk
|
rows come back to PHP as arrays- PHP builds a SQL command as text
- PDO sends it to the database server
- The server checks the schema rules
- Rows come back as PHP arrays
PHP never touches the data files; it only talks to the server through a driver.
General pattern
<?php
$pdo = new PDO($dsn, $user, $password, $options);
$pdo->exec('CREATE TABLE table_name (column_name TYPE constraints, ...)');
$stmt = $pdo->prepare('SELECT column_name FROM table_name WHERE column_name = ?');
$stmt->execute([$value]);
$rows = $stmt->fetchAll();new PDO(...) opens the connection, and exec() runs a command that needs no result rows, such as CREATE TABLE. For queries that return rows use prepare() and execute(), put the values where the ? marks are, and collect the rows with fetchAll().
Example: create the contacts table and inspect it
The example opens an in-memory SQLite database through PDO, creates the contacts table and then asks the database to describe it. PRAGMA table_info is SQLite's way of listing columns; MySQL uses DESCRIBE contacts or SHOW COLUMNS FROM contacts for the same job. The in-memory database lives only as long as the script, which makes it ideal for practice.
<?php
$pdo = new PDO('sqlite::memory:');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->exec(<<<'SQL'
CREATE TABLE contacts (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
email TEXT NOT NULL,
message TEXT NOT NULL,
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
)
SQL);
echo "Columns of contacts:\n";
foreach ($pdo->query('PRAGMA table_info(contacts)') as $column) {
$rule = $column['notnull'] ? 'required' : 'optional';
if ($column['pk']) {
$rule = 'primary key';
}
printf(" %-10s %-8s %s\n", $column['name'], $column['type'], $rule);
}
$pdo->exec(
"INSERT INTO contacts (name, email, message)
VALUES ('Aye', 'aye@example.com', 'Hello')"
);
$count = $pdo->query('SELECT COUNT(*) FROM contacts')->fetchColumn();
echo 'Rows stored: ', $count, "\n";Code breakdown
- Line 2
$pdo = new PDO('sqlite::memory:');'sqlite::memory:' is the DSN: the first word, sqlite, selects the driver and the rest is that driver's settings. For MySQL it would be mysql:host=localhost;dbname=thutatech_demo;charset=utf8mb4 plus a username and password.
- Line 3
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);Makes database problems throw a PDOException. This is already the default in PHP 8, but writing it keeps the code explicit and behaves the same on older versions.
- Line 7
id INTEGER PRIMARY KEY AUTOINCREMENT,The primary key column. In SQLite, INTEGER PRIMARY KEY makes the database number the rows itself; in MySQL you would write id INT AUTO_INCREMENT PRIMARY KEY.
- Line 11
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMPIf PHP supplies no value the database fills in the current time itself. NOT NULL plus DEFAULT says 'this column always has a value'.
- Line 16
foreach ($pdo->query('PRAGMA table_info(contacts)') as $column) {query() returns a statement object you can loop over with foreach, one row at a time. Each row is an array keyed by column name.
- Lines 24-27
INSERT INTO contacts (name, email, message)exec() runs a command that returns no rows. The values are written straight into the SQL here only because no user input is involved; real input always goes through a prepared statement, as the next lessons show.
- Line 28
$count = $pdo->query('SELECT COUNT(*) FROM contacts')->fetchColumn();fetchColumn() returns the first column of the first row, which suits one-value queries such as COUNT(*). The last line of output confirms that one row was stored.
Columns of contacts:
id INTEGER primary key
name TEXT required
email TEXT required
message TEXT required
created_at TEXT required
Rows stored: 1PDO or MySQLi?
Both are safe when used with prepared statements; the difference is mostly convenience and portability. This course picks PDO because switching databases then changes the least code and because it gives you named placeholders. If you meet mysqli code in older tutorials, the same query is shown below in both APIs.
| Question | PDO | MySQLi |
|---|---|---|
| Databases supported | MySQL, MariaDB, PostgreSQL, SQLite and more, through drivers | MySQL and MariaDB only |
| Placeholders | Positional ? and named :name | Positional ? only |
| Programming style | Object-oriented | Object-oriented and procedural |
| Switching database later | Mostly a DSN change plus SQL dialect fixes | A rewrite of the database layer |
<?php
// mysqli: works with MySQL and MariaDB only
$mysqli = new mysqli('localhost', 'app_user', 'secret', 'thutatech_demo');
$stmt = $mysqli->prepare('SELECT id, name FROM contacts WHERE email = ?');
$stmt->bind_param('s', $email);
$stmt->execute();
$row = $stmt->get_result()->fetch_assoc();
// PDO: the same job, and the same code for any database the DSN names
$dsn = 'mysql:host=localhost;dbname=thutatech_demo;charset=utf8mb4';
$pdo = new PDO($dsn, 'app_user', 'secret');
$stmt = $pdo->prepare('SELECT id, name FROM contacts WHERE email = ?');
$stmt->execute([$email]);
$row = $stmt->fetch(PDO::FETCH_ASSOC);The contacts table in MySQL and in SQLite
On a MySQL project the table is usually declared like this. This SQL is for MySQL and MariaDB, so pasting it into the SQLite example of this lesson needs adjustments; the table below lists the differences.
-- MySQL / MariaDB version of the contacts table
CREATE TABLE contacts (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
email VARCHAR(150) NOT NULL,
message TEXT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;| Concept | MySQL / MariaDB | SQLite |
|---|---|---|
| Auto-numbered id | id INT AUTO_INCREMENT PRIMARY KEY | id INTEGER PRIMARY KEY AUTOINCREMENT |
| Short text | VARCHAR(100); the length is enforced (strict mode in modern MySQL rejects too-long values) | TEXT; VARCHAR(n) is accepted but the length is not enforced |
| Time default | TIMESTAMP DEFAULT CURRENT_TIMESTAMP | TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP |
| Engine and charset | ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 | Not applicable (text is UTF-8) |
| List the columns | DESCRIBE contacts; | PRAGMA table_info(contacts); |
Check MySQL-specific parts on your own server
The runnable examples in this lesson use SQLite, so MySQL-specific statements and error messages (the CREATE TABLE above, DESCRIBE, MySQL's own error wording) are given as what MySQL documents and what you should expect. Run them against your own MySQL or MariaDB server and trust what it prints.
Constraints are the last line of defence
This code creates the table with NOT NULL and DEFAULT. Watch the database fill in id and status itself, and then refuse a row without an email, whatever the PHP code believes. The wording of the error message differs between databases (the message above is SQLite's), so test the SQLSTATE rather than the message text. Integrity constraint violations are reported with SQLSTATE class 23000, and you should expect to see the same class on MySQL.
<?php
$options = [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION];
$pdo = new PDO('sqlite::memory:', null, null, $options);
$pdo->exec(<<<'SQL'
CREATE TABLE contacts (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
email TEXT NOT NULL,
status TEXT NOT NULL DEFAULT 'new'
)
SQL);
// The database fills in id and status for us
$pdo->exec("INSERT INTO contacts (name, email) VALUES ('Aye', 'aye@example.com')");
$row = $pdo->query('SELECT id, name, status FROM contacts')->fetch(PDO::FETCH_ASSOC);
echo json_encode($row), "\n";
// A row that breaks the schema is refused, whatever the PHP code believes
try {
$pdo->exec("INSERT INTO contacts (name, email) VALUES ('Kyaw', NULL)");
} catch (PDOException $e) {
echo 'Refused: ', $e->getMessage(), "\n";
echo 'SQLSTATE: ', $e->getCode(), "\n";
}
echo 'Rows stored: ', $pdo->query('SELECT COUNT(*) FROM contacts')->fetchColumn(), "\n";In real projects
Where this shows up in real projects
Almost every dynamic PHP site sits on a database: WordPress keeps posts and settings in MySQL tables, Laravel and Symfony ship migration tools that create and change tables from versioned scripts, and shop and booking apps keep orders, products and users there. In real teams the schema is not typed into a console; it lives in migration files committed to git, so every developer and every server builds the same structure. The application connects with a dedicated low-privilege account rather than root, and the credentials come from the environment.
Backups, indexes on the columns you search by (such as email) and a clear naming convention (singular or plural table names, snake_case columns, created_at everywhere) are decisions made at the start, because renaming a column later means coordinating a migration across code, reports and production data.
Common mistakes
Common mistakes
1. Pasting MySQL SQL into SQLite
Running id INT AUTO_INCREMENT PRIMARY KEY in SQLite raises no error, because unknown words are accepted as part of a type name, yet if you insert two rows without an id, both ids come out NULL. In SQLite write INTEGER PRIMARY KEY AUTOINCREMENT. It is dangerous precisely because it fails silently.
2. Treating the column type as validation
SQLite will happily store 24 characters in a VARCHAR(5) column because the type is only a hint, while MySQL checks the length. Always validate length and format in PHP and never rely on the database type alone.
3. Skipping constraints because PHP already validates
Another script, an import tool or code written next year can write to the table without going through your form. Declaring NOT NULL and UNIQUE protects those paths as well.
4. Running CREATE TABLE on every page load
It seems to work on the first run and then fails on the second request with a 'table already exists' error. Run the schema once as a setup script or a migration, and keep it out of ordinary page code.
Best practices
Best practices
- Keep the schema in migration files under version control instead of typing it into a console.
- Start every column as NOT NULL and allow NULL only when 'no value' is genuinely possible.
- Pick one naming convention at the start and follow it, for example snake_case columns and created_at everywhere.
- On MySQL use the utf8mb4 charset so Myanmar text and emoji are stored in full.
Mini challenge
Mini challenge: a products table
Build a products table for a small shop with PDO, then prove what the database fills in by itself and what it refuses.
- A products table: id (auto primary key), name (required), price_cents (required integer), in_stock (required, default 1)
- Ask the database for its column names and print 'products columns: a, b, c, d'
- Insert one product without in_stock, read it back and print name, price and in_stock
- Try an INSERT that leaves out name, catch the PDOException and print 'Rejected: SQLSTATE <code>'; finish with the row count
<?php
$options = [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION];
$pdo = new PDO('sqlite::memory:', null, null, $options);
// TODO: CREATE TABLE products: id (auto primary key), name (required),
// price_cents (required integer), in_stock (required, defaults to 1)
// TODO: ask the database for the column names (PRAGMA table_info) and print
// "products columns: a, b, c, d"
// TODO: insert one product WITHOUT in_stock, read it back, print name, price and in_stock
// TODO: try an INSERT that leaves out the required name; catch PDOException and print
// "Rejected: SQLSTATE <code>"
// TODO: print how many rows the table holdsExpected: products columns: id, name, price_cents, in_stock Stored Notebook at 2500 cents, in_stock=1 Rejected: SQLSTATE 23000 Rows stored: 1
Show hint
The column names are in the name key of every row of PRAGMA table_info(products). Get the SQLSTATE with the PDOException's getCode().
Show solution
<?php
$options = [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION];
$pdo = new PDO('sqlite::memory:', null, null, $options);
$pdo->exec(<<<'SQL'
CREATE TABLE products (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
price_cents INTEGER NOT NULL,
in_stock INTEGER NOT NULL DEFAULT 1
)
SQL);
$names = [];
foreach ($pdo->query('PRAGMA table_info(products)') as $column) {
$names[] = $column['name'];
}
echo 'products columns: ', implode(', ', $names), "\n";
$pdo->exec("INSERT INTO products (name, price_cents) VALUES ('Notebook', 2500)");
$sql = 'SELECT name, price_cents, in_stock FROM products';
$product = $pdo->query($sql)->fetch(PDO::FETCH_ASSOC);
printf(
"Stored %s at %d cents, in_stock=%d\n",
$product['name'],
$product['price_cents'],
$product['in_stock']
);
try {
$pdo->exec('INSERT INTO products (price_cents) VALUES (900)');
} catch (PDOException $e) {
echo 'Rejected: SQLSTATE ', $e->getCode(), "\n";
}
echo 'Rows stored: ', $pdo->query('SELECT COUNT(*) FROM products')->fetchColumn(), "\n";Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- A PHP request forgets everything when it ends, so lasting data lives in a database server organised into tables, rows, columns and primary keys.
- SQL is text that PHP sends, and gluing user input into it invites injection, so prepared statements are required (coming up).
- PDO picks the driver from the DSN and uses the same methods for every database, but you still handle SQL dialect differences yourself.
- Constraints such as NOT NULL, UNIQUE and DEFAULT do not replace PHP validation; they sit behind it as the last line of defence.
PDO Prepared Statements — PHP Documentation Group