Classes and objects, modern PHP 8.3 features, exceptions, and MySQL with PDO.
13
Object-Oriented PHP Basics
10 examples • 5 h
14
Advanced OOP & Modern PHP 8.3
10 examples • 5 h
15
Errors, Exceptions & Debugging
10 examples • 4 h
16
MySQL & PDO
10 examples • 6 h
🐘
<?php
PHP 8.3 • MySQL • XAMPP
BrainBit Infotech, Ranchi | Complete PHP 8.3 Course | Keys: ← → navigate M menu L Code Lab F fullscreen
M13
Object-Oriented PHP Basics
Big projects are organised with classes and objects. A class bundles data and the functions that work on it, like a Student with marks and a percentage() method.
Class vs object
Properties, methods and $this
Constructors and constructor promotion (PHP 8)
public, private and protected
readonly properties, static members and class constants
__toString, objects as handles, and ?->
YOU WILL BUILD: BankAccountShopping cart classLibrary issue/returnSchool result system
🏗️
Part 4 • about 5 hours 10 practice examples: 5 Easy • 3 Medium • 2 Hard
Vocabularyclass = blueprint • object (instance) = a thing made from it with new • property = a variable inside • method = a function inside • -> = "use this object's ..."
● Medium💼 Real project: GST invoices that must never change after issue
Once issued, an invoice must not change. readonly properties enforce it: any later change throws an Error (demonstrated on purpose at the end, inside try/catch).
invoice.php
REAL RUN
✍ Try it yourself Add a readonly $date property set to today in the constructor.
public readonly string $date; then $this->date = date('d-m-Y');
● Medium💼 Real project: School and college library systems
Two classes work together: a Library holds Book objects and members. Methods enforce rules: a book cannot be issued twice, and a member can hold at most 2 books.
library.php
REAL RUN
✍ Try it yourself Add a method available() that lists the titles not issued.
array_filter($this->books, fn($b) => $b->issuedTo === null), then map to titles.
Example 10: Mini school result system with classes
● Hard💼 Real project: Result processing at school level
Three classes: Subject, Student and ResultSheet. The sheet ranks students, finds subject toppers and prints a class report. This is how a real result module is organised.
results.php
REAL RUN
✍ Try it yourself Add a class average for each subject.
In ResultSheet: array_sum(array_map(fn($s) => $s->mark($name), $this->students)) / count($this->students).
Inheritance, interfaces and traits let classes share and swap behaviour. Enums, readonly classes, typed class constants and #[\Override] are the modern PHP 8.1 to 8.3 tools used in today's projects.
Inheritance, overriding and parent::
Abstract classes and interfaces
Polymorphism: one call, many behaviours
Traits for shared code
Enums (8.1), readonly classes (8.2)
Typed class constants and #[\Override] (8.3), namespaces and autoloading
YOU WILL BUILD: Payment methods (UPI, Card, Cash)Notification channelsDiscount rules engineGST tax system
🧬
Part 4 • about 5 hours 10 practice examples: 5 Easy • 3 Medium • 2 Hard
class Clerk extends Employee(nothing new: inherits everything)
public function salary(): float { return parent::salary() + 5000; }
Rule of thumbUse inheritance for a true "is a" relationship (a Teacher is an Employee). For "can do" abilities shared by unrelated classes, use interfaces or traits.
Complete PHP 8.3 Course | Part 4 | Advanced OOP & Modern PHP 8.3
M14Concept
Abstract classes and interfaces
abstract class
interface
Can be created with new?
no
no
Contains
some code + abstract methods
only method signatures (+ constants)
A class can use
one (extends)
many (implements A, B)
Means
"is a kind of"
"can do"
Polymorphism: code that works with the interface type works with every class that implements it.
shapes.php
REAL RUN
Complete PHP 8.3 Course | Part 4 | Advanced OOP & Modern PHP 8.3
M14Concept
Traits: copy-paste done right
A trait is a bundle of methods (and properties) that you can use inside any class.
Solves "I need the same helper in unrelated classes" without inheritance.
A class can use several traits: use Timestamps, SoftDeletes;
Complete PHP 8.3 Course | Part 4 | Advanced OOP & Modern PHP 8.3
M14Animated explainer
Enums: a fixed set of named values (PHP 8.1)
Before: strings everywhere
$order->status = 'shiped'; // typo! if ($status == 'Shipped') ... // never true
enum OrderStatus: string
case Pending = 'pending'; case Paid = 'paid'; case Shipped = 'shipped'; case Delivered = 'delivered';
Pending➤Paid➤Shipped➤Delivered
OrderStatus::from('paid') → OrderStatus::Paid OrderStatus::tryFrom('xyz') → null OrderStatus::cases() → all 4
function ship(Order $o) { $o->status = OrderStatus::Shipped; } // a typo is now a compile error, not a silent bug
Enums can have methods$status->label() returns "Out for delivery", ->color() returns "orange" for the UI.
Complete PHP 8.3 Course | Part 4 | Advanced OOP & Modern PHP 8.3
M14Concept
PHP 8.2 and 8.3 class features
Feature
Version
What it does
readonly class
8.2
every property is readonly: perfect for value objects like Money
Typed class constants const string X
8.3
constants have types; child classes cannot change the type
#[\Override]
8.3
PHP checks that the parent really has this method; catches renamed/misspelled methods
Foo::{$name}
8.3
fetch a class constant by a variable name
The Fatal error in the output is on purpose: #[\Override] caught a misspelled method name.
php83.phpbadtax.php
REAL RUN
Complete PHP 8.3 Course | Part 4 | Advanced OOP & Modern PHP 8.3
M14Concept
Namespaces and autoloading
A namespace is a folder-like name for classes: App\Models\Student. Two libraries can both have a Student class without clashing.
use App\Models\Student; lets you write just Student.
Autoloading: instead of 50 require lines, PHP calls your loader the first time a class is used. Convention (PSR-4): App\Models\Student → src/Models/Student.php.
Composer generates this loader for you (Module 19).
Complete PHP 8.3 Course | Part 4 | Advanced OOP & Modern PHP 8.3
M14Practice 1 of 10 • Easy
Example 1: Animal sounds (inheritance)
● Easy💼 Real project: Learning inheritance with a simple model
Each child class overrides sound(); introduce() is written once in the parent and works for all.
animals.php
REAL RUN
✍ Try it yourself Add an Elephant class (Jharkhand's state animal) that says "Pawoo!".
class Elephant extends Animal { public function sound(): string { return 'Pawoo!'; } }
Complete PHP 8.3 Course | Part 4 | Advanced OOP & Modern PHP 8.3
M14Practice 2 of 10 • Easy
Example 2: Shape area (abstract class)
● Easy💼 Real project: Estimating materials for construction
An abstract class cannot be created with new; it forces every child to implement area(). Trying new Shape() is an error, so we show it inside try/catch.
abstract.php
REAL RUN
✍ Try it yourself Add a TrianglePlot (base, height).
area() returns 0.5 * $this->base * $this->height.
Complete PHP 8.3 Course | Part 4 | Advanced OOP & Modern PHP 8.3
M14Practice 3 of 10 • Easy
Example 3: Payment interface (UPI, Card, Cash)
● Easy💼 Real project: Checkout pages with many payment options
The checkout only knows the PaymentMethod interface. Each payment class implements pay() its own way, including its own fee rule.
payment.php
REAL RUN
✍ Try it yourself Add a NetBanking class with a flat Rs 10 fee.
Complete PHP 8.3 Course | Part 4 | Advanced OOP & Modern PHP 8.3
M14Practice 4 of 10 • Easy
Example 4: Order status enum
● Easy💼 Real project: Order tracking in e-commerce and food delivery
A backed enum with methods. tryFrom converts values coming from the database; label() and next() keep all status logic in one place.
status.php
REAL RUN
✍ Try it yourself Add a Cancelled case and make next() return null for it.
Add case Cancelled = 'cancelled'; in next(): if ($this === self::Cancelled) return null;
Complete PHP 8.3 Course | Part 4 | Advanced OOP & Modern PHP 8.3
M14Practice 5 of 10 • Easy
Example 5: Logger trait
● Easy💼 Real project: Logging inside many unrelated classes
One trait adds logging to any class. The trait uses static::class to know which class is logging.
logger.php
REAL RUN
✍ Try it yourself Add a method clearLog() to the trait.
public function clearLog(): void { $this->log = []; }
Complete PHP 8.3 Course | Part 4 | Advanced OOP & Modern PHP 8.3
M14Practice 6 of 10 • Medium
Example 6: Employee salary hierarchy
● Medium💼 Real project: Payroll software
A base class with common salary parts; child classes add allowances and override gross() using parent::gross(). Polymorphism prints the payroll for everyone in one loop.
payroll.php
REAL RUN
✍ Try it yourself Add a Principal class with a Rs 10,000 head allowance.
class Principal extends Teacher, override gross() to return parent::gross() + 10000.
Complete PHP 8.3 Course | Part 4 | Advanced OOP & Modern PHP 8.3
M14Practice 7 of 10 • Medium
Example 7: Notification channels (SMS, Email, WhatsApp)
● Medium💼 Real project: Fee reminders and OTP delivery
Each channel implements Notifier. A NotificationService sends through every channel the parent chose, without knowing the details of any channel.
notify.php
REAL RUN
✍ Try it yourself Add a PushNotifier for the school app that needs a device token.
canSend checks isset($c['token']); send uses the token.
Complete PHP 8.3 Course | Part 4 | Advanced OOP & Modern PHP 8.3
M14Practice 8 of 10 • Medium
Example 8: Namespaces + autoloader
● Medium💼 Real project: Project structure of real applications
A small project in the standard layout: classes in src/ by namespace, one autoloader, and index.php as the entry point. Notice that no file is required by hand.
✍ Try it yourself Add src/Models/Batch.php (namespace App\Models) and use it in index.php without any require.
The autoloader maps App\Models\Batch to src/Models/Batch.php automatically.
Complete PHP 8.3 Course | Part 4 | Advanced OOP & Modern PHP 8.3
M14Practice 9 of 10 • Hard
Example 9: Plugin-style discount rules
● Hard💼 Real project: Coupon and offer engines in e-commerce
Each rule is a class implementing DiscountRule. The engine applies every rule that matches and picks the best discount. Adding a new offer means adding one class: the engine never changes (the "open/closed" principle).
offers.php
REAL RUN
✍ Try it yourself Add a FestivalOffer rule: 12% off between 1 and 15 November.
Implement DiscountRule; check the date inside discount() and register it in the engine array.
Complete PHP 8.3 Course | Part 4 | Advanced OOP & Modern PHP 8.3
M14Practice 10 of 10 • Hard
Example 10: Typed class constants and #[\Override] in a tax system
● Hard💼 Real project: GST calculation modules in billing software
PHP 8.3 features in a realistic setting: each tax category class has typed constants (const float RATE), #[\Override] marks overridden methods, an enum holds the supply type, and a readonly class holds each invoice line.
gst.php
REAL RUN
✍ Try it yourself Try changing public const float RATE = 0.05; in Essentials to public const string RATE = '5%';. What does PHP 8.3 say?
Fatal error: Type of Essentials::RATE must be compatible with GstCategory::RATE of type float. Typed constants protect the whole family.
Complete PHP 8.3 Course | Part 4 | Advanced OOP & Modern PHP 8.3
M14Check your understanding
Quick Quiz
Click an answer. Wrong answers shake; the right one turns green and explains why.
Q1. A class can extends how many classes?
✔ Use interfaces (many allowed) or traits for more.
Q2. What does #[\Override] (PHP 8.3) check?
✔ A misspelled override becomes a compile-time error.
Q3. OrderStatus::tryFrom('xyz') returns ...
✔ from() would throw a ValueError instead.
🎯
Your score: 0 / 3 (first try counts)
Answer all questions. Discuss any wrong answer with your partner before moving on.
Complete PHP 8.3 Course | Part 4 | Advanced OOP & Modern PHP 8.3
M14Module summary
Recap: Advanced OOP & Modern PHP 8.3
What you learned in M14
✔extends reuses a parent class; override methods and call parent::method().
Complete PHP 8.3 Course | Part 4 | Advanced OOP & Modern PHP 8.3
M15
Errors, Exceptions & Debugging
Things go wrong: missing files, bad input, a database that is down. Professional code expects problems, handles them gracefully and leaves a trail for the developer to fix them.
Error types: parse, fatal, warning, deprecated
display_errors vs log_errors (development vs production)
try, catch, finally
Throwable, Exception, Error and custom exceptions
Global handlers and logging
Debugging with var_dump, stack traces and Xdebug
YOU WILL BUILD: Safe file readerInsufficientBalanceExceptionRetry with exceptionsPayment with rollback
🐛
Part 4 • about 4 hours 10 practice examples: 5 Easy • 3 Medium • 2 Hard
php.ini settingsDevelopment: display_errors=On, error_reporting=E_ALL. Production: display_errors=Off, log_errors=On. The run below is a set of mistakes on purpose.
One handler for the whole site: uncaught exceptions are logged with a reference id and the visitor sees a friendly 500 page. Look at the Files tab for the log line.
index.php
REAL RUN
✍ Try it yourself What happens for ?page=contact? Which class appears in the log?
match has no arm for it, so UnhandledMatchError is thrown and logged.
● Medium💼 Real project: Calling SMS and payment APIs that sometimes fail
Network calls fail now and then. retry() runs a function up to 3 times, waiting longer each time (backoff), and gives up with a clear exception. The flaky SMS gateway below is a simulation that fails twice, then works.
retry.php
REAL RUN
✍ Try it yourself Make retry() also accept a list of exception classes that should NOT be retried (e.g. InvalidArgumentException).
Catch Throwable, check $e instanceof each class, and rethrow immediately if it matches.
● Hard💼 Real project: Validating big forms in one pass
Instead of stopping at the first error, the validator collects all problems into one ValidationFailed exception that carries an array of field errors. Controllers in Laravel work the same way.
validator.php
REAL RUN
✍ Try it yourself Add an email() rule that uses filter_var with FILTER_VALIDATE_EMAIL.
public function email(string $f): static { if (!filter_var(...)) $this->errors[$f][] = 'is invalid'; return $this; }
Example 10: Safe payment process with rollback logic
● Hard💼 Real project: Order and payment workflows
An order has steps: reserve stock, charge the customer, create the invoice. If a later step fails, earlier steps are undone in reverse order (compensation). Module 16 does the same with real database transactions.
order.php
REAL RUN
✍ Try it yourself Add a 4th step "send SMS" that may fail but must NOT roll back the order (the order is still valid).
Put the SMS call after $this->undo = [] in its own try/catch that only logs the failure.
Real applications keep data in a database. You will design tables, write SQL, and use PHP's PDO to read and write MySQL safely, including reports, joins and transactions.
Databases, tables, rows and columns
phpMyAdmin and creating the brainbit database
SQL: CREATE, INSERT, SELECT, UPDATE, DELETE
PDO connection and fetch modes
Prepared statements and SQL injection
JOIN, GROUP BY reports and transactions
YOU WILL BUILD: Student recordsFee reportFee payment transactionSQL injection demo and fix
🗃️
Part 4 • about 6 hours 10 practice examples: 5 Easy • 3 Medium • 2 Hard
This is the real data used in this module's examples (MariaDB 10.11, as in XAMPP).
🏫
Everything is stored here
Students, fees, attendance, products, orders, users: tables in MySQL/MariaDB.
⚡
Fast search and reports
SQL finds one student among lakhs in milliseconds and builds monthly reports in one query.
🔐
Safe and shared
Many users can read and write at the same time; transactions keep money records correct.
Complete PHP 8.3 Course | Part 4 | MySQL & PDO
M16Animated explainer
Database, table, row, column
🗃 brainbitdatabase 📋 courses 📋 students 📋 payments
id
name
city
mobile
course_id
1
Riya Kumari
Ranchi
9835011111
1
2
Aman Toppo
Gumla
7004022222
1
Column
one kind of data with a type: INT, VARCHAR(80), DATE, DECIMAL
Row
one record: one student
Primary key
id is unique for every row; AUTO_INCREMENT fills it
Foreign keystudents.course_id stores the id of a course instead of repeating its name and fee. Tables are linked, not copied.
Complete PHP 8.3 Course | Part 4 | MySQL & PDO
M16Setup
Set up the database in XAMPP (5 minutes)
1
Start Apache and MySQL in the XAMPP Control Panel.
2
Open http://localhost/phpmyadmin. Click New, name the database brainbit, collation utf8mb4_unicode_ci, click Create.
3
Open the SQL tab, paste the script on the right, click Go. You now have the same 3 tables used in the slides.
4
In PHP connect with user root and an empty password (XAMPP default). On real hosting you get a separate user and a strong password.
5
Every example in this module resets these tables first, so your results match the slides.
ProductionNever use root without a password on a live server. Create a user with only the rights the app needs.
CREATE TABLE courses (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(60) NOT NULL,
fee INT NOT NULL);
CREATE TABLE students (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(80) NOT NULL,
city VARCHAR(40), mobile CHAR(10),
course_id INT, joined DATE,
FOREIGN KEY (course_id) REFERENCES courses(id));
CREATE TABLE payments (
id INT AUTO_INCREMENT PRIMARY KEY,
student_id INT NOT NULL, amount INT NOT NULL,
mode VARCHAR(10), paid_on DATE,
FOREIGN KEY (student_id) REFERENCES students(id));
INSERT INTO courses (name, fee) VALUES
('PHP & MySQL', 12000), ('Python Basics', 8000),
('Tally with GST', 6500);
-- then the students and payments rows:
-- copy the full script from the setup.sql tab
-- on the slide "Connecting with PDO"
Complete PHP 8.3 Course | Part 4 | MySQL & PDO
M16Concept
SQL in one slide
Task
SQL
Add
INSERT INTO students (name, city) VALUES ('Asha', 'Gaya')
Read
SELECT name, city FROM students WHERE city = 'Ranchi' ORDER BY name LIMIT 10
Change
UPDATE students SET city = 'Hazaribagh' WHERE id = 3
Remove
DELETE FROM students WHERE id = 5
Count/sum
SELECT city, COUNT(*) FROM students GROUP BY city
Always use WHERE with UPDATE and DELETEWithout it, every row in the table is changed or deleted.
query.sql
Complete PHP 8.3 Course | Part 4 | MySQL & PDO
M16Concept
Connecting with PDO
PDO (PHP Data Objects) works with MySQL, PostgreSQL, SQLite... the same code style everywhere.
query() for fixed SQL; fetchAll() all rows, fetch() one row, fetchColumn() one value.
mysqliPHP also has mysqli (MySQL only). Both are fine; this course uses PDO.
connect.phpsetup.sql
REAL RUN
Complete PHP 8.3 Course | Part 4 | MySQL & PDO
M16Animated explainer
SQL injection: the most famous attack
$sql = "SELECT * FROM users WHERE mobile = '" . $_POST['mobile'] . "'";
Normal user types
9835011111 → ... WHERE mobile = '9835011111'
Attacker types
' OR '1'='1 → ... WHERE mobile = '' OR '1'='1'
'1'='1' is always true: every user is returned. Logins bypassed, data leaked.
✅ Prepared statement
$st = $pdo->prepare('SELECT * FROM users WHERE mobile = ?'); $st->execute([$_POST['mobile']]);
SQL template sent first
+
data sent separately
=
data can never become SQL
RuleEvery value from a user goes through a placeholder (? or :name). No exceptions. Example 10 runs the attack and the fix for real.
Complete PHP 8.3 Course | Part 4 | MySQL & PDO
M16Concept
Prepared statements: ? and :name
$st = $pdo->prepare('... WHERE city = ? AND course_id = ?'); $st->execute([$city, $cid]);
Named: ':city' with execute(['city' => $city]), clearer for many values.
After INSERT: $pdo->lastInsertId(). After UPDATE/DELETE: $st->rowCount().
Prepare once, execute many times (fast bulk inserts).
Placeholders are for values only, not table or column names.
prepared.php
REAL RUN
Complete PHP 8.3 Course | Part 4 | MySQL & PDO
M16Animated explainer
Transactions: all or nothing
Fee payment = 3 changes
1. INSERT payment row (Rs 6,000)
2. UPDATE student: fee_due - 6,000
3. INSERT receipt → fails! (power cut, error)
Without a transaction: payment saved, due reduced, but no receipt. The data is now inconsistent.
$pdo->beginTransaction(); try { ... step 1, 2, 3 ... $pdo->commit(); // save all } catch (Throwable $e) { $pdo->rollBack(); // undo all }
Step 3 failed → rollBack() → steps 1 and 2 are undone. The database looks as if nothing happened.
Use forpayments, stock movements, transfers, anything where several tables must change together.
Complete PHP 8.3 Course | Part 4 | MySQL & PDO
M16Practice 1 of 10 • Easy
Example 1: Connect to MySQL
● Easy💼 Real project: The db.php file of every project
A reusable db.php returns one PDO connection. If MySQL is stopped or the password is wrong, a clear message appears instead of a scary stack trace.
db.phptest.php
REAL RUN
✍ Try it yourself Change the password to "abc" and run again. What message do you see?
Database connection failed ... (1045): access denied. The code 1045 means wrong user/password.
Complete PHP 8.3 Course | Part 4 | MySQL & PDO
M16Practice 2 of 10 • Easy
Example 2: Create a table and insert
● Easy💼 Real project: Setting up a new module (attendance, library...)
exec() runs SQL that returns no rows (CREATE). A prepared INSERT in a loop adds several rows. See the Database tab.
setup.php
REAL RUN
✍ Try it yourself Add a column posted_by VARCHAR(50) and fill it.
ALTER TABLE notices ADD posted_by VARCHAR(50); or add it to CREATE and the INSERT.
Complete PHP 8.3 Course | Part 4 | MySQL & PDO
M16Practice 3 of 10 • Easy
Example 3: Select and show students
● Easy💼 Real project: Student list pages
Read rows with a query and print them as an HTML table: the most common page in any admin panel.
list.php
REAL RUN
✍ Try it yourself Show only students who joined in October 2026.
WHERE joined BETWEEN '2026-10-01' AND '2026-10-31' (or MONTH(joined) = 10).
Complete PHP 8.3 Course | Part 4 | MySQL & PDO
M16Practice 4 of 10 • Easy
Example 4: Update a record
● Easy💼 Real project: Edit forms in admin panels
A prepared UPDATE changes one student's city and mobile. rowCount() tells whether a row was really changed.
update.php
REAL RUN
✍ Try it yourself Update the fee of "Python Basics" to 8500 in the courses table.
UPDATE courses SET fee = ? WHERE name = ? with [8500, 'Python Basics'].
Complete PHP 8.3 Course | Part 4 | MySQL & PDO
M16Practice 5 of 10 • Easy
Example 5: Delete a record
● Easy💼 Real project: Removing wrong or test entries
DELETE with a WHERE on the id. The foreign key protects data: a course that still has students cannot be deleted (the error is caught on purpose).
delete.php
REAL RUN
✍ Try it yourself Many apps never really delete: they set deleted_at = NOW(). Add that column and "soft delete" student 5.
ALTER TABLE students ADD deleted_at DATETIME NULL; then UPDATE ... SET deleted_at = NOW() WHERE id = 5, and filter WHERE deleted_at IS NULL.
Complete PHP 8.3 Course | Part 4 | MySQL & PDO
M16Practice 6 of 10 • Medium
Example 6: Safe search with a prepared statement
● Medium💼 Real project: Search boxes on admin panels
The search text comes from a GET form. LIKE with % wildcards finds partial names; the value still goes through a placeholder.
search.php
REAL RUN
✍ Try it yourself Try searching for ' OR '1'='1. What happens and why?
No results: the whole text is treated as a value to search for, not as SQL.
Complete PHP 8.3 Course | Part 4 | MySQL & PDO
M16Practice 7 of 10 • Medium
Example 7: JOIN students and courses
● Medium💼 Real project: Reports that combine tables
JOIN connects each student to their course through course_id. LEFT JOIN keeps courses that have no students.
join.php
REAL RUN
✍ Try it yourself List students with their course for one city only, using a prepared statement.
Add WHERE s.city = ? to the first query and use prepare/execute.
Complete PHP 8.3 Course | Part 4 | MySQL & PDO
M16Practice 8 of 10 • Medium
Example 8: Fee report with GROUP BY
● Medium💼 Real project: Monthly fee collection reports
Aggregate functions (SUM, COUNT, AVG) with GROUP BY turn hundreds of payments into a short report: per payment mode and per month, plus each student's balance due.
report.php
REAL RUN
✍ Try it yourself Add a total row for the "By month" section using SQL WITH ROLLUP or PHP array_sum.
GROUP BY ... WITH ROLLUP adds a row with NULL month and the grand total.
Complete PHP 8.3 Course | Part 4 | MySQL & PDO
M16Practice 9 of 10 • Hard
Example 9: Fee payment transaction (commit/rollback)
● Hard💼 Real project: Payment recording in ERPs
A payment inserts a row, updates the student's due and writes a receipt, all in one transaction. The second payment fails at the receipt step (a duplicate receipt number, on purpose), so everything is rolled back. Check the Database tab.
pay.php
REAL RUN
✍ Try it yourself Remove beginTransaction/commit/rollBack and run again. What is wrong with the data now?
Student 2 gets a payment row and a reduced due but no receipt: inconsistent data.
Complete PHP 8.3 Course | Part 4 | MySQL & PDO
M16Practice 10 of 10 • Hard
Example 10: SQL injection attack and the fix
● Hard💼 Real project: Security testing of login forms
login_unsafe.php glues input into SQL (vulnerable on purpose): the attacker logs in without a password. login_safe.php uses a prepared statement and password_verify: the attack fails. Never ship code like the unsafe file.
login_unsafe.phplogin_safe.php
REAL RUN
✍ Try it yourself Why does the safe version also use password_verify instead of comparing plain passwords in SQL?
Passwords must be stored as hashes (Module 18). Even if the database leaks, the real passwords are not exposed.
Complete PHP 8.3 Course | Part 4 | MySQL & PDO
M16Check your understanding
Quick Quiz
Click an answer. Wrong answers shake; the right one turns green and explains why.
Q1. Which method protects against SQL injection?
✔ Data and SQL travel separately.
Q2. What does rollBack() do?
✔ commit() saves them; rollBack() cancels them.
Q3. Which JOIN keeps courses that have no students?
✔ LEFT JOIN keeps every row of the left table.
🎯
Your score: 0 / 3 (first try counts)
Answer all questions. Discuss any wrong answer with your partner before moving on.
Complete PHP 8.3 Course | Part 4 | MySQL & PDO
M16Module summary
Recap: MySQL & PDO
What you learned in M16
✔A database holds tables; rows are records; columns have types; id is the primary key.
✔SQL: INSERT, SELECT ... WHERE ... ORDER BY ... LIMIT, UPDATE and DELETE (always with WHERE).
✔PDO with ERRMODE_EXCEPTION and FETCH_ASSOC; fetchAll, fetch, fetchColumn.
✔Prepared statements for every user value; lastInsertId and rowCount.
✔JOIN links tables; GROUP BY + SUM/COUNT builds reports.
✔Transactions: beginTransaction, commit, rollBack keep data consistent.
🏆
Module 16 complete!
You practised 10 real examples.
👉 Coming next
Part 5, M17 Building a CRUD Web App: put it all together in a complete Student Management System.
Complete PHP 8.3 Course | Part 4 | MySQL & PDO
1 / 1
All slides: Part 4 - OOP, Errors & Databases (press M or Esc to close)