Skip to content
PHP Advanced — OOP, Sessions, PDO Database & Error Handling

PHP Advanced — OOP, Sessions, PDO Database & Error Handling

DodaTech Updated Jun 6, 2026 6 min read

Advanced PHP features unlock professional application development — object-oriented programming organizes code, PDO provides secure database access, and sessions maintain state across page requests.

What You’ll Learn

By the end of this tutorial, you’ll build an MVC-style application using OOP classes, PDO with prepared statements, session management, and proper exception handling.

Why Advanced PHP Matters

Real-world applications need structure. Durga Antivirus Pro uses OOP classes for threat detection engines, PDO for database queries, and sessions for user authentication. Doda Browser uses OOP for sync services and PDO for bookmark storage. DodaZIP uses file I/O extensively for archive operations. These patterns separate concerns, prevent SQL injection, and maintain state securely.

Advanced PHP Learning Path

    flowchart LR
  A[Forms] --> B[Advanced PHP]
  B --> C[Frameworks]
  B --> D[Laravel]
  B --> E{You Are Here}
  style E fill:#f90,color:#fff
  
Prerequisites: Complete PHP basics through forms. Knowledge of MySQL or any database helps. Understanding OOP concepts from other languages is beneficial.

OOP in PHP — Why Classes?

Think of a class as a blueprint and an object as the actual house built from that blueprint. The blueprint defines what every house has (walls, doors, windows) but each house (object) can have different values (blue walls, red door).

Classes & Objects

<?php
class User {
    // Properties (what a user has)
    public function __construct(
        public string $name,
        public string $email,
        private int $id = 0
    ) {}

    // Methods (what a user can do)
    public function getEmail(): string {
        return $this->email;
    }
}

$user = new User("Alice", "alice@example.com");
echo $user->name;  // Alice
?>

Line by line:

  • class User { } — the blueprint
  • public string $name — a public property (anyone can read/write)
  • private int $id — a private property (only this class can access)
  • __construct(...) — runs automatically when you create a new object
  • $this->name — refers to THIS object’s name property
  • new User(...) — builds a new object from the blueprint

Inheritance — Child Classes

<?php
class Animal {
    public function __construct(protected string $name) {}
    public function speak(): string {
        return "$this->name makes a sound";
    }
}

class Dog extends Animal {
    public function speak(): string {
        return "$this->name barks";
    }
}

$dog = new Dog("Rex");
echo $dog->speak();  // Rex barks
?>

extends means “is a kind of.” A Dog IS a kind of Animal. It inherits everything from Animal but can override methods.

PDO — Secure Database Access

PDO (PHP Data Objects) is a database abstraction layer. Never insert user input directly into SQL — use prepared statements.

<?php
$pdo = new PDO(
    "mysql:host=localhost;dbname=myapp;charset=utf8mb4",
    "root", "secret",
    [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    ]
);

// SAFE: prepared statement with placeholders
$stmt = $pdo->prepare(
    "SELECT * FROM users WHERE email = ? AND active = ?"
);
$stmt->execute([$_GET["email"], true]);
$user = $stmt->fetch();
?>

Why prepared statements? They separate SQL logic from data. The database knows “this is a query structure” and “this is just a value that can never change the structure.” SQL injection becomes impossible.

Transactions

<?php
try {
    $pdo->beginTransaction();
    $pdo->prepare("UPDATE accounts SET balance = balance - ? WHERE id = ?")
         ->execute([100, 1]);
    $pdo->prepare("UPDATE accounts SET balance = balance + ? WHERE id = ?")
         ->execute([100, 2]);
    $pdo->commit();
} catch (PDOException $e) {
    $pdo->rollBack();
}
?>

Transactions ensure either ALL operations succeed or NONE do — critical for money transfers, order processing, and any multi-step operation.

Sessions — Remembering Users

HTTP is stateless — each request is independent. Sessions bridge that gap by storing data on the server between requests:

<?php session_start();  // Must be before ANY output

$_SESSION["user_id"] = 42;
$_SESSION["username"] = "alice";

// Read in another page
echo $_SESSION["username"];  // alice

// Destroy on logout
session_destroy();
?>

Think of sessions like a locker at a gym. The server keeps the locker (session data) and gives the browser a key (session cookie). Each request shows the key, and the server opens the right locker.

Common Mistakes

1. Not Using Prepared Statements (SQL Injection)

// DANGEROUS
$sql = "SELECT * FROM users WHERE id = " . $_GET["id"];

// SAFE
$stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
$stmt->execute([$_GET["id"]]);

2. Storing Passwords in Plain Text

$hash = password_hash($_POST["password"], PASSWORD_BCRYPT, ["cost" => 12]);
// Verify with: password_verify($input, $hash)

3. Starting Sessions After Output

session_start() must be called before any HTML or whitespace is sent to the browser.

4. Forgetting parent::__construct

class Child extends Parent {
    public function __construct(string $extra) {
        parent::__construct();  // Don't skip this!
    }
}

5. Re-throwing Exceptions Without Previous

throw new RuntimeException("Error", 0, $e);  // Preserves the original exception chain

Practice Questions

1. What’s the difference between public, protected, and private?

public — accessible anywhere. protected — accessible in the class and subclasses. private — accessible only within the defining class.

2. Why use PDO prepared statements?

They prevent SQL injection by separating SQL structure from data. User input is treated as values, never as executable SQL.

3. How do sessions work in PHP?

PHP stores a session file on the server and sends a cookie with the session ID to the browser. On each request, PHP reads the session ID from the cookie and loads the corresponding data.

4. What’s the difference between an abstract class and an interface?

Abstract classes can have implemented methods; a class can extend only one. Interfaces are pure contracts (method signatures only); a class can implement multiple.

5. Challenge: Build a User model class with PDO that can create, find by ID, and list all users.

<?php
class UserModel {
    private PDO $pdo;
    public function __construct(PDO $pdo) { $this->pdo = $pdo; }
    public function create(string $name, string $email): array {
        $stmt = $this->pdo->prepare("INSERT INTO users (name, email) VALUES (?, ?)");
        $stmt->execute([$name, $email]);
        return $this->findById((int)$this->pdo->lastInsertId());
    }
    public function findById(int $id): ?array {
        $stmt = $this->pdo->prepare("SELECT * FROM users WHERE id = ?");
        $stmt->execute([$id]);
        return $stmt->fetch() ?: null;
    }
    public function findAll(): array {
        return $this->pdo->query("SELECT * FROM users ORDER BY name")->fetchAll();
    }
}
?>

FAQ

What is PDO and why use it?
PDO is a database abstraction layer that provides prepared statements (SQL injection protection), multiple database support, transactions, and consistent error handling.
How do I store passwords securely?
Use password_hash() with PASSWORD_BCRYPT. Verify with password_verify(). Never use MD5, SHA1, or plain text.
What is autoloading?
Composer’s autoloader loads classes automatically based on namespace and PSR-4 mapping — no more require_once for every file.
What are traits?
Reusable code blocks that can be composed into classes. Like a copy-paste mechanism at the code level — useful for sharing methods across unrelated classes.

Try It Yourself

Create a User Management System with OOP and PDO. Use the code above as a starting point, connect to a database, and implement CRUD operations.

What’s Next

LessonDescription
https://tutorials.dodatech.com/backend/php/php-reference/Complete PHP cheatsheet
https://tutorials.dodatech.com/backend/php/laravel/Laravel PHP framework
https://tutorials.dodatech.com/backend/php/symfony/Symfony PHP framework
MySQLDatabase design and queries
MVCMVC architectural pattern

What’s Next

Congratulations on completing this Php Advanced tutorial! Here’s where to go from here:

  • Practice daily — Consistency is more important than long study sessions
  • Build a project — Apply what you learned by building something real
  • Explore related topics — Check out other tutorials in the same category
  • Join the community — Discuss with other learners and share your progress

Remember: every expert was once a beginner. Keep coding!

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro