PHP and MariaDB: Insert form data with a prepared statement

To save a PHP form to MariaDB, validate the submitted values on the server, then bind them to placeholders in INSERT. This example stores a first name, last name, and hire date, then reports the generated ID after an HTTP 303 redirect to a GET request.

Prepare the practice table and connection settings

You need mysqli, mbstring, and a MariaDB database named learning. See the mysqli connection guide for setup. Run the SQL once in a fresh practice database. If the name is taken, choose a separate practice database. The setup account needs CREATE. Give the application account the required INSERT access.

USE learning;
CREATE TABLE employees_insert_demo (
    id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
    first_name VARCHAR(50) NOT NULL,
    last_name VARCHAR(50) NOT NULL,
    hire_date DATE NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

MariaDB generates id with AUTO_INCREMENT. Each name field holds up to 50 characters and the hire date uses DATE. Create database-config.php and a public directory. Replace the sample settings and 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,
];

Open the form and save an employee

Save the example in UTF-8 as public/employee-add.php. From the practice directory, run php -S 127.0.0.1:8000 -t public and open http://127.0.0.1:8000/employee-add.php. Allow the session cookie and save the file without a BOM or leading output before the PHP opening tag.

<?php
session_start(['use_strict_mode' => true, 'cookie_httponly' => true, 'cookie_samesite' => 'Lax']);
header('Content-Type: text/html; charset=UTF-8');
if (!extension_loaded('mysqli') || !extension_loaded('mbstring')) {
    http_response_code(500);
    exit('The mysqli and mbstring extensions are required.');
}
$_SESSION['csrf'] ??= bin2hex(random_bytes(32));
$message = $_SESSION['flash'] ?? '';
unset($_SESSION['flash']);
$errors = [];
$firstName = $lastName = $hireDate = '';
function escapeText($value): string {
    return htmlspecialchars((string) $value, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $token = $_POST['csrf'] ?? null;
    if (!is_string($token) || !hash_equals($_SESSION['csrf'], $token)) {
        http_response_code(403);
        exit('Open the form again and submit it.');
    }
    $firstName = is_string($_POST['first_name'] ?? null) ? trim($_POST['first_name']) : '';
    $lastName = is_string($_POST['last_name'] ?? null) ? trim($_POST['last_name']) : '';
    $hireDate = is_string($_POST['hire_date'] ?? null) ? $_POST['hire_date'] : '';
    foreach ([$firstName, $lastName] as $name) {
        if (!mb_check_encoding($name, 'UTF-8') || $name === '' || mb_strlen($name, 'UTF-8') > 50) {
            $errors[] = 'Enter 1–50 valid UTF-8 characters for each name.';
            break;
        }
    }
    $date = preg_match('/^[0-9]{4}-[0-9]{2}-[0-9]{2}$/D', $hireDate)
        ? DateTimeImmutable::createFromFormat('!Y-m-d', $hireDate) : false;
    if (!$date || $date->format('Y-m-d') !== $hireDate || $hireDate < '1000-01-01') {
        $errors[] = 'Enter a valid hire date in YYYY-MM-DD format.';
    }
    if ($errors !== []) {
        http_response_code(422);
    } else {
        $link = $stmt = null;
        $saved = false;
        try {
            $c = require dirname(__DIR__) . '/database-config.php';
            mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
            $link = mysqli_connect($c['host'], $c['username'], $c['password'], $c['database'], $c['port']);
            mysqli_set_charset($link, 'utf8mb4');
            $stmt = mysqli_prepare($link,
                'INSERT INTO employees_insert_demo (first_name, last_name, hire_date) VALUES (?, ?, ?)');
            mysqli_stmt_bind_param($stmt, 'sss', $firstName, $lastName, $hireDate);
            mysqli_stmt_execute($stmt);
            $id = mysqli_insert_id($link);
            $saved = mysqli_stmt_affected_rows($stmt) === 1;
            if (!$saved) {
                throw new RuntimeException('Unexpected affected row count');
            }
        } catch (Throwable $e) {
            http_response_code(500);
            error_log('Employee insert failed. Code: ' . $e->getCode());
            $errors[] = 'The record could not be saved. Check the server log.';
        } finally {
            if ($stmt instanceof mysqli_stmt) {
                mysqli_stmt_close($stmt);
            }
            if ($link instanceof mysqli) {
                mysqli_close($link);
            }
        }
        if ($saved) {
            $_SESSION['flash'] = 'Saved. New ID: ' . $id;
            $_SESSION['csrf'] = bin2hex(random_bytes(32));
            header('Location: employee-add.php', true, 303);
            exit;
        }
    }
}
?>
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Employee form example</title>
</head>
<body>
  <h1>Add an employee</h1>
  <?php if ($message !== ''): ?><p><?= escapeText($message) ?></p><?php endif; ?>
  <?php foreach ($errors as $error): ?><p><?= escapeText($error) ?></p><?php endforeach; ?>
  <form action="employee-add.php" method="post">
    <input type="hidden" name="csrf" value="<?= escapeText($_SESSION['csrf']) ?>">
    <p><label>First name <input name="first_name" maxlength="50" required value="<?= escapeText($firstName) ?>"></label></p>
    <p><label>Last name <input name="last_name" maxlength="50" required value="<?= escapeText($lastName) ?>"></label></p>
    <p><label>Hire date <input type="date" name="hire_date" required value="<?= escapeText($hireDate) ?>"></label></p>
    <button type="submit">Save</button>
  </form>
</body>
</html>

Enter a fictional first and last name and 2025-03-01. On success, the page returns to the form and shows the new ID. Auto-incremented values can have gaps. A production form needs authentication, authorization, and HTTPS appropriate to the application.

Understand server validation and prepared INSERT

The browser’s required and maxlength help users. The server checks that names are valid UTF-8 strings of 1–50 code points. It checks the date format and the year range from 1000, then compares the formatted date with the input to reject normalized dates such as 2025-02-30. PHP Manual — DateTimeImmutable::createFromFormat()

VALUES (?, ?, ?) marks three value positions. sss binds three strings. A name containing an apostrophe travels as data, and table and column names remain in the SQL statement. Bind SQL values and escape redisplayed form values for HTML at their respective points of use. PHP Manual — mysqli_stmt_bind_param() PHP Manual — Prepared statements

Read the generated ID with mysqli_insert_id() on the same connection immediately after executing. A separate maximum-ID query can find another request’s row. This single-row INSERT checks that exactly one row was affected. PHP Manual — mysqli_insert_id() PHP Manual — mysqli_stmt_affected_rows()

Check CSRF and redirect to GET after saving

For cross-site request forgery (CSRF) protection, the form compares its token with a random token in the session using hash_equals(). A missing or mismatched token returns 403 before opening a database connection. Check the signed-in user’s permission separately. PHP Manual — session_start() PHP Manual — hash_equals()

On success the example stores a one-time message, rotates the token, and sends 303 before output. Refreshing the resulting GET page does not repeat the insert. Older tabs need a fresh token. Use a suitable unique key or request identifier if the business rules forbid duplicates. PHP Manual — header()

Verify stored rows and rejected submissions

SELECT id, first_name, last_name, hire_date
FROM learning.employees_insert_demo
ORDER BY id DESC LIMIT 5;

Check the names, date, and new ID in SQL. Invalid input should give 422 and a POST without a token 403, with no new row in either case. Database errors return 500 and a generic message. Consult the restricted server log for the code and stop the local server with Ctrl+C.