PHP and MariaDB: Fetch rows and display query results

To display MariaDB data in PHP, run SELECT and read rows with mysqli_fetch_assoc(). Loop for multiple rows and read a COUNT(*) result once. Escape strings with htmlspecialchars() when inserting them into HTML.

Prepare employee and salary sample data

Start with mysqli, a running MariaDB server, a learning database, and an account. See the mysqli connection guide to set up the connection. If the table names are taken, pick a separate practice database and update both SQL and PHP settings. Use create and insert privileges for setup and grant the read-only account only the necessary SELECT access.

USE learning;
CREATE TABLE employees_demo (
    emp_no INT PRIMARY KEY,
    first_name VARCHAR(50) NOT NULL,
    last_name VARCHAR(50) NOT NULL,
    hire_date DATE NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
CREATE TABLE salaries_demo (
    emp_no INT NOT NULL,
    salary INT NOT NULL,
    valid_from DATE NOT NULL,
    valid_until DATE NOT NULL,
    PRIMARY KEY (emp_no, valid_from)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
INSERT INTO employees_demo VALUES
    (101, 'Min', 'Kim', '2023-03-01'),
    (102, 'Sujin', 'Park', '2024-07-01');
INSERT INTO salaries_demo VALUES
    (101, 50000, '2024-01-01', '2024-12-31'),
    (101, 55000, '2025-01-01', '2025-12-31'),
    (102, 48000, '2025-01-01', '2025-12-31');

The employee table stores one row per employee. The salary table stores one row per pay period. Two fictional employees and three salary records let you see how the join produces three rows for two people.

Keep configuration and shared code outside the document root

Create database-config.php, db.php, and the public directory. Save the configuration below in the first file and replace the example account and password placeholder. Keep the configuration outside public, version control, and public deployment packages.

<?php
return [
    'host' => '127.0.0.1',
    'username' => 'learning_user',
    'password' => 'REPLACE_WITH_YOUR_PRIVATE_PASSWORD',
    'database' => 'learning',
    'port' => 3306,
];

The second file, db.php, opens a strict-mode utf8mb4 connection and defines a helper for HTML text. Restrict access to server logs and turn off display_errors in production.

<?php
function openDatabase(): mysqli {
    if (!extension_loaded('mysqli')) {
        throw new RuntimeException('mysqli is required');
    }
    mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
    $c = require __DIR__ . '/database-config.php';
    $link = mysqli_connect($c['host'], $c['username'], $c['password'], $c['database'], $c['port']);
    try {
        mysqli_set_charset($link, 'utf8mb4');
    } catch (Throwable $e) {
        mysqli_close($link);
        throw $e;
    }
    return $link;
}
function escapeText($value): string {
    return htmlspecialchars((string) $value, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}

Display query rows in an HTML table

Save the third PHP file as public/employees.php. Run php -S 127.0.0.1:8000 -t public from the practice directory and visit http://127.0.0.1:8000/employees.php. The web root is public.

<?php
header('Content-Type: text/html; charset=UTF-8');
require dirname(__DIR__) . '/db.php';
$rows = [];
$total = 0;
$failed = false;
$link = null;
try {
    $link = openDatabase();
    $result = mysqli_query($link,
        'SELECT emp_no, first_name, last_name, hire_date
         FROM employees_demo ORDER BY emp_no LIMIT 5');
    while (is_array($row = mysqli_fetch_assoc($result))) {
        $rows[] = $row;
    }
    mysqli_free_result($result);
    if ($row === false) {
        throw new RuntimeException('Could not fetch the result row');
    }
    $countResult = mysqli_query($link, 'SELECT COUNT(*) AS total FROM employees_demo');
    $countRow = mysqli_fetch_assoc($countResult);
    $total = (int) $countRow['total'];
    mysqli_free_result($countResult);
} catch (Throwable $e) {
    http_response_code(500);
    error_log('Employee query failed. Code: ' . $e->getCode());
    $failed = true;
} finally {
    if ($link instanceof mysqli) {
        mysqli_close($link);
    }
}
?>
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Employee lookup example</title>
</head>
<body>
  <h1>Employees</h1>
  <?php if ($failed): ?>
    <p>Could not load the data.</p>
  <?php elseif ($rows === []): ?>
    <p>No employees found.</p>
  <?php else: ?>
    <p>Showing up to 5 of <?= $total ?> employees.</p>
    <div class="jb-table-scroll">
    <table class="jb-table-01">
      <thead><tr><th scope="col">ID</th><th scope="col">First name</th><th scope="col">Last name</th><th scope="col">Hire date</th></tr></thead>
      <tbody>
      <?php foreach ($rows as $row): ?>
        <tr>
          <td><?= escapeText($row['emp_no']) ?></td>
          <td><?= escapeText($row['first_name']) ?></td>
          <td><?= escapeText($row['last_name']) ?></td>
          <td><?= escapeText($row['hire_date']) ?></td>
        </tr>
      <?php endforeach; ?>
      </tbody>
    </table>
    </div>
  <?php endif; ?>
</body>
</html>

The example displays a total of two employees and rows 101 and 102. ORDER BY emp_no makes the ordering explicit and LIMIT 5 caps the list. For a larger result, paginate using the same ordering.

Read rows and count the full result separately

A successful SELECT through mysqli_query() returns a result set. mysqli_fetch_assoc() returns each row keyed by column name or alias, then null at the end. A false result indicates failure. Alias duplicate column names to keep values from overwriting each other. PHP Manual — mysqli_query() PHP Manual — mysqli_fetch_assoc()

The separate COUNT(*) query counts all employees even though the list stops at five. Without GROUP BY, it returns one row with total equal to zero for an empty table. COUNT(column) excludes NULL values. MariaDB — COUNT

escapeText() uses htmlspecialchars() for values in the HTML body. Special characters such as & and < in a name then appear as text. Apply the escaping at the point of HTML output. PHP Manual — htmlspecialchars()

Show salary history with LEFT JOIN

Save the fourth PHP file as public/salaries.php and open http://127.0.0.1:8000/salaries.php. The text/plain result shows 50000 and 55000 for employee 101 and 48000 for employee 102, ordered by employee and period.

<?php
header('Content-Type: text/plain; charset=UTF-8');
require dirname(__DIR__) . '/db.php';
$link = null;
try {
    $link = openDatabase();
    $result = mysqli_query($link,
        'SELECT e.emp_no, e.first_name, e.last_name,
                s.salary, s.valid_from, s.valid_until
         FROM employees_demo AS e
         LEFT JOIN salaries_demo AS s ON s.emp_no = e.emp_no
         ORDER BY e.emp_no, s.valid_from LIMIT 20');
    while (is_array($row = mysqli_fetch_assoc($result))) {
        echo $row['emp_no'], ' ', $row['first_name'], ' ', $row['last_name'], ' | ',
            $row['salary'] ?? 'No salary record', ' | ',
            $row['valid_from'] ?? '-', ' ~ ', $row['valid_until'] ?? '-', PHP_EOL;
    }
    mysqli_free_result($result);
    if ($row === false) {
        throw new RuntimeException('Could not fetch the result row');
    }
} catch (Throwable $e) {
    http_response_code(500);
    error_log('Salary query failed. Code: ' . $e->getCode());
    echo "Could not load the data.", PHP_EOL;
} finally {
    if ($link instanceof mysqli) {
        mysqli_close($link);
    }
}

With employees on the left of LEFT JOIN, a person without a salary record still appears, with NULL in the right-hand columns. The page prints the missing-record message and dashes. To find current pay, add a condition on the applicable dates. A global LIMIT 1 picks at most one row for the entire query. MariaDB — JOIN

Handle an empty list and a query failure

An empty employee table returns normally with the empty-list message. A query failure responds with HTTP 500 and a generic message, and writes the error code to the server log.

For queries receiving a search term or employee ID, bind the value to a prepared statement. SQL parameter binding and HTML escaping apply at different points. Press Ctrl+C to stop the test server when you are done. PHP Manual — Prepared statements