Web Development courseLesson 8 of 20 · tap to see all lessons
Web Development · Beginner
PHP and Database Integration: Connecting with PDO, Prepared Statements, and Saving Form Data
Connect PHP to a MySQL database with PDO, save and list form data, update and delete records, and stop SQL injection with prepared statements.
- Qyubie Learn Editorial Team
- Published
- 13 min read
Includes 1 quick check you can do right here.
Your registration form from lesson 5 validated the data, then forgot it as soon as the page finished. To keep data, an application stores it in a database. In this lesson PHP connects to MySQL, saves form submissions, lists them, and changes them, using prepared statements, the one technique that stops the most common attack on web databases.
By the end of this lesson you will be able to:
- describe the flow of server-side form processing from browser to database,
- explain relational tables, rows, columns, and keys,
- connect PHP to MySQL with PDO,
- insert, select, update, and delete rows from PHP, and
- explain SQL injection and prevent it with prepared statements.
Server-side form processing, end to end
Here's the full path of a registration form once a database is involved:
Browser Web server (PHP) Database (MySQL)
│ POST /register.php ───────▶ │
│ student_no, name, ... │ 1. read $_POST
│ │ 2. validate (lesson 5)
│ │ 3. INSERT with a prepared statement ──▶ │ stores the row
│ │ ◀─────────────────────────── OK, id 3 ─ │
│ ◀── 302 redirect ────────── │ 4. redirect (Post/Redirect/Get)
│ GET /students.php ────────▶ │ 5. SELECT ─────────────────────────────▶ │
│ │ ◀──────────────────────────────── rows ─ │
│ ◀── HTML table ──────────── │ 6. print rows with htmlspecialcharsThe browser never talks to the database. Only the server does, using a database password the user never sees.
Database concepts in brief
A relational database stores data in tables. Each column has a name and a type; each row is one record. A primary key column (usually id) gives every row a unique identifier, and a foreign key column refers to the primary key of another table to link them (for example, an enrollments.student_id pointing to students.id). Lesson 9 covers SQL and relationships in more depth.
The table used in this lesson:
CREATE DATABASE school_db;
USE school_db;
CREATE TABLE students (
id INT AUTO_INCREMENT PRIMARY KEY,
student_no VARCHAR(10) NOT NULL UNIQUE,
full_name VARCHAR(100) NOT NULL,
course VARCHAR(10) NOT NULL,
email VARCHAR(100)
);
INSERT INTO students (student_no, full_name, course, email) VALUES
('2024-0001', 'Ana Reyes', 'BSCS', 'ana@example.com'),
('2024-0002', 'Ben Cruz', 'BSIT', 'ben@example.com');With XAMPP, start MySQL in the Control Panel, open phpMyAdmin at http://localhost/phpmyadmin, click the SQL tab, and run the script above.
Connecting with PDO
PHP talks to databases through PDO (PHP Data Objects). The same PDO code works with MySQL, PostgreSQL, SQLite, and others; only the connection string changes. Put the connection in its own file and require it wherever you need the database:
<?php
// db.php: the one place that knows how to connect
$host = "127.0.0.1";
$dbname = "school_db";
$user = "root"; // XAMPP's default user...
$pass = ""; // ...has no password. Never do this on a real server.
$dsn = "mysql:host=$host;dbname=$dbname;charset=utf8mb4";
try {
$pdo = new PDO($dsn, $user, $pass, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, // throw on SQL errors
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, // rows as ["column" => value]
]);
} catch (PDOException $e) {
error_log($e->getMessage()); // details go to the server log, not the page
http_response_code(500);
exit("Sorry, the database is not available right now.");
}- The DSN (data source name) says which driver, host, and database to use.
charset=utf8mb4stores every character correctly, including ñ and emoji. ERRMODE_EXCEPTIONmakes PDO throw aPDOExceptionwhen a query fails, instead of failing silently.FETCH_ASSOCreturns each row as an associative array, like the arrays in lesson 4.- Never show
$e->getMessage()to visitors. It can reveal table names and server details. Log it, and show a plain message. - On a real server, keep the password out of your code and out of Git: read it from an environment variable or a config file listed in
.gitignore(lesson 17).
For PostgreSQL (lesson 9), the only change is the DSN: pgsql:host=...;port=5432;dbname=....
Reading rows: SELECT
<?php
require "db.php";
$stmt = $pdo->query("SELECT id, student_no, full_name, course FROM students ORDER BY full_name");
$students = $stmt->fetchAll();
echo count($students) . " students\n";
foreach ($students as $s) {
echo "{$s['student_no']} {$s['full_name']} ({$s['course']})\n";
}Output:
2 students
2024-0001 Ana Reyes (BSCS)
2024-0002 Ben Cruz (BSIT)$pdo->query() runs SQL that contains no user input. fetchAll() returns every row as an array of associative arrays; fetch() returns just the next row (or false when there are no more). On a real page you'd print them into an HTML table with htmlspecialchars, exactly as in lesson 4.
SQL injection: why you never build SQL from input
Suppose a search page builds its query by gluing user input into the SQL string:
<?php
$no = $_GET["no"] ?? "x' OR '1'='1"; // what an attacker typed
$sql = "SELECT * FROM students WHERE student_no = '$no'";
echo $sql, "\n";Output:
SELECT * FROM students WHERE student_no = 'x' OR '1'='1'The attacker's quote closed the string early, and the rest of their input became part of the SQL. OR '1'='1' is always true, so this returns every student. With other input, an attacker can read password tables, change grades, or delete data. This is SQL injection, one of the most damaging and most common web vulnerabilities.
Prepared statements
A prepared statement sends the SQL and the values separately. The SQL has placeholders; the values are attached afterwards and are always treated as data, never as SQL, whatever characters they contain.
<?php
require "db.php";
function findStudent(PDO $pdo, string $studentNo): ?array {
$stmt = $pdo->prepare("SELECT full_name, course FROM students WHERE student_no = :no");
$stmt->execute(["no" => $studentNo]);
$row = $stmt->fetch();
return $row ?: null;
}
$found = findStudent($pdo, "2024-0002");
echo $found ? "{$found['full_name']}, {$found['course']}\n" : "Not found\n";
$attack = findStudent($pdo, "x' OR '1'='1");
echo $attack ? "Leaked!\n" : "Attack found nothing\n";Output:
Ben Cruz, BSIT
Attack found nothingThe steps are always the same:
prepare()the SQL with placeholders: named (:no) or positional (?).execute()with the values:["no" => $value]for named, or[$value]for?.- Fetch the results, if it's a
SELECT.
The rule: every value that comes from outside your code goes through a placeholder. That includes $_GET, $_POST, cookies, and data from APIs. Placeholders are for values only; table and column names can't be placeholders, so if a user chooses a sort column, check it against an allow-list.
Quick check
Saving form data: INSERT
Here is lesson 5's registration handler, now saving to the database. It validates, inserts with a prepared statement, and handles a duplicate student number:
<?php
require "db.php";
$errors = [];
if ($_SERVER["REQUEST_METHOD"] === "POST") {
$no = trim($_POST["student_no"] ?? "");
$name = trim($_POST["full_name"] ?? "");
$course = $_POST["course"] ?? "";
$email = trim($_POST["email"] ?? "");
if (!preg_match('/^\d{4}-\d{4}$/', $no)) $errors[] = "Student number must look like 2025-0001.";
if ($name === "") $errors[] = "Name is required.";
if (!in_array($course, ["BSCS", "BSIT"], true)) $errors[] = "Choose a valid course.";
if ($email !== "" && !filter_var($email, FILTER_VALIDATE_EMAIL)) $errors[] = "Email is not valid.";
if (!$errors) {
try {
$stmt = $pdo->prepare(
"INSERT INTO students (student_no, full_name, course, email)
VALUES (:no, :name, :course, :email)"
);
$stmt->execute([
"no" => $no,
"name" => $name,
"course" => $course,
"email" => $email === "" ? null : $email,
]);
echo "Saved with id " . $pdo->lastInsertId() . "\n";
// On a real page: header("Location: students.php"); exit;
} catch (PDOException $e) {
if ($e->getCode() === "23000") { // integrity rule broken: here, UNIQUE
$errors[] = "That student number is already registered.";
} else {
throw $e;
}
}
}
}
foreach ($errors as $e) echo "Error: $e\n";Output:
Saved with id 3lastInsertId()gives theAUTO_INCREMENTid of the new row.- Empty optional fields are stored as
NULL, not as an empty string. - SQLSTATE
23000means a constraint was broken: a duplicateUNIQUEvalue or a bad foreign key. Turn it into a friendly message; let any other error go to the log. - The
UNIQUErule in the table is the real guarantee against duplicates. Checking with aSELECTfirst isn't enough, because two people could submit at the same moment.
Updating and deleting
UPDATE and DELETE follow the same pattern. Always identify the row by its id, and check how many rows were affected:
<?php
require "db.php";
$stmt = $pdo->prepare("UPDATE students SET course = :course WHERE id = :id");
$stmt->execute(["course" => "BSCS", "id" => 2]);
echo "Updated: " . $stmt->rowCount() . "\n";
$stmt = $pdo->prepare("DELETE FROM students WHERE id = ?");
$stmt->execute([99]);
echo "Deleted: " . $stmt->rowCount() . "\n"; // no row 99
$stmt = $pdo->prepare("DELETE FROM students WHERE id = ?");
$stmt->execute([1]);
echo "Deleted: " . $stmt->rowCount() . "\n";
$left = $pdo->query("SELECT full_name, course FROM students")->fetchAll();
foreach ($left as $s) echo "{$s['full_name']} ({$s['course']})\n";Output:
Updated: 1
Deleted: 0
Deleted: 1
Ben Cruz (BSCS)rowCount() tells you how many rows changed. Zero means nothing matched, which usually deserves a "not found" message.
On a web page, edits and deletes are sent with POST, never with a plain link (<a href="delete.php?id=1">). Links can be followed by search engines, browser prefetching, or a malicious page, and a GET request should never change data. A delete button is a tiny form:
<form method="post" action="delete.php" onsubmit="return confirm('Delete this student?')">
<input type="hidden" name="id" value="<?= (int) $s['id'] ?>">
<button>Delete</button>
</form>A simple CRUD page structure
A small PHP application usually looks like this:
cs324-sis/
├── db.php connection (password from config, not committed)
├── students.php READ: table of students, with Edit and Delete buttons
├── register.php CREATE: form + INSERT
├── edit.php UPDATE: form filled from SELECT ... WHERE id = ?, then UPDATE
├── delete.php DELETE: POST only, then redirect back
└── partials/
├── header.php
└── footer.phpEach page validates its input, uses prepared statements, escapes its output with htmlspecialchars, and redirects after a successful POST. That combination covers the core of almost every database-driven website.
Common mistakes
- Building SQL with string concatenation and user input.
- Showing database error messages to visitors.
- Committing
db.phpwith a real password. - Deleting or updating with GET links.
- Forgetting
ERRMODE_EXCEPTION, so failed queries go unnoticed. localhostvs127.0.0.1: on some setupslocalhostuses a socket or IPv6 and fails to connect;127.0.0.1is the reliable choice.- Forgetting
charset=utf8mb4, so names with ñ turn into?.
Summary
- The browser sends the form to PHP; PHP validates it and talks to the database; the user never touches the database directly.
- PDO connects PHP to MySQL (or PostgreSQL) with a DSN; set
ERRMODE_EXCEPTIONandFETCH_ASSOC, and keep credentials out of Git. - SQL injection happens when input is glued into SQL. Prepared statements with placeholders prevent it:
prepare,execute,fetch. fetchAll,lastInsertId, androwCountreport the results; constraint errors (SQLSTATE 23000) become friendly messages.- Changes go through POST forms, and every page escapes its output.
Next lesson: SQL and Supabase/PostgreSQL: writing SQL queries, and setting up a cloud PostgreSQL database.