Database design: keys, relationships and normalization
Design tables that avoid duplicated data: primary keys, foreign keys, one-to-many and many-to-many relationships.
Return data from MySQL as JSON, with correct headers and status codes.
<?php
// api/products.php
require __DIR__ . '/../db.php';
header('Content-Type: application/json; charset=utf-8');
function respond(int $code, array $data): never
{
http_response_code($code);
echo json_encode($data, JSON_UNESCAPED_UNICODE);
exit;
}
if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
respond(405, ['error' => 'Method not allowed']);
}
$id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT);
if ($id) {
$s = $pdo->prepare('SELECT id, name, price FROM products WHERE id = ?');
$s->execute([$id]);
$row = $s->fetch();
$row ? respond(200, $row) : respond(404, ['error' => 'Not found']);
}
respond(200, $pdo->query('SELECT id, name, price FROM products LIMIT 50')->fetchAll());200 OK, 201 created, 204 no content400 bad request, 401 not logged in, 403 not allowed, 404 not found, 422 validation failed405 wrong method, 429 too many requests, 500 server errorDesign tables that avoid duplicated data: primary keys, foreign keys, one-to-many and many-to-many relationships.
A folder layout and a few habits that keep a growing PHP site tidy, secure and easy to maintain.