Using a PHP CRUD class simplifies database operations by encapsulating Create, Read, Update, and Delete logic into a reusable object-oriented structure.
A CRUD class typically maintains a database connection, table name, and exposes methods for each database operation.
// 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 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();
The class performs secure database operations while keeping application code clean and readable.