Master PHPUnit Testing with MariaDB Integration for Developers

PHPUnit Tutorial for Beginners
PHPUnit Tutorial for Beginners

Live stream set for 2026-01-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.

Introduction

PHPUnit is an essential tool for testing PHP code to ensure it behaves as expected. In this beginner-level guide, we’ll walk you through setting up a basic WordPress plugin that connects to an existing MariaDB database table named “people”. This tutorial will cover connecting to the database, retrieving data, updating records, inserting new records, and deleting records.

Prerequisites

  • Basic understanding of PHP.
  • A WordPress installation.
  • MariaDB server with the “people” table set up.

Step 1: Setting Up PHPUnit in WordPress

First, you need to install PHPUnit in your WordPress environment. You can use Composer for this:

composer require --dev phpunit/phpunit ^9

Step 2: Creating a Basic Plugin Structure

Create a new folder named people-manager in the wp-content/plugins/ directory of your WordPress installation. Inside this folder, create the following files:

  • plugin.php
  • db.php
  • views/list-people.php
  • tests/TestPeopleManager.php

Step 3: Connecting to MariaDB

Create a file named db.php in the people-manager/ directory and add the following code:

<?php
class PeopleManager {
    private $conn;

    public function __construct($servername, $username, $password, $dbname) {
        $this->conn = new mysqli($servername, $username, $password, $dbname);
        if ($this->conn->connect_error) {
            die("Connection failed: " . $this->conn->connect_error);
        }
    }

    public function getAllPeople() {
        $sql = "SELECT * FROM people";
        $result = $this->conn->query($sql);

        $people = [];
        if ($result->num_rows > 0) {
            while ($row = $result->fetch_assoc()) {
                $people[] = $row;
            }
        }

        return $people;
    }

    public function updatePerson($id, $username, $name, $age, $verified) {
        $sql = "UPDATE people SET username='$username', name='$name', age=$age, verified=$verified WHERE id=$id";
        if ($this->conn->query($sql) === TRUE) {
            return true;
        } else {
            return false;
        }
    }

    public function insertPerson($username, $name, $age, $verified) {
        $sql = "INSERT INTO people (username, name, age, verified) VALUES ('$username', '$name', $age, $verified)";
        if ($this->conn->query($sql) === TRUE) {
            return true;
        } else {
            return false;
        }
    }

    public function deletePerson($id) {
        $sql = "DELETE FROM people WHERE id=$id";
        if ($this->conn->query($sql) === TRUE) {
            return true;
        } else {
            return false;
        }
    }

    public function closeConnection() {
        $this->conn->close();
    }
}
?>

Step 4: Displaying People Data

Create a file named list-people.php in the people-manager/views/ directory and add the following code:

<?php
if (!defined('ABSPATH')) exit; // Exit if accessed directly

require_once 'db.php';

$servername = 'your_servername';
$username = 'your_username';
$password = 'your_password';
$dbname = 'your_database';

$peopleManager = new PeopleManager($servername, $username, $password, $dbname);
$people = $peopleManager->getAllPeople();
?>

<table>
    <tr>
        <th>ID</th>
        <th>Username</th>
        <th>Name</th>
        <th>Age</th>
        <th>Verified</th>
        <th>Action</th>
    </tr>
    <?php foreach ($people as $person): ?>
        <tr>
            <td><?php echo $person['id']; ?></td>
            <td><?php echo $person['username']; ?></td>
            <td><?php echo $person['name']; ?></td>
            <td><?php echo $person['age']; ?></td>
            <td><?php echo $person['verified'] ? 'Yes' : 'No'; ?></td>
            <td>
                <a href="update.php?id=<?php echo $person['id']; ?>">Update</a> |
                <a href="delete.php?id=<?php echo $person['id']; ?>">Delete</a>
            </td>
        </tr>
    <?php endforeach; ?>
</table>

<?php
$peopleManager->closeConnection();
?>

Step 5: Writing a Test Case

Create a file named TestPeopleManager.php in the people-manager/tests/ directory and add the following code:

<?php
use PHPUnit\Framework\TestCase;

class TestPeopleManager extends TestCase {
    public function testGetAllPeople() {
        $servername = 'your_servername';
        $username = 'your_username';
        $password = 'your_password';
        $dbname = 'your_database';

        $peopleManager = new PeopleManager($servername, $username, $password, $dbname);
        $people = $peopleManager->getAllPeople();

        $this->assertNotEmpty($people);
    }
}
?>

Step 6: Running the Tests

Navigate to your WordPress admin area and use the PHPUnit plugin or run tests from the command line:

./vendor/bin/phpunit people-manager/tests/

Screenshots and Screencast Tutorial

People Directory Entry
Web Browser Displaying People Directory Entry Results

People Directory Update
Web Browser Displaying People Directory Update Form

People Directory Updated
Web Browser Displaying People Directory Updated Results

People Directory SQL
Gnome Text Editor Displaying People Directory SQL Code

People Directory Code
Gnome Text Editor Displaying People Directory Database Code

PHPUnit Install
Command Line PHP Compose Installing PHPUnit

PHPUnit Tests
Command Line PHP PHPUnit Test Results

Screencast Of PHPUnit Test

Conclusion

This tutorial provides a basic introduction to integrating PHPUnit with a MariaDB database in a WordPress plugin. You can expand this application by adding more features, such as user authentication, form validation, and more sophisticated error handling.

Feel free to ask any questions or share your thoughts below!

Recommended Resources:

Disclosure: Some of the links above are referral (affiliate) links. I may earn a commission if you purchase through them - at no extra cost to you.

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 *