Overview
Reusable Create, Read, Update and Delete operations using prepared statements.
What this script does
This starter demonstrates the core implementation pattern. Adapt database fields, configuration and error handling to your application.
Source code
<?php
declare(strict_types=1);
function findPost(PDO $pdo, int $id): ?array {
$s=$pdo->prepare('SELECT id,title,body FROM posts WHERE id=:id LIMIT 1');
$s->execute(['id'=>$id]); return $s->fetch(PDO::FETCH_ASSOC) ?: null;
}
function createPost(PDO $pdo,string $title,string $body): int {
$s=$pdo->prepare('INSERT INTO posts(title,body,created_at) VALUES(:title,:body,NOW())');
$s->execute(['title'=>$title,'body'=>$body]); return (int)$pdo->lastInsertId();
}
function updatePost(PDO $pdo,int $id,string $title,string $body): bool {
$s=$pdo->prepare('UPDATE posts SET title=:title,body=:body WHERE id=:id');
return $s->execute(['title'=>$title,'body'=>$body,'id'=>$id]);
}
function deletePost(PDO $pdo,int $id): bool {
$s=$pdo->prepare('DELETE FROM posts WHERE id=:id'); return $s->execute(['id'=>$id]);
}
Download starter source: Download PHP PDO CRUD Starter source
Installation and customization
- Review the code and required PHP extensions.
- Configure database and storage settings outside the public web root where applicable.
- Add authorization, rate limiting and logging for public-facing endpoints.
- Test valid, invalid and boundary inputs before deployment.
> This is a learning starter, not a complete production application. Apply the security and deployment requirements of your project.