PHP MySQL CRUD with AJAX and Fetch
A CRUD interface uses asynchronous requests to create, read, update, and delete records. Keep database access on the server and expose narrow endpoints rather than allowing the browser to construct SQL.
Read records with PDO
$pdo = new PDO($dsn, $user, $password, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
]);
$stmt = $pdo->prepare('SELECT id, name FROM items ORDER BY id DESC LIMIT 50');
$stmt->execute();
$items = $stmt->fetchAll();
header('Content-Type: application/json; charset=utf-8');
echo json_encode($items);
Separate each operation
Use GET for reading, POST for creating, and deliberate methods or action endpoints for updates and deletes. Validate identifiers as integers and check that the target record exists.
Protect mutations
Require authentication and authorization, validate all fields, use prepared statements, and protect cookie-authenticated state changes with CSRF tokens. Return consistent JSON and HTTP status codes. Never rely on hiding a button as access control.