← Back to Chapters

PHP CRUD Class

? PHP CRUD Class

? Quick Overview

Using a PHP CRUD class simplifies database operations by encapsulating Create, Read, Update, and Delete logic into a reusable object-oriented structure.

? Key Concepts

  • Encapsulation of database logic
  • Reusable object-oriented design
  • Secure prepared statements
  • Cleaner application architecture

? Syntax / Theory

A CRUD class typically maintains a database connection, table name, and exposes methods for each database operation.

? Code Example – CRUD Class

? View Code Example
// PHP CRUD class using MySQLi
class User {
private $conn;
private $table = "users";

public function __construct($db) {
$this->conn = $db;
}

public function create($first_name,$last_name,$email) {
$stmt = $this->conn->prepare("INSERT INTO ".$this->table." (first_name,last_name,email) VALUES (?,?,?)");
$stmt->bind_param("sss",$first_name,$last_name,$email);
return $stmt->execute();
}

public function read() {
$sql = "SELECT * FROM ".$this->table;
return $this->conn->query($sql);
}

public function update($id,$first_name,$last_name,$email) {
$stmt = $this->conn->prepare("UPDATE ".$this->table." SET first_name=?,last_name=?,email=? WHERE id=?");
$stmt->bind_param("sssi",$first_name,$last_name,$email,$id);
return $stmt->execute();
}

public function delete($id) {
$stmt = $this->conn->prepare("DELETE FROM ".$this->table." WHERE id=?");
$stmt->bind_param("i",$id);
return $stmt->execute();
}
}

? Using the CRUD Class

? View Code Example
// Using the CRUD class in application code
$conn = new mysqli("localhost","username","password","myDB");
if ($conn->connect_error) {
die("Connection failed");
}

$user = new User($conn);
$user->create("John","Doe","john.doe@example.com");

$result = $user->read();
while($row = $result->fetch_assoc()) {
echo $row["first_name"];
}

$user->update(1,"Jane","Doe","jane.doe@example.com");
$user->delete(1);
$conn->close();

? Live Output / Explanation

The class performs secure database operations while keeping application code clean and readable.

? Use Cases

  • User management systems
  • Admin dashboards
  • Product catalogs
  • Any database-driven PHP application

✅ Tips & Best Practices

  • Always validate user input
  • Reuse CRUD classes across modules
  • Use exception handling for robustness

? Try It Yourself

  • Create a CRUD class for products
  • Add pagination support
  • Implement search functionality