PHP Database PDO For Custom CRUD MVC App

Master PHP PDO!
Master PHP PDO!

Live stream set for 2025-09-01 at 14:00:00 Eastern

Ask questions in the live chat about any programming or lifestyle topic.

This livestream will be on YouTube or you can watch below.

Getting Started with PHP PDO Using MVC: Connect to MariaDB and Perform CRUD

Learning how to connect PHP to a MariaDB database using PDO (PHP Data Objects) is a fundamental skill for beginner developers. In this post, we’ll create a basic MVC (Model-View-Controller) application that connects to an existing MariaDB table called people, and allows us to:

  • Display all people in an HTML table
  • Insert new records
  • Update existing records
  • Delete records

This is a beginner-friendly project and a great way to start learning modern PHP development practices.

Requirements

  • PHP 8.2 or higher
  • MariaDB (or MySQL)
  • Apache/Nginx or localhost setup (e.g., XAMPP, MAMP)
  • Basic knowledge of HTML & PHP

Database Structure

You’ll need a table named people with the following columns:

Column Type
id INT, AUTO_INCREMENT, PRIMARY KEY
username VARCHAR(50)
name VARCHAR(100)
age INT
verified BOOLEAN

Project Structure

 /people-mvc/
 ├── config/
 │   └── database.php
 ├── controllers/
 │   └── PeopleController.php
 ├── models/
 │   └── Person.php
 ├── views/
 │   └── people.php
 ├── index.php
 └── style.css

1. Database Connection (PDO)

config/database.php

class Database {
    private $host = "localhost";
    private $db_name = "your_database";
    private $username = "your_user";
    private $password = "your_password";
    public $conn;

    public function connect() {
        $this->conn = null;
        try {
            $this->conn = new PDO(
                "mysql:host={$this->host};dbname={$this->db_name}",
                $this->username,
                $this->password
            );
            $this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        } catch(PDOException $e) {
            echo "Connection error: " . $e->getMessage();
        }
        return $this->conn;
    }
}

2. Person Model

models/Person.php

require_once 'config/database.php';

class Person {
    private $conn;

    public function __construct() {
        $db = new Database();
        $this->conn = $db->connect();
    }

    public function getAll() {
        $stmt = $this->conn->prepare("SELECT * FROM people");
        $stmt->execute();
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }

    public function insert($username, $name, $age, $verified) {
        $stmt = $this->conn->prepare("INSERT INTO people (username, name, age, verified) VALUES (?, ?, ?, ?)");
        return $stmt->execute([$username, $name, $age, $verified]);
    }

    public function update($id, $username, $name, $age, $verified) {
        $stmt = $this->conn->prepare("UPDATE people SET username = ?, name = ?, age = ?, verified = ? WHERE id = ?");
        return $stmt->execute([$username, $name, $age, $verified, $id]);
    }

    public function delete($id) {
        $stmt = $this->conn->prepare("DELETE FROM people WHERE id = ?");
        return $stmt->execute([$id]);
    }
}

3. Controller Logic

controllers/PeopleController.php

require_once 'models/Person.php';

$person = new Person();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['insert'])) {
        $person->insert($_POST['username'], $_POST['name'], $_POST['age'], isset($_POST['verified']));
    }
    if (isset($_POST['update'])) {
        $person->update($_POST['id'], $_POST['username'], $_POST['name'], $_POST['age'], isset($_POST['verified']));
    }
    if (isset($_POST['delete'])) {
        $person->delete($_POST['id']);
    }
}

$data = $person->getAll();
include 'views/people.php';

4. View (HTML Table Output)

views/people.php

<!DOCTYPE html>
<html>
<head>
    <title>People Table</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
<h2>People List</h2>
<table border="1">
    <tr>
        <th>ID</th><th>Username</th><th>Name</th><th>Age</th><th>Verified</th><th>Actions</th>
    </tr>
    <?php foreach ($data as $row): ?>
    <tr>
        <form method="post">
            <input type="hidden" name="id" value="<?= $row['id'] ?>">
            <td><?= $row['id'] ?></td>
            <td><input type="text" name="username" value="<?= $row['username'] ?>"></td>
            <td><input type="text" name="name" value="<?= $row['name'] ?>"></td>
            <td><input type="number" name="age" value="<?= $row['age'] ?>"></td>
            <td><input type="checkbox" name="verified" <?= $row['verified'] ? 'checked' : '' ?>></td>
            <td>
                <button name="update">Update</button>
                <button name="delete" onclick="return confirm('Delete this record?')">Delete</button>
            </td>
        </form>
    </tr>
    <?php endforeach; ?>
    <tr>
        <form method="post">
            <td>#</td>
            <td><input type="text" name="username"></td>
            <td><input type="text" name="name"></td>
            <td><input type="number" name="age"></td>
            <td><input type="checkbox" name="verified"></td>
            <td><button name="insert">Insert</button></td>
        </form>
    </tr>
</table>
</body>
</html>

5. Entry Point

index.php

<?php
require_once 'controllers/PeopleController.php';

[/php]

Optional: Simple CSS

style.css

body {
    font-family: Roboto, sans-serif;
    padding: 20px;
}

table {
    width: 100%;
    border-collapse: collapse;
}

td, th {
    padding: 8px;
    text-align: center;
}

6: Running Your Application

To see the result:

  1. Place all the files in your web server directory.
  2. Make sure your MariaDB database is running and contains a people table with the columns id, username, name, age, and verified.
  3. Open the index.php file in your browser to see the data displayed in an HTML table.

Screenshots And Screencast

Custom Database Config
Gnome Text Editor Displaying App Database Configuration File

Custom People Controller
Gnome Text Editor Displaying Custom People Controller

Custom People Model
Gnome Text Editor Displaying Custom People Model

Custom People View
Gnome Text Editor Displaying App View File

Custom People Index
Gnome Text Editor Displaying App Index File

Created Person Result
Web Browser Displaying Created Person Result

Remove Person Prompt
Web Browser Displaying Remove Person Prompt

Tempest Custom View Records In Web Browser

Conclusion

This simple PHP PDO MVC application will help you understand how to interact with databases using PDO and build an MVC structure for easier maintenance and scaling. Now, you can add, update, and delete records from your database with ease!

If you’re eager to expand your knowledge, don’t forget to check out my book on learning PHP and the Learning PHP course.

I am also available for one-on-one tutorials and assistance with updating or migrating PHP and database applications. Feel free to contact me here if you need personalized help.

About Edward

Edward is a software engineer, web developer, and author dedicated to helping people achieve their personal and professional goals through actionable advice and real-world tools.

As the author of impactful books including Learning JavaScript, Learning Python, Learning PHP, Mastering Blender Python API, and fiction The Algorithmic Serpent, Edward writes with a focus on personal growth, entrepreneurship, and practical success strategies. His work is designed to guide, motivate, and empower.

In addition to writing, Edward offers professional "full-stack development," "database design," "1-on-1 tutoring," "consulting sessions,", tailored to help you take the next step. Whether you are launching a business, developing a brand, or leveling up your mindset, Edward will be there to support you.

Edward also offers online courses designed to deepen your learning and accelerate your progress. Explore the programming on languages like JavaScript, Python and PHP to find the perfect fit for your journey.

📚 Explore His Books – Visit the Book Shop to grab your copies today.
💼 Need Support? – Learn more about Services and the ways to benefit from his expertise.
🎓 Ready to Learn? – Check out his Online Courses to turn your ideas into results.

Leave a Reply

Your email address will not be published. Required fields are marked *