# Inserting Validated Form Data

An insert should accept input, validate it, store it with a prepared statement and report a useful result.

## Example form

~~~html
<form method="post">
  <label for="activity_name">Activity name</label>
  <input id="activity_name" name="activity_name" maxlength="100" required>

  <label for="capacity">Capacity</label>
  <input id="capacity" name="capacity" type="number" min="1" max="100" required>

  <button type="submit">Add activity</button>
</form>
~~~

Browser validation helps users, but PHP must validate again.

## Process the submission

~~~php
$name = trim($_POST["activity_name"] ?? "");
$capacity = filter_input(INPUT_POST, "capacity", FILTER_VALIDATE_INT);
$errors = [];

if ($name === "" || mb_strlen($name) > 100) {
    $errors[] = "Enter an activity name of 100 characters or fewer.";
}
if ($capacity === false || $capacity < 1 || $capacity > 100) {
    $errors[] = "Capacity must be from 1 to 100.";
}

if (!$errors) {
    $stmt = $pdo->prepare(
        "INSERT INTO activities (activity_name, capacity)
         VALUES (:name, :capacity)"
    );
    $stmt->execute(["name" => $name, "capacity" => $capacity]);
}
~~~

## Output safely

Escape values when redisplaying them:

~~~php
<?= htmlspecialchars($name, ENT_QUOTES, "UTF-8") ?>
~~~

## Check

- [ ] Required fields have labels.
- [ ] Server-side validation handles missing and invalid values.
- [ ] A prepared statement performs the insert.
- [ ] Success appears only after the database operation succeeds.
- [ ] Invalid input remains unstored.