TExcelTAD
Home › PHP › PHP Mini Project

PHP Mini Project

Let's combine what you've learned into one small but realistic program: an inventory processor for a little shop. Every evening the shop exports its stock movements as plain text. Our script will:

  1. Parse the raw lines into structured records.
  2. Validate each record and collect errors instead of crashing.
  3. Store the valid movements in an SQLite database.
  4. Report current stock and items that need re-ordering.
  5. Export the result as JSON for another system.

We build it in steps. Each playground is complete and runnable on its own, so you can experiment with any stage.

The input format

Each line has four fields separated by |: the date, the product code, the movement type (IN for a delivery, OUT for a sale) and the quantity. Lines starting with # are comments.

text
# date      | sku     | type | qty
2025-06-02 | TEA-01  | IN   | 40
2025-06-02 | MUG-02  | IN   | 12
2025-06-03 | TEA-01  | OUT  | 15
2025-06-03 | CUP-07  | OUT  | three
2025-06-04 | MUG-02  | OUT  | 9
2025-06-04 | TEA-01  | BACK | 2
2025-06-05 | JAR-03  | IN   | 25
2025-06-05 | TEA-01  | OUT  | 18

Step 1 — Parse the lines

We use a heredoc for the input, split it into lines, skip blanks and comments, and turn each row into an associative array. array_map('trim', ...) cleans the spaces around every field.

php · try it yourself
<?php
$raw = <<<TXT
# date      | sku     | type | qty
2025-06-02 | TEA-01  | IN   | 40
2025-06-02 | MUG-02  | IN   | 12
2025-06-03 | TEA-01  | OUT  | 15
2025-06-03 | CUP-07  | OUT  | three

2025-06-04 | MUG-02  | OUT  | 9
TXT;

function parseLines(string $raw): array {
    $records = [];
    foreach (explode("\n", $raw) as $n => $line) {
        $line = trim($line);
        if ($line === '' || str_starts_with($line, '#')) {
            continue;
        }
        $fields = array_map('trim', explode('|', $line));
        $records[] = ['line' => $n + 1, 'fields' => $fields];
    }
    return $records;
}

foreach (parseLines($raw) as $r) {
    echo "line {$r['line']}: ", implode(' / ', $r['fields']), "\n";
}
line 2: 2025-06-02 / TEA-01 / IN / 40
line 3: 2025-06-02 / MUG-02 / IN / 12
line 4: 2025-06-03 / TEA-01 / OUT / 15
line 5: 2025-06-03 / CUP-07 / OUT / three
line 7: 2025-06-04 / MUG-02 / OUT / 9

Tip: We keep the original line number with every record. When validation fails later, a message like "line 5: …" saves the shop owner a lot of searching.

Step 2 — Validate into typed objects

Arrays of strings are easy to misuse, so valid rows become Movement objects: a readonly class with an enum for the type. Invalid rows produce an error message instead. The validator uses tools from earlier lessons — count(), DateTimeImmutable::createFromFormat(), preg_match(), filter_var() and Enum::tryFrom().

php · try it yourself
<?php
enum MoveType: string {
    case In = 'IN';
    case Out = 'OUT';

    public function sign(): int {
        return $this === self::In ? 1 : -1;
    }
}

final readonly class Movement {
    public function __construct(
        public string $date,
        public string $sku,
        public MoveType $type,
        public int $qty,
    ) {}
}

/** @return Movement|string a Movement, or an error message */
function validate(array $f): Movement|string {
    if (count($f) !== 4) {
        return 'expected 4 fields, got ' . count($f);
    }
    [$date, $sku, $type, $qty] = $f;

    $d = DateTimeImmutable::createFromFormat('!Y-m-d', $date);
    if ($d === false || $d->format('Y-m-d') !== $date) {
        return "invalid date '$date'";
    }
    if (!preg_match('/^[A-Z]{3}-\d{2}$/', $sku)) {
        return "invalid SKU '$sku'";
    }
    $moveType = MoveType::tryFrom($type);
    if ($moveType === null) {
        return "unknown type '$type'";
    }
    $amount = filter_var($qty, FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]);
    if ($amount === false) {
        return "quantity must be a positive whole number, got '$qty'";
    }
    return new Movement($date, $sku, $moveType, $amount);
}

$rows = [
    ['2025-06-02', 'TEA-01', 'IN', '40'],
    ['2025-06-03', 'CUP-07', 'OUT', 'three'],
    ['2025-06-04', 'TEA-01', 'BACK', '2'],
    ['2025-02-30', 'JAR-03', 'IN', '25'],
    ['2025-06-05', 'jar3', 'IN', '25'],
    ['2025-06-05', 'MUG-02'],
];
foreach ($rows as $row) {
    $result = validate($row);
    echo $result instanceof Movement
        ? "OK    {$result->sku} {$result->type->name} {$result->qty}\n"
        : "ERROR $result\n";
}
OK    TEA-01 In 40
ERROR quantity must be a positive whole number, got 'three'
ERROR unknown type 'BACK'
ERROR invalid date '2025-02-30'
ERROR invalid SKU 'jar3'
ERROR expected 4 fields, got 2

The date check deserves a second look: createFromFormat() happily turns 2025-02-30 into March 2nd, so we format the result again and compare it with the input. If they differ, the date didn't exist.

Step 3 — Store and report with SQLite

Now we put everything together. Valid movements are inserted with one prepared statement inside a transaction, and SQL does the arithmetic: SUM(qty * sign) gives the current stock per product. A small $reorderAt table defines the minimum stock for each product.

php · try it yourself
<?php
enum MoveType: string {
    case In = 'IN';
    case Out = 'OUT';
    public function sign(): int { return $this === self::In ? 1 : -1; }
}

$raw = <<<TXT
# date      | sku     | type | qty
2025-06-02 | TEA-01  | IN   | 40
2025-06-02 | MUG-02  | IN   | 12
2025-06-03 | TEA-01  | OUT  | 15
2025-06-03 | CUP-07  | OUT  | three
2025-06-04 | MUG-02  | OUT  | 9
2025-06-04 | TEA-01  | BACK | 2
2025-06-05 | JAR-03  | IN   | 25
2025-06-05 | TEA-01  | OUT  | 18
TXT;

$valid = [];
$errors = [];
foreach (explode("\n", $raw) as $n => $line) {
    if (trim($line) === '' || str_starts_with(trim($line), '#')) continue;
    [$date, $sku, $type, $qty] = array_map('trim', explode('|', $line)) + [null, null, null, null];
    $move = MoveType::tryFrom((string) $type);
    $amount = filter_var($qty, FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]);
    if ($move === null || $amount === false) {
        $errors[] = 'line ' . ($n + 1) . ": rejected '" . trim($line) . "'";
        continue;
    }
    $valid[] = [$date, $sku, $move->value, $amount * $move->sign()];
}

$pdo = new PDO('sqlite::memory:', options: [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
]);
$pdo->exec('CREATE TABLE movements (day TEXT, sku TEXT, type TEXT, delta INTEGER)');

$pdo->beginTransaction();
$insert = $pdo->prepare('INSERT INTO movements VALUES (?, ?, ?, ?)');
foreach ($valid as $row) {
    $insert->execute($row);
}
$pdo->commit();

$reorderAt = ['TEA-01' => 10, 'MUG-02' => 5, 'JAR-03' => 10];

echo "Imported ", count($valid), " movements, ", count($errors), " rejected\n";
foreach ($errors as $e) {
    echo "  $e\n";
}

echo "\nSKU      STOCK  STATUS\n";
$stock = $pdo->query('SELECT sku, SUM(delta) AS qty FROM movements GROUP BY sku ORDER BY sku')
             ->fetchAll(PDO::FETCH_KEY_PAIR);
foreach ($stock as $sku => $qty) {
    $status = $qty < ($reorderAt[$sku] ?? 0) ? 'REORDER' : 'ok';
    printf("%-8s %5d  %s\n", $sku, $qty, $status);
}
Imported 6 movements, 2 rejected
  line 5: rejected '2025-06-03 | CUP-07  | OUT  | three'
  line 7: rejected '2025-06-04 | TEA-01  | BACK | 2'

SKU      STOCK  STATUS
JAR-03      25  ok
MUG-02       3  REORDER
TEA-01       7  REORDER

Note: Storing outgoing movements as negative numbers (delta) keeps the report query trivial. This "signed amount" trick is common in bookkeeping and stock systems.

Step 4 — Export as JSON

Finally, other systems — a web dashboard, a supplier's ordering API — want the results as JSON. We build a plain PHP array and let json_encode() do the rest. The report date is fixed so the output is reproducible.

php · try it yourself
<?php
date_default_timezone_set('UTC');

$stock = ['JAR-03' => 25, 'MUG-02' => 3, 'TEA-01' => 7];
$reorderAt = ['TEA-01' => 10, 'MUG-02' => 5, 'JAR-03' => 10];
$errors = 2;

$toOrder = array_filter($stock, fn($qty, $sku) => $qty < $reorderAt[$sku], ARRAY_FILTER_USE_BOTH);

$report = [
    'generated' => (new DateTimeImmutable('2025-06-05 18:00:00'))->format(DATE_ATOM),
    'products'  => count($stock),
    'totalUnits'=> array_sum($stock),
    'rejectedLines' => $errors,
    'reorder'   => array_map(
        fn($sku) => ['sku' => $sku, 'have' => $stock[$sku], 'orderQty' => $reorderAt[$sku] * 2 - $stock[$sku]],
        array_keys($toOrder),
    ),
];

echo json_encode($report, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES), "\n";
{
    "generated": "2025-06-05T18:00:00+00:00",
    "products": 3,
    "totalUnits": 35,
    "rejectedLines": 2,
    "reorder": [
        {
            "sku": "MUG-02",
            "have": 3,
            "orderQty": 7
        },
        {
            "sku": "TEA-01",
            "have": 7,
            "orderQty": 13
        }
    ]
}

array_keys($toOrder) gives a list with keys 0, 1, …, so json_encode() produces a JSON array. If we had mapped over $toOrder directly, its string keys would have turned it into a JSON object.

Ideas to extend the project

Idea Lessons to revisit
Read the input from a file with file() and write the JSON with file_put_contents() File Handling
Move parsing, validation and storage into separate classes behind an interface Classes, Interfaces
Accept the lines through an HTML form and show errors next to the field Form Handling, Form Validation
Add a products table with names and prices and JOIN it in the report PDO, CRUD
Throw a custom ImportException when more than half of the lines are invalid Exceptions

Test yourself

Why does the validator re-format the parsed date and compare it with the input?

  1. To change the time zone
  2. Because createFromFormat() rolls impossible dates like 2025-02-30 over into the next month
  3. To remove the time part
  4. Because createFromFormat() always returns false

What is the benefit of inserting all rows inside beginTransaction() / commit()?

  1. Rows are automatically validated
  2. Either all rows are saved or none, and bulk inserts are faster
  3. It prevents SQL injection
  4. It makes SUM() work

json_encode(['a' => 1, 'b' => 2]) produces which JSON type?

  1. An array [1,2]
  2. An object {"a":1,"b":2}
  3. A string
  4. null