PART 4 of 5  •  about 20 class hours

OOP, Errors & Databases

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
Complete PHP 8.3 Course  |  BrainBit Infotech, Ranchi
M13Where is this used in real work?

Modern PHP is object-oriented

VS Code - app/Models
📁 app/Models
  Student.php  class Student { name, roll, marks... }
  Invoice.php  class Invoice { items, total(), gst() }
  BankAccount.php
📁 app/Services
  SmsService.php  send($mobile, $text)
$s = new Student('Riya', 21);
echo $s->percentage();
🧱

Laravel, WordPress, Symfony

Every modern PHP framework is built from classes. You must know OOP to use them.
📦

Data + behaviour together

An Invoice object holds its items and knows how to calculate its own total and GST.
🔐

Protection

Private properties stop other code from setting balance = -5000 directly. Changes go through checked methods.
Complete PHP 8.3 Course  |  Part 4  |  Object-Oriented PHP Basics
M13Animated explainer

Class vs object: the cookie cutter

📐
class Studentthe design (blueprint)
name, roll, marks
percentage()
🧑
$riyaname: Riya
roll: 21
marks: [88, 92]
🧑
$amanname: Aman
roll: 7
marks: [64, 71]
🧑
$zoyaname: Zoya
roll: 30
marks: [95, 99]
echo $riya->percentage(); // 90
echo $aman->percentage(); // 67.5
Vocabularyclass = blueprint • object (instance) = a thing made from it with new • property = a variable inside • method = a function inside • -> = "use this object's ..."
Complete PHP 8.3 Course  |  Part 4  |  Object-Oriented PHP Basics
M13Concept

Your first class

  • class Student { ... } names start with a Capital.
  • Properties hold data; give them types: public string $name;
  • Methods are functions inside the class.
  • Inside a method, $this means "the current object".
  • Create with new; use with ->
One class per fileIn real projects Student lives in Student.php. Examples here keep everything in one file for easy reading.
student.php
REAL RUN
Complete PHP 8.3 Course  |  Part 4  |  Object-Oriented PHP Basics
M13Concept

Constructors and constructor promotion

  • __construct() runs automatically when you call new. It sets up the object.
  • Constructor promotion (PHP 8): write visibility in the parameter list and PHP creates and fills the property for you.
  • Default values and named arguments work as in functions.

Old way (PHP 7)

private string $name;
public function __construct(string $name)
{ $this->name = $name; }

PHP 8 way

public function __construct(
  private string $name
) {}
product.php
REAL RUN
Complete PHP 8.3 Course  |  Part 4  |  Object-Oriented PHP Basics
M13Animated explainer

Visibility: who can touch what?

class BankAccount
public string $holder anyone can read/write
private float $balance only methods of this class
protected $branch this class + child classes
public function withdraw($amt) checks the rules
$acc->holder = 'Ravi'; // OK
$acc->balance = 1000000;
// Error: Cannot modify private property
$acc->withdraw(500); // OK, goes through the checks
EncapsulationHide the data, expose safe methods. The class guarantees the balance never becomes negative.
Complete PHP 8.3 Course  |  Part 4  |  Object-Oriented PHP Basics
M13Concept

readonly, static and class constants

  • public readonly string $invoiceNo; can be set once (in the constructor) and never changed (PHP 8.1).
  • static properties/methods belong to the class, not an object: Invoice::$count, Invoice::nextNumber().
  • Class constants: const GST = 18; used as self::GST or Invoice::GST.
  • __toString() decides what echo $obj prints.

The Error at the end is on purpose: readonly properties cannot be changed.

invoice.php
REAL RUN
Complete PHP 8.3 Course  |  Part 4  |  Object-Oriented PHP Basics
M13Concept

Objects are handles; nullsafe ?->

  • $b = $a; does not copy an object: both variables point to the same object. Change one, both see it.
  • $b = clone $a; makes a real copy.
  • Arrays are the opposite: assigning an array copies it.
  • Nullsafe $user?->address?->city returns null instead of crashing when something in the chain is null (PHP 8).
handles.php
REAL RUN
Complete PHP 8.3 Course  |  Part 4  |  Object-Oriented PHP Basics
M13Practice 1 of 10  •  Easy

Example 1: Student class

● Easy💼 Real project: Student records in an ERP
A class with constructor promotion, a method for the percentage and one for the result. Each object keeps its own data.
student.php
REAL RUN
✍ Try it yourself Add a method grade() using match(true) on the percentage.
public function grade(): string { return match (true) { $this->percentage() >= 90 => 'A+', ... }; }
Complete PHP 8.3 Course  |  Part 4  |  Object-Oriented PHP Basics
M13Practice 2 of 10  •  Easy

Example 2: BankAccount deposit and withdraw

● Easy💼 Real project: Wallets and banking software
The balance is private; only deposit and withdraw can change it, and they check the rules. Methods return messages so the screen can show them.
bank.php
REAL RUN
✍ Try it yourself Add a minimum balance rule of Rs 500 for withdrawals.
Fail if $this->balance - $amt < 500.
Complete PHP 8.3 Course  |  Part 4  |  Object-Oriented PHP Basics
M13Practice 3 of 10  •  Easy

Example 3: Product with constructor promotion

● Easy💼 Real project: Product catalogues
Constructor promotion keeps the class short. A method calculates the selling price after discount; number_format prints it.
product.php
REAL RUN
✍ Try it yourself Add a property $gstRate = 18 and a method priceWithGst().
Add public int $gstRate = 18 to the constructor and return $this->price() * (1 + $this->gstRate / 100).
Complete PHP 8.3 Course  |  Part 4  |  Object-Oriented PHP Basics
M13Practice 4 of 10  •  Easy

Example 4: Counter with static

● Easy💼 Real project: Counting objects, generating ids
A static property is shared by all objects of the class. Every new ticket gets the next number automatically.
ticket.php
REAL RUN
✍ Try it yourself Add a static method that returns the next number without creating a ticket.
public static function peek(): int { return self::$next; }
Complete PHP 8.3 Course  |  Part 4  |  Object-Oriented PHP Basics
M13Practice 5 of 10  •  Easy

Example 5: Rectangle with __toString

● Easy💼 Real project: Readable objects in logs and debugging
__toString lets you echo an object directly. Methods return new values; the object stays simple.
room.php
REAL RUN
✍ Try it yourself Add a method tiles() that returns how many 2x2 ft tiles the floor needs.
return (int) ceil($this->area() / 4);
Complete PHP 8.3 Course  |  Part 4  |  Object-Oriented PHP Basics
M13Practice 6 of 10  •  Medium

Example 6: Shopping cart class

● Medium💼 Real project: E-commerce checkout
The Cart object owns its items. add() returns $this so calls can be chained; total and delivery rules live inside the class.
cart.php
REAL RUN
✍ Try it yourself Add a coupon method applyCoupon(string $code) for 10% off with code SAVE10.
Store a $discount property; total() subtracts subtotal * discount.
Complete PHP 8.3 Course  |  Part 4  |  Object-Oriented PHP Basics
M13Practice 7 of 10  •  Medium

Example 7: Readonly invoice

● 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');
Complete PHP 8.3 Course  |  Part 4  |  Object-Oriented PHP Basics
M13Practice 8 of 10  •  Medium

Example 8: Library book issue and return

● 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.
Complete PHP 8.3 Course  |  Part 4  |  Object-Oriented PHP Basics
M13Practice 9 of 10  •  Hard

Example 9: Bank account with transaction history

● Hard💼 Real project: Passbooks and mini statements
Each deposit or withdrawal is recorded as a Transaction object (readonly). The statement method prints a passbook with a running balance.
passbook.php
REAL RUN
✍ Try it yourself Add a method miniStatement(int $n = 3) that prints only the last n transactions.
Use array_slice($this->tx, -$n) and compute the starting balance first.
Complete PHP 8.3 Course  |  Part 4  |  Object-Oriented PHP Basics
M13Practice 10 of 10  •  Hard

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).
Complete PHP 8.3 Course  |  Part 4  |  Object-Oriented PHP Basics
M13Check your understanding

Quick Quiz

Click an answer. Wrong answers shake; the right one turns green and explains why.

Q1. What does $this mean inside a method?
✔ $this->name is this particular object's name.
Q2. What does constructor promotion do?
✔ public function __construct(private string $name) {} is enough.
Q3. After $b = $a; with an object, changing $b ...
✔ Use clone to make a copy.
🎯
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  |  Object-Oriented PHP Basics
M13Module summary

Recap: Object-Oriented PHP Basics

What you learned in M13

  • ✔A class is a blueprint; new creates objects; -> uses them.
  • ✔Properties hold data, methods hold behaviour, $this is the current object.
  • ✔Constructor promotion (PHP 8) declares and fills properties in one line.
  • ✔public / private / protected protect data: encapsulation.
  • ✔readonly (8.1), static members, class constants (self::GST), __toString.
  • ✔Objects are passed as handles: use clone to copy; ?-> for nullable chains.
🏆

Module 13 complete!

You practised 10 real examples.

👉 Coming next

M14 Advanced OOP & Modern PHP 8.3: inheritance, interfaces, traits, enums, readonly classes, typed constants and #[\Override].
Complete PHP 8.3 Course  |  Part 4  |  Object-Oriented PHP Basics
M14

Advanced OOP & Modern PHP 8.3

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
Complete PHP 8.3 Course  |  BrainBit Infotech, Ranchi
M14Where is this used in real work?

Swappable parts: the power of interfaces

shop.example.in/checkout.php
Choose payment methodPHP
📱 UPI💳 Card💵 Cash on delivery🏦 Net banking
interface PaymentMethod { function pay(float $amt): string; }
$method->pay(749.50);   // works for ANY method
🔌

Plug-in design

Checkout code calls pay() without knowing which method it is. Adding Net banking needs a new class, not changes everywhere.
🏷️

Enums for fixed choices

Order status (Pending, Paid, Shipped), roles and payment modes become enums: no more typo bugs like "Shiped".
🧱

Framework code

Laravel models extend Model, controllers extend Controller, and services implement interfaces: exactly these ideas.
Complete PHP 8.3 Course  |  Part 4  |  Advanced OOP & Modern PHP 8.3
M14Animated explainer

Inheritance: a family of classes

class Employeename, basicPay • salary() • describe()
↑
class Teacher extends Employee+ subject • salary(): basic + 5,000 allowance
↑
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 classinterface
Can be created with new?nono
Containssome code + abstract methodsonly method signatures (+ constants)
A class can useone (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;
  • Laravel uses traits everywhere: HasFactory, Notifiable, SoftDeletes.
traits.php
REAL RUN
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

FeatureVersionWhat it does
readonly class8.2every property is readonly: perfect for value objects like Money
Typed class constants const string X8.3constants have types; child classes cannot change the type
#[\Override]8.3PHP checks that the parent really has this method; catches renamed/misspelled methods
Foo::{$name}8.3fetch 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).
index.phpsrc/Models/Student.phpsrc/Services/Sms.php
REAL RUN
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.
class NetBanking implements PaymentMethod { ... fee returns 10 ... }
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.
index.phpsrc/Models/Course.phpsrc/Models/Enrollment.phpsrc/Support/Money.php
REAL RUN
✍ 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().
  • ✔Abstract classes give shared code + required methods; interfaces describe abilities.
  • ✔Polymorphism: code written for an interface works with every implementation.
  • ✔Traits share methods across unrelated classes.
  • ✔Enums (8.1) for fixed choices; readonly classes (8.2) for value objects.
  • ✔PHP 8.3: typed class constants, #[\Override], dynamic constant fetch; namespaces + autoload organise projects.
🏆

Module 14 complete!

You practised 10 real examples.

👉 Coming next

M15 Errors, Exceptions & Debugging: try/catch/finally, custom exceptions, logging and reading stack traces.
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
Complete PHP 8.3 Course  |  BrainBit Infotech, Ranchi
M15Where is this used in real work?

Good error handling is invisible to users

shop.example.in/pay.php
Fatal error: Uncaught PDOException: SQLSTATE[HY000] [2002] Connection refused in /var/www/html/db.php:4
Stack trace: #0 ...
shop.example.in/pay.php
🔧
We are fixing a small problem

Your money is safe. Please try again in 5 minutes.

Ref: ERR-8F2A

Left: no handling: scary for customers and it leaks file paths to attackers. Right: caught, logged with a reference number, friendly message.

🛡️

Security

Raw error messages reveal file paths, SQL and versions. Production sites log errors and show friendly pages.
💰

Money and data safety

Payment and stock updates use try/catch with rollback so a half-finished operation never corrupts data.
🔎

Faster fixing

Logs with time, message, file and line let developers fix bugs reported as "it did not work".
Complete PHP 8.3 Course  |  Part 4  |  Errors, Exceptions & Debugging
M15Concept

The kinds of PHP problems

TypeExampleStops the script?
Parse errormissing ; or }yes, nothing runs
Fatal error / Errorcalling an undefined functionyes
Warningfile not found, undefined variable/keyno
Deprecateda feature to be removed in future PHPno
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.
kinds.php
REAL RUN
Complete PHP 8.3 Course  |  Part 4  |  Errors, Exceptions & Debugging
M15Animated explainer

try, catch, finally

<?php
try {
    $f = openFile('fees.csv');
    $total = readTotal($f);   // throws!
    echo "Total: $total";
} catch (RuntimeException $e) {
    echo "Sorry: " . $e->getMessage();
} finally {
    closeFile($f);
}
echo "Page continues";
1. try: run the risky code
2. readTotal() throws an exception: PHP jumps out immediately; echo "Total" is skipped
3. catch with a matching type handles it
4. finally runs in every case: success or failure
5. The script continues normally
Complete PHP 8.3 Course  |  Part 4  |  Errors, Exceptions & Debugging
M15Concept

The exception family

Throwable
Error
Exception
  • Error: PHP engine problems: TypeError, ValueError, DivisionByZeroError, UnhandledMatchError.
  • Exception: problems your code reports: RuntimeException, InvalidArgumentException, JsonException, PDOException.
  • Catch several: catch (TypeError | ValueError $e)
  • Useful methods: getMessage(), getCode(), getFile(), getLine(), getPrevious()
family.php
REAL RUN
Complete PHP 8.3 Course  |  Part 4  |  Errors, Exceptions & Debugging
M15Concept

Custom exceptions and throw

  • Make your own: class InsufficientBalanceException extends RuntimeException {}
  • Add useful data (like the shortfall) as properties.
  • throw new ... anywhere; in PHP 8 throw is also an expression: $id = $_GET['id'] ?? throw new ...;
  • Wrap low-level errors with a clear message and keep the original as $previous.
custom.php
REAL RUN
Complete PHP 8.3 Course  |  Part 4  |  Errors, Exceptions & Debugging
M15Concept

Logging and global handlers

  • error_log($msg, 3, 'app.log') appends a line to your log file.
  • set_exception_handler(fn): last chance for any uncaught exception. Log it, show a friendly page.
  • set_error_handler(fn): turn warnings into exceptions so they cannot be ignored.
  • Give users a short reference id; keep the details in the log.
handlers.php
REAL RUN
Complete PHP 8.3 Course  |  Part 4  |  Errors, Exceptions & Debugging
M15Practice 1 of 10  •  Easy

Example 1: Divide by zero caught

● Easy💼 Real project: Average and percentage calculations
Dividing by zero with intdiv or % throws DivisionByZeroError. Catching it lets a report show "N/A" instead of crashing.
average.php
REAL RUN
✍ Try it yourself Use / instead of intdiv. Does it still throw in PHP 8?
Yes: in PHP 8, 1 / 0 also throws DivisionByZeroError (PHP 7 only gave a warning).
Complete PHP 8.3 Course  |  Part 4  |  Errors, Exceptions & Debugging
M15Practice 2 of 10  •  Easy

Example 2: Missing file handled

● Easy💼 Real project: Loading settings and templates
Check before reading, or turn the failure into a clear exception. The program continues with default settings.
settings.php
REAL RUN
✍ Try it yourself Create settings.json with broken JSON. Which exception is thrown now? Is it caught?
JsonException, which extends Exception, not RuntimeException: so it is NOT caught. Catch JsonException too.
Complete PHP 8.3 Course  |  Part 4  |  Errors, Exceptions & Debugging
M15Practice 3 of 10  •  Easy

Example 3: finally to close a file

● Easy💼 Real project: Cleaning up connections and locks
finally runs whether the try succeeded or failed, so the file is always closed. The log lines show the order of events.
finally.php
REAL RUN
✍ Try it yourself Fix the CSV (Salt,15). In which order are the lines printed now?
opened, closed, then Total: 35. finally runs even when the function returns normally.
Complete PHP 8.3 Course  |  Part 4  |  Errors, Exceptions & Debugging
M15Practice 4 of 10  •  Easy

Example 4: Validate age with an exception

● Easy💼 Real project: Eligibility checks in forms
A function throws InvalidArgumentException for bad input. The calling code decides how to show the message.
age.php
REAL RUN
✍ Try it yourself Add a check: age must be a whole number from the form (it comes as a string).
filter_var($input, FILTER_VALIDATE_INT) === false -> throw new InvalidArgumentException.
Complete PHP 8.3 Course  |  Part 4  |  Errors, Exceptions & Debugging
M15Practice 5 of 10  •  Easy

Example 5: TypeError demo

● Easy💼 Real project: Why strict_types catches bugs early
With strict_types=1, passing the wrong type throws a TypeError that we can catch, log and report.
types.php
REAL RUN
✍ Try it yourself Remove the declare line. Which inputs work now, and is that good or bad?
"750" is silently converted and works; null still fails. Silent conversion can hide bugs from form input.
Complete PHP 8.3 Course  |  Part 4  |  Errors, Exceptions & Debugging
M15Practice 6 of 10  •  Medium

Example 6: Custom InsufficientBalanceException

● Medium💼 Real project: Wallets, prepaid cards, mess accounts
A custom exception carries extra data (balance and shortfall), so the screen can say exactly how much more to add.
wallet.php
REAL RUN
✍ Try it yourself Add a topUp() method and retry the dinner after topping up Rs 100.
public function topUp(float $a): void { $this->balance += $a; }
Complete PHP 8.3 Course  |  Part 4  |  Errors, Exceptions & Debugging
M15Practice 7 of 10  •  Medium

Example 7: Global error page + log file

● Medium💼 Real project: Production websites
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.
Complete PHP 8.3 Course  |  Part 4  |  Errors, Exceptions & Debugging
M15Practice 8 of 10  •  Medium

Example 8: Retry with exceptions

● 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.
Complete PHP 8.3 Course  |  Part 4  |  Errors, Exceptions & Debugging
M15Practice 9 of 10  •  Hard

Example 9: Form validation with an exception bag

● 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; }
Complete PHP 8.3 Course  |  Part 4  |  Errors, Exceptions & Debugging
M15Practice 10 of 10  •  Hard

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.
Complete PHP 8.3 Course  |  Part 4  |  Errors, Exceptions & Debugging
M15Check your understanding

Quick Quiz

Click an answer. Wrong answers shake; the right one turns green and explains why.

Q1. Which block always runs?
✔ finally runs after success and after failure.
Q2. What should production sites do with error details?
✔ display_errors=Off, log_errors=On.
Q3. TypeError belongs to which branch?
✔ Both Error and Exception implement Throwable.
🎯
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  |  Errors, Exceptions & Debugging
M15Module summary

Recap: Errors, Exceptions & Debugging

What you learned in M15

  • ✔Parse and fatal errors stop the script; warnings and deprecations do not.
  • ✔Development shows errors; production logs them (display_errors Off, log_errors On).
  • ✔try / catch / finally; catch specific types, several with |.
  • ✔Throwable = Error (engine) + Exception (your code); custom exceptions carry extra data.
  • ✔set_exception_handler + error_log give friendly pages with reference ids.
  • ✔Retries and rollbacks keep real workflows safe.
🏆

Module 15 complete!

You practised 10 real examples.

👉 Coming next

M16 MySQL & PDO: tables, SQL, prepared statements, joins, reports and transactions with a real database.
Complete PHP 8.3 Course  |  Part 4  |  Errors, Exceptions & Debugging
M16

MySQL & PDO

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
Complete PHP 8.3 Course  |  BrainBit Infotech, Ranchi
M16Where is this used in real work?

Behind every serious website is a database

localhost/phpmyadmin > brainbit > students
idnamecitymobilecourse_id
1Riya KumariRanchi98350111111
2Aman ToppoGumla70040222221
3Zoya KhanRanchi94310333332

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

🗃 brainbit database
 📋 courses
 📋 students
 📋 payments
idnamecitymobilecourse_id
1Riya KumariRanchi98350111111
2Aman ToppoGumla70040222221

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. 1
    Start Apache and MySQL in the XAMPP Control Panel.
  2. 2
    Open http://localhost/phpmyadmin. Click New, name the database brainbit, collation utf8mb4_unicode_ci, click Create.
  3. 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. 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. 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

TaskSQL
AddINSERT INTO students (name, city) VALUES ('Asha', 'Gaya')
ReadSELECT name, city FROM students WHERE city = 'Ranchi' ORDER BY name LIMIT 10
ChangeUPDATE students SET city = 'Hazaribagh' WHERE id = 3
RemoveDELETE FROM students WHERE id = 5
Count/sumSELECT 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.
  • DSN: mysql:host=localhost;dbname=brainbit;charset=utf8mb4
  • ERRMODE_EXCEPTION: SQL errors throw PDOException (never fail silently).
  • FETCH_ASSOC: rows come as associative arrays.
  • 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

✎ Code Lab